ยปCore Development>Code coverage>Lib/uu.py

Python code coverage for Lib/uu.py

#countcontent
1n/a#! /usr/bin/env python3
2n/a
3n/a# Copyright 1994 by Lance Ellinghouse
4n/a# Cathedral City, California Republic, United States of America.
5n/a# All Rights Reserved
6n/a# Permission to use, copy, modify, and distribute this software and its
7n/a# documentation for any purpose and without fee is hereby granted,
8n/a# provided that the above copyright notice appear in all copies and that
9n/a# both that copyright notice and this permission notice appear in
10n/a# supporting documentation, and that the name of Lance Ellinghouse
11n/a# not be used in advertising or publicity pertaining to distribution
12n/a# of the software without specific, written prior permission.
13n/a# LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
14n/a# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
15n/a# FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
16n/a# FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17n/a# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18n/a# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
19n/a# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20n/a#
21n/a# Modified by Jack Jansen, CWI, July 1995:
22n/a# - Use binascii module to do the actual line-by-line conversion
23n/a# between ascii and binary. This results in a 1000-fold speedup. The C
24n/a# version is still 5 times faster, though.
25n/a# - Arguments more compliant with python standard
26n/a
27n/a"""Implementation of the UUencode and UUdecode functions.
28n/a
29n/aencode(in_file, out_file [,name, mode])
30n/adecode(in_file [, out_file, mode])
31n/a"""
32n/a
33n/aimport binascii
34n/aimport os
35n/aimport sys
36n/a
37n/a__all__ = ["Error", "encode", "decode"]
38n/a
39n/aclass Error(Exception):
40n/a pass
41n/a
42n/adef encode(in_file, out_file, name=None, mode=None):
43n/a """Uuencode file"""
44n/a #
45n/a # If in_file is a pathname open it and change defaults
46n/a #
47n/a opened_files = []
48n/a try:
49n/a if in_file == '-':
50n/a in_file = sys.stdin.buffer
51n/a elif isinstance(in_file, str):
52n/a if name is None:
53n/a name = os.path.basename(in_file)
54n/a if mode is None:
55n/a try:
56n/a mode = os.stat(in_file).st_mode
57n/a except AttributeError:
58n/a pass
59n/a in_file = open(in_file, 'rb')
60n/a opened_files.append(in_file)
61n/a #
62n/a # Open out_file if it is a pathname
63n/a #
64n/a if out_file == '-':
65n/a out_file = sys.stdout.buffer
66n/a elif isinstance(out_file, str):
67n/a out_file = open(out_file, 'wb')
68n/a opened_files.append(out_file)
69n/a #
70n/a # Set defaults for name and mode
71n/a #
72n/a if name is None:
73n/a name = '-'
74n/a if mode is None:
75n/a mode = 0o666
76n/a #
77n/a # Write the data
78n/a #
79n/a out_file.write(('begin %o %s\n' % ((mode & 0o777), name)).encode("ascii"))
80n/a data = in_file.read(45)
81n/a while len(data) > 0:
82n/a out_file.write(binascii.b2a_uu(data))
83n/a data = in_file.read(45)
84n/a out_file.write(b' \nend\n')
85n/a finally:
86n/a for f in opened_files:
87n/a f.close()
88n/a
89n/a
90n/adef decode(in_file, out_file=None, mode=None, quiet=False):
91n/a """Decode uuencoded file"""
92n/a #
93n/a # Open the input file, if needed.
94n/a #
95n/a opened_files = []
96n/a if in_file == '-':
97n/a in_file = sys.stdin.buffer
98n/a elif isinstance(in_file, str):
99n/a in_file = open(in_file, 'rb')
100n/a opened_files.append(in_file)
101n/a
102n/a try:
103n/a #
104n/a # Read until a begin is encountered or we've exhausted the file
105n/a #
106n/a while True:
107n/a hdr = in_file.readline()
108n/a if not hdr:
109n/a raise Error('No valid begin line found in input file')
110n/a if not hdr.startswith(b'begin'):
111n/a continue
112n/a hdrfields = hdr.split(b' ', 2)
113n/a if len(hdrfields) == 3 and hdrfields[0] == b'begin':
114n/a try:
115n/a int(hdrfields[1], 8)
116n/a break
117n/a except ValueError:
118n/a pass
119n/a if out_file is None:
120n/a # If the filename isn't ASCII, what's up with that?!?
121n/a out_file = hdrfields[2].rstrip(b' \t\r\n\f').decode("ascii")
122n/a if os.path.exists(out_file):
123n/a raise Error('Cannot overwrite existing file: %s' % out_file)
124n/a if mode is None:
125n/a mode = int(hdrfields[1], 8)
126n/a #
127n/a # Open the output file
128n/a #
129n/a if out_file == '-':
130n/a out_file = sys.stdout.buffer
131n/a elif isinstance(out_file, str):
132n/a fp = open(out_file, 'wb')
133n/a try:
134n/a os.path.chmod(out_file, mode)
135n/a except AttributeError:
136n/a pass
137n/a out_file = fp
138n/a opened_files.append(out_file)
139n/a #
140n/a # Main decoding loop
141n/a #
142n/a s = in_file.readline()
143n/a while s and s.strip(b' \t\r\n\f') != b'end':
144n/a try:
145n/a data = binascii.a2b_uu(s)
146n/a except binascii.Error as v:
147n/a # Workaround for broken uuencoders by /Fredrik Lundh
148n/a nbytes = (((s[0]-32) & 63) * 4 + 5) // 3
149n/a data = binascii.a2b_uu(s[:nbytes])
150n/a if not quiet:
151n/a sys.stderr.write("Warning: %s\n" % v)
152n/a out_file.write(data)
153n/a s = in_file.readline()
154n/a if not s:
155n/a raise Error('Truncated input file')
156n/a finally:
157n/a for f in opened_files:
158n/a f.close()
159n/a
160n/adef test():
161n/a """uuencode/uudecode main program"""
162n/a
163n/a import optparse
164n/a parser = optparse.OptionParser(usage='usage: %prog [-d] [-t] [input [output]]')
165n/a parser.add_option('-d', '--decode', dest='decode', help='Decode (instead of encode)?', default=False, action='store_true')
166n/a parser.add_option('-t', '--text', dest='text', help='data is text, encoded format unix-compatible text?', default=False, action='store_true')
167n/a
168n/a (options, args) = parser.parse_args()
169n/a if len(args) > 2:
170n/a parser.error('incorrect number of arguments')
171n/a sys.exit(1)
172n/a
173n/a # Use the binary streams underlying stdin/stdout
174n/a input = sys.stdin.buffer
175n/a output = sys.stdout.buffer
176n/a if len(args) > 0:
177n/a input = args[0]
178n/a if len(args) > 1:
179n/a output = args[1]
180n/a
181n/a if options.decode:
182n/a if options.text:
183n/a if isinstance(output, str):
184n/a output = open(output, 'wb')
185n/a else:
186n/a print(sys.argv[0], ': cannot do -t to stdout')
187n/a sys.exit(1)
188n/a decode(input, output)
189n/a else:
190n/a if options.text:
191n/a if isinstance(input, str):
192n/a input = open(input, 'rb')
193n/a else:
194n/a print(sys.argv[0], ': cannot do -t from stdin')
195n/a sys.exit(1)
196n/a encode(input, output)
197n/a
198n/aif __name__ == '__main__':
199n/a test()