Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
mode = argv[2]
violation_detected = False
for file_to_style in os.listdir(srcdir):
if file_to_style.endswith('.py'):
filepath = os.path.join(srcdir, file_to_style)
if mode == "CHECK":
if detect_formatting_violation(filepath):
print(str(argv[0]) + ": ERROR: formatting violation detected in " + str(file_to_style))
violation_detected = True
elif mode == "APPLY":
if detect_formatting_violation(filepath):
print(str(file_to_style) + ": found issue, reformatting...")
FormatFile(filepath, in_place=True, style_config='style.yapf')
violation_detected = True
else:
print("ERROR: invalid mode " + str(mode))
exit(1)
if mode == 'CHECK' and violation_detected:
exit(1)
elif not violation_detected:
print(str(argv[0]) + " INFO: all formatting for targets in " + str(argv[1]) + " OK!")
def format(ctx, noimports=False, nostyle=False):
if not noimports:
from isort import SortImports
if not nostyle:
from yapf.yapflib.yapf_api import FormatFile
for filename in glob.glob('**/*.py', recursive=True):
if not noimports:
SortImports(filename)
if not nostyle:
FormatFile(filename, in_place=True)
def apply_to_file(fp, sp, in_place=False):
"""
Apply the style to a file.
:param fp: path to file
:type fp: str
:param sp: path to style
:type sp: str
:param in_place: format code in-place
:type in_place: bool
:return: the reformated code
:rtype: str or None
"""
rc, encoidng, changed = FormatFile(fp, style_config=sp, verify=True, in_place=in_place)
return rc
def detect_formatting_violation(filepath):
original = read_file_contents(filepath)
reformatted = FormatFile(filepath, style_config='style.yapf')
if original != reformatted[0]:
print(FormatCode(original, filename=filepath, print_diff=True, style_config='style.yapf')[0])
return True
return False
except Exception as e:
error = "isort crashed on {path}: {error}".format(path=short_path,
error=e)
print(error, file=sys.stderr)
return False
if isort_changed:
print("\nSorted imports in {path}.".format(path=short_path))
# Then YAPF
try:
# It might be tempting to use the "inplace" option to FormatFile, but
# it doesn't do an atomic replace, which is dangerous, so don't use
# it unless you submit a fix to yapf.
if format_code:
(contents, encoding, changed) = FormatFile(
path, style_config=style_config)
if platform.system() == 'Windows':
# yapf screws up line endings on windows
with codecs.open(path, 'r', encoding) as f:
old_contents = f.read()
contents = contents.replace("\r\n", "\n")
if len(old_contents) == 0:
# Windows yapf seems to force a newline? I dunno
contents = ""
changed = (old_contents != contents)
else:
changed = False
except Exception as e:
error = "yapf crashed on {path}: {error}".format(path=short_path,
lines,
style_config=None,
no_local_style=False,
in_place=False,
print_diff=False,
verify=False,
quiet=False,
verbose=False):
"""Format an individual file."""
if verbose and not quiet:
print('Reformatting %s' % filename)
if style_config is None and not no_local_style:
style_config = file_resources.GetDefaultStyleForDir(
os.path.dirname(filename))
try:
reformatted_code, encoding, has_change = yapf_api.FormatFile(
filename,
in_place=in_place,
style_config=style_config,
lines=lines,
print_diff=print_diff,
verify=verify,
logger=logging.warning)
if not in_place and not quiet and reformatted_code:
file_resources.WriteReformattedCode(filename, reformatted_code, encoding,
in_place)
return has_change
except tokenize.TokenError as e:
raise errors.YapfError('%s:%s:%s' % (filename, e.args[1][0], e.args[0]))
except SyntaxError as e:
e.filename = filename
raise
def validateFormat(fix=False):
"""Check the format of python files in the tools directory.
Arguments:
fix: a flag to indicate if fixes should be applied.
"""
fixes_required = False
failed_update_files = set()
successful_update_files = set()
for python_file in collectFiles():
reformatted_source, encoding, changed = FormatFile(python_file,
style_config='tools/.style.yapf',
in_place=fix,
print_diff=not fix)
if not fix:
fixes_required = True if changed else fixes_required
if reformatted_source:
print(reformatted_source)
continue
file_list = failed_update_files if reformatted_source else successful_update_files
file_list.add(python_file)
if fix:
displayFixResults(successful_update_files, failed_update_files)
fixes_required = len(failed_update_files) > 0
return not fixes_required
@task
def format_python(py_diff_list):
if confirm('Review formatting changes? (Select no to approve all)'):
for pyfile in py_diff_list:
print 'Changes:\n' + FormatFile(pyfile, print_diff=True)[0]
if confirm('Accept changes to %s?' % pyfile):
FormatFile(pyfile, in_place=True)
else:
for pyfile in py_diff_list:
FormatFile(pyfile, in_place=True)