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