ยปCore Development>Code coverage>Lib/lib2to3/main.py

Python code coverage for Lib/lib2to3/main.py

#countcontent
1n/a"""
2n/aMain program for 2to3.
3n/a"""
4n/a
5n/afrom __future__ import with_statement, print_function
6n/a
7n/aimport sys
8n/aimport os
9n/aimport difflib
10n/aimport logging
11n/aimport shutil
12n/aimport optparse
13n/a
14n/afrom . import refactor
15n/a
16n/a
17n/adef diff_texts(a, b, filename):
18n/a """Return a unified diff of two strings."""
19n/a a = a.splitlines()
20n/a b = b.splitlines()
21n/a return difflib.unified_diff(a, b, filename, filename,
22n/a "(original)", "(refactored)",
23n/a lineterm="")
24n/a
25n/a
26n/aclass StdoutRefactoringTool(refactor.MultiprocessRefactoringTool):
27n/a """
28n/a A refactoring tool that can avoid overwriting its input files.
29n/a Prints output to stdout.
30n/a
31n/a Output files can optionally be written to a different directory and or
32n/a have an extra file suffix appended to their name for use in situations
33n/a where you do not want to replace the input files.
34n/a """
35n/a
36n/a def __init__(self, fixers, options, explicit, nobackups, show_diffs,
37n/a input_base_dir='', output_dir='', append_suffix=''):
38n/a """
39n/a Args:
40n/a fixers: A list of fixers to import.
41n/a options: A dict with RefactoringTool configuration.
42n/a explicit: A list of fixers to run even if they are explicit.
43n/a nobackups: If true no backup '.bak' files will be created for those
44n/a files that are being refactored.
45n/a show_diffs: Should diffs of the refactoring be printed to stdout?
46n/a input_base_dir: The base directory for all input files. This class
47n/a will strip this path prefix off of filenames before substituting
48n/a it with output_dir. Only meaningful if output_dir is supplied.
49n/a All files processed by refactor() must start with this path.
50n/a output_dir: If supplied, all converted files will be written into
51n/a this directory tree instead of input_base_dir.
52n/a append_suffix: If supplied, all files output by this tool will have
53n/a this appended to their filename. Useful for changing .py to
54n/a .py3 for example by passing append_suffix='3'.
55n/a """
56n/a self.nobackups = nobackups
57n/a self.show_diffs = show_diffs
58n/a if input_base_dir and not input_base_dir.endswith(os.sep):
59n/a input_base_dir += os.sep
60n/a self._input_base_dir = input_base_dir
61n/a self._output_dir = output_dir
62n/a self._append_suffix = append_suffix
63n/a super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
64n/a
65n/a def log_error(self, msg, *args, **kwargs):
66n/a self.errors.append((msg, args, kwargs))
67n/a self.logger.error(msg, *args, **kwargs)
68n/a
69n/a def write_file(self, new_text, filename, old_text, encoding):
70n/a orig_filename = filename
71n/a if self._output_dir:
72n/a if filename.startswith(self._input_base_dir):
73n/a filename = os.path.join(self._output_dir,
74n/a filename[len(self._input_base_dir):])
75n/a else:
76n/a raise ValueError('filename %s does not start with the '
77n/a 'input_base_dir %s' % (
78n/a filename, self._input_base_dir))
79n/a if self._append_suffix:
80n/a filename += self._append_suffix
81n/a if orig_filename != filename:
82n/a output_dir = os.path.dirname(filename)
83n/a if not os.path.isdir(output_dir):
84n/a os.makedirs(output_dir)
85n/a self.log_message('Writing converted %s to %s.', orig_filename,
86n/a filename)
87n/a if not self.nobackups:
88n/a # Make backup
89n/a backup = filename + ".bak"
90n/a if os.path.lexists(backup):
91n/a try:
92n/a os.remove(backup)
93n/a except OSError as err:
94n/a self.log_message("Can't remove backup %s", backup)
95n/a try:
96n/a os.rename(filename, backup)
97n/a except OSError as err:
98n/a self.log_message("Can't rename %s to %s", filename, backup)
99n/a # Actually write the new file
100n/a write = super(StdoutRefactoringTool, self).write_file
101n/a write(new_text, filename, old_text, encoding)
102n/a if not self.nobackups:
103n/a shutil.copymode(backup, filename)
104n/a if orig_filename != filename:
105n/a # Preserve the file mode in the new output directory.
106n/a shutil.copymode(orig_filename, filename)
107n/a
108n/a def print_output(self, old, new, filename, equal):
109n/a if equal:
110n/a self.log_message("No changes to %s", filename)
111n/a else:
112n/a self.log_message("Refactored %s", filename)
113n/a if self.show_diffs:
114n/a diff_lines = diff_texts(old, new, filename)
115n/a try:
116n/a if self.output_lock is not None:
117n/a with self.output_lock:
118n/a for line in diff_lines:
119n/a print(line)
120n/a sys.stdout.flush()
121n/a else:
122n/a for line in diff_lines:
123n/a print(line)
124n/a except UnicodeEncodeError:
125n/a warn("couldn't encode %s's diff for your terminal" %
126n/a (filename,))
127n/a return
128n/a
129n/adef warn(msg):
130n/a print("WARNING: %s" % (msg,), file=sys.stderr)
131n/a
132n/a
133n/adef main(fixer_pkg, args=None):
134n/a """Main program.
135n/a
136n/a Args:
137n/a fixer_pkg: the name of a package where the fixers are located.
138n/a args: optional; a list of command line arguments. If omitted,
139n/a sys.argv[1:] is used.
140n/a
141n/a Returns a suggested exit status (0, 1, 2).
142n/a """
143n/a # Set up option parser
144n/a parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
145n/a parser.add_option("-d", "--doctests_only", action="store_true",
146n/a help="Fix up doctests only")
147n/a parser.add_option("-f", "--fix", action="append", default=[],
148n/a help="Each FIX specifies a transformation; default: all")
149n/a parser.add_option("-j", "--processes", action="store", default=1,
150n/a type="int", help="Run 2to3 concurrently")
151n/a parser.add_option("-x", "--nofix", action="append", default=[],
152n/a help="Prevent a transformation from being run")
153n/a parser.add_option("-l", "--list-fixes", action="store_true",
154n/a help="List available transformations")
155n/a parser.add_option("-p", "--print-function", action="store_true",
156n/a help="Modify the grammar so that print() is a function")
157n/a parser.add_option("-v", "--verbose", action="store_true",
158n/a help="More verbose logging")
159n/a parser.add_option("--no-diffs", action="store_true",
160n/a help="Don't show diffs of the refactoring")
161n/a parser.add_option("-w", "--write", action="store_true",
162n/a help="Write back modified files")
163n/a parser.add_option("-n", "--nobackups", action="store_true", default=False,
164n/a help="Don't write backups for modified files")
165n/a parser.add_option("-o", "--output-dir", action="store", type="str",
166n/a default="", help="Put output files in this directory "
167n/a "instead of overwriting the input files. Requires -n.")
168n/a parser.add_option("-W", "--write-unchanged-files", action="store_true",
169n/a help="Also write files even if no changes were required"
170n/a " (useful with --output-dir); implies -w.")
171n/a parser.add_option("--add-suffix", action="store", type="str", default="",
172n/a help="Append this string to all output filenames."
173n/a " Requires -n if non-empty. "
174n/a "ex: --add-suffix='3' will generate .py3 files.")
175n/a
176n/a # Parse command line arguments
177n/a refactor_stdin = False
178n/a flags = {}
179n/a options, args = parser.parse_args(args)
180n/a if options.write_unchanged_files:
181n/a flags["write_unchanged_files"] = True
182n/a if not options.write:
183n/a warn("--write-unchanged-files/-W implies -w.")
184n/a options.write = True
185n/a # If we allowed these, the original files would be renamed to backup names
186n/a # but not replaced.
187n/a if options.output_dir and not options.nobackups:
188n/a parser.error("Can't use --output-dir/-o without -n.")
189n/a if options.add_suffix and not options.nobackups:
190n/a parser.error("Can't use --add-suffix without -n.")
191n/a
192n/a if not options.write and options.no_diffs:
193n/a warn("not writing files and not printing diffs; that's not very useful")
194n/a if not options.write and options.nobackups:
195n/a parser.error("Can't use -n without -w")
196n/a if options.list_fixes:
197n/a print("Available transformations for the -f/--fix option:")
198n/a for fixname in refactor.get_all_fix_names(fixer_pkg):
199n/a print(fixname)
200n/a if not args:
201n/a return 0
202n/a if not args:
203n/a print("At least one file or directory argument required.", file=sys.stderr)
204n/a print("Use --help to show usage.", file=sys.stderr)
205n/a return 2
206n/a if "-" in args:
207n/a refactor_stdin = True
208n/a if options.write:
209n/a print("Can't write to stdin.", file=sys.stderr)
210n/a return 2
211n/a if options.print_function:
212n/a flags["print_function"] = True
213n/a
214n/a # Set up logging handler
215n/a level = logging.DEBUG if options.verbose else logging.INFO
216n/a logging.basicConfig(format='%(name)s: %(message)s', level=level)
217n/a logger = logging.getLogger('lib2to3.main')
218n/a
219n/a # Initialize the refactoring tool
220n/a avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
221n/a unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
222n/a explicit = set()
223n/a if options.fix:
224n/a all_present = False
225n/a for fix in options.fix:
226n/a if fix == "all":
227n/a all_present = True
228n/a else:
229n/a explicit.add(fixer_pkg + ".fix_" + fix)
230n/a requested = avail_fixes.union(explicit) if all_present else explicit
231n/a else:
232n/a requested = avail_fixes.union(explicit)
233n/a fixer_names = requested.difference(unwanted_fixes)
234n/a input_base_dir = os.path.commonprefix(args)
235n/a if (input_base_dir and not input_base_dir.endswith(os.sep)
236n/a and not os.path.isdir(input_base_dir)):
237n/a # One or more similar names were passed, their directory is the base.
238n/a # os.path.commonprefix() is ignorant of path elements, this corrects
239n/a # for that weird API.
240n/a input_base_dir = os.path.dirname(input_base_dir)
241n/a if options.output_dir:
242n/a input_base_dir = input_base_dir.rstrip(os.sep)
243n/a logger.info('Output in %r will mirror the input directory %r layout.',
244n/a options.output_dir, input_base_dir)
245n/a rt = StdoutRefactoringTool(
246n/a sorted(fixer_names), flags, sorted(explicit),
247n/a options.nobackups, not options.no_diffs,
248n/a input_base_dir=input_base_dir,
249n/a output_dir=options.output_dir,
250n/a append_suffix=options.add_suffix)
251n/a
252n/a # Refactor all files and directories passed as arguments
253n/a if not rt.errors:
254n/a if refactor_stdin:
255n/a rt.refactor_stdin()
256n/a else:
257n/a try:
258n/a rt.refactor(args, options.write, options.doctests_only,
259n/a options.processes)
260n/a except refactor.MultiprocessingUnsupported:
261n/a assert options.processes > 1
262n/a print("Sorry, -j isn't supported on this platform.",
263n/a file=sys.stderr)
264n/a return 1
265n/a rt.summarize()
266n/a
267n/a # Return error status (0 if rt.errors is zero)
268n/a return int(bool(rt.errors))