Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_files_format(self):
for file in list_all_py_files():
try:
print(file)
code = _read_utf_8_file(file)
# https://pypi.python.org/pypi/yapf/0.20.2#example-as-a-module
diff, changed = FormatCode(code, filename=file, style_config='setup.cfg', print_diff=True)
if changed:
print(diff)
self.badly_formatted_files.append(file)
except Exception as e:
print("Error while processing file: `%s`\n" "Error: %s" % (file, str(e)))
with self.assertNotRaises(Exception):
str_err = ""
if self.badly_formatted_files:
for filename in self.badly_formatted_files:
str_err += 'yapf -i --style=setup.cfg %s\n' % filename
str_err = "\n======================================================================================\n" \
Parses the code into a tree, performs comment splicing and runs the
unwrapper.
Arguments:
code: code to parse as a string
dumptree: if True, the parsed pytree (after comment splicing) is dumped
to stderr. Useful for debugging.
Returns:
List of unwrapped lines.
"""
tree = pytree_utils.ParseCodeToTree(code)
comment_splicer.SpliceComments(tree)
continuation_splicer.SpliceContinuations(tree)
subtype_assigner.AssignSubtypes(tree)
split_penalty.ComputeSplitPenalties(tree)
blank_line_calculator.CalculateBlankLines(tree)
if dumptree:
pytree_visitor.DumpPyTree(tree, target_stream=sys.stderr)
uwlines = pytree_unwrapper.UnwrapPyTree(tree)
for uwl in uwlines:
uwl.CalculateFormattingInformation()
return uwlines
def Visit_or_test(self, node): # pylint: disable=invalid-name
# or_test ::= and_test ('or' and_test)*
self.DefaultNodeVisit(node)
_IncreasePenalty(node, OR_TEST)
index = 1
while index + 1 < len(node.children):
if style.Get('SPLIT_BEFORE_LOGICAL_OPERATOR'):
_DecrementSplitPenalty(
pytree_utils.FirstLeafNode(node.children[index]), OR_TEST)
else:
_DecrementSplitPenalty(
pytree_utils.FirstLeafNode(node.children[index + 1]), OR_TEST)
index += 2
def Visit_comp_if(self, node): # pylint: disable=invalid-name
# comp_if ::= 'if' old_test [comp_iter]
_SetSplitPenalty(node.children[0],
style.Get('SPLIT_PENALTY_BEFORE_IF_EXPR'))
_SetStronglyConnected(*node.children[1:])
self.DefaultNodeVisit(node)
initial_indent = ' ' * bonus_space
k = self.parameters[name].keys()
kwargs = ', '.join(map(''.join, zip(k, 500 * ['='], k)))
prelude = name.split('.')[-1].lower() + ' = '
prelude2 = initial_indent + \
prelude + \
self.packages[name]['class'].__module__ + '.' + \
self.packages[name]['class'].__name__ + \
'('
s = prelude2 + kwargs + ')'
if use_yapf:
s2 = FormatCode(s, style_config=style)[0][:-1]
else:
sout = textwrap.wrap(
s,
width=width,
initial_indent=' ' * bonus_space,
subsequent_indent=' ' * (bonus_space + len(prelude2)),
break_on_hyphens=False,
break_long_words=False)
s2 = '\n'.join(sout)
return s2
elif isinstance(each, (Python, Engine)):
pass
else:
raise TypeError(type(each))
ctx = Context('', tables, relations)
proc = Proc([
'from kizmi.database.types import *',
'import kizmi.database.infrastructure as db',
'import builtins',
])
for each in asts:
proc, ctx = emit(each, proc, ctx)
proc += '__base__.metadata.create_all(bind=engine)'
proc += 'session = __session__'
return FormatCode(dedent(dumps(proc.codes)))[0]
def main():
if not _YAPF_IMPORTED:
return
encoding = vim.eval('&encoding')
buf = vim.current.buffer
unicode_buf = [unicode(s, encoding) for s in buf]
text = '\n'.join(unicode_buf)
buf_range = (vim.current.range.start, vim.current.range.end)
lines_range = [pos + 1 for pos in buf_range]
style_config = _get_style()
vim.command('let l:used_style = "{}"'.format(style_config))
try:
formatted = yapf_api.FormatCode(text,
filename='',
style_config=style_config,
lines=[lines_range],
verify=False)
except (SyntaxError, IndentationError) as err:
vim.command('let l:error_type = "{}"'.format(type(err).__name__))
vim.command('let l:error_position = [{}, {}]'.format(err.lineno,
err.offset))
return
if isinstance(formatted, tuple):
formatted = formatted[0]
lines = formatted.rstrip('\n').split('\n')
sequence = difflib.SequenceMatcher(None, unicode_buf, lines)
def _format(line, *, indent=0):
'''Format Python code lines, with a specific indent
NOTE: Uses yapf if available
'''
prefix = ' ' * indent
if yapf is None:
yield prefix + line
else:
from yapf.yapflib.yapf_api import FormatCode
from yapf.yapflib.style import _style
# TODO study awkward yapf api more closely
_style['COLUMN_LIMIT'] = 79 - indent
for formatted_line in FormatCode(line)[0].split('\n'):
if formatted_line:
yield prefix + formatted_line.rstrip()
def DefaultNodeVisit(self, node):
"""Override the default visitor for Node.
This will set the blank lines required if the last entity was a class or
function.
Arguments:
node: (pytree.Node) The node to visit.
"""
if self.last_was_class_or_function:
if pytree_utils.NodeName(node) in _PYTHON_STATEMENTS:
leaf = _GetFirstChildLeaf(node)
self._SetNumNewlines(leaf, self._GetNumNewlines(leaf))
self.last_was_class_or_function = False
super(_BlankLineCalculator, self).DefaultNodeVisit(node)
def Visit_async_funcdef(self, node): # pylint: disable=invalid-name
self._StartNewLine()
index = 0
for child in node.children:
index += 1
self.Visit(child)
if pytree_utils.NodeName(child) == 'ASYNC':
break
for child in node.children[index].children:
self.Visit(child)