Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
Given a filename and some code to be checked, uses the PyFlakesmodule to
return a dictionary describing issues of code quality per line. See:
https://github.com/PyCQA/pyflakes
If a list symbols is passed in as "builtins" these are assumed to be
additional builtins available when run by Mu.
"""
import_all = "from microbit import *" in code
if import_all:
# Massage code so "from microbit import *" is expanded so the symbols
# are known to flake.
code = code.replace("from microbit import *", EXPANDED_IMPORT)
reporter = MuFlakeCodeReporter()
check(code, filename, reporter)
if builtins:
builtins_regex = re.compile(r"^undefined name '(" +
'|'.join(builtins) + r")'")
feedback = {}
for log in reporter.log:
if import_all:
# Guard to stop unwanted "microbit.* imported but unused" messages.
message = log['message']
if EXPAND_FALSE_POSITIVE.match(message):
continue
if builtins:
if builtins_regex.match(log['message']):
continue
if log['line_no'] not in feedback:
feedback[log['line_no']] = []
feedback[log['line_no']].append(log)
fn = self.finalize(root)
sfn = g.shortFileName(fn)
# #1306: nopyflakes
if any([z.strip().startswith('@nopyflakes') for z in g.splitLines(root.b)]):
continue
# Report the file name.
s = g.readFileIntoEncodedString(fn)
if s and s.strip():
if not pyflakes_errors_only:
g.es(f"Pyflakes: {sfn}")
# Send all output to the log pane.
r = reporter.Reporter(
errorStream=self.LogStream(i, roots),
warningStream=self.LogStream(i, roots),
)
errors = api.check(s, sfn, r)
total_errors += errors
return total_errors
#@+node:ekr.20171228013625.1: *3* pyflakes.check_script
def identify_missing(file_dict):
local_imports = {}
for key, file_names in file_dict.items():
if key in USED_FOLDER_EMAN2:
local_imports[key] = []
continue
input_dir = os.path.join(NO_IMPORTS_DIR, key)
for file_path in file_names:
basename = os.path.basename(file_path)
input_file_path = os.path.join(input_dir, basename)
reset_lists()
with open(input_file_path) as read:
file_content = read.read()
pyfl.check(file_content, basename, GLOBAL_REPORTER)
local_imports[basename] = GLOBAL_CHECKER.undefined_names
return local_imports
if idx - final_idx == 2 and IF_RE.match(lines[final_idx]) and ELSE_RE.match(lines[idx-1]):
print(basename, lines[idx-1], lines[final_idx])
bad_idx.append(idx-1)
bad_idx.append(final_idx)
elif IF_RE.match(lines[final_idx]):
bad_idx.append(final_idx)
else:
do_break = True
break
if do_break:
print('ERROR', output_file_path, GLOBAL_REPORTER.indent_error)
break
for idx in reversed(sorted(bad_idx)):
del lines[idx]
reset_lists()
pyfl.check(''.join(lines), output_file_path, GLOBAL_REPORTER)
with open(output_file_path, 'w') as write:
write.write(''.join(lines))
def pyflakes_report(code):
"""Inspect code using PyFlakes to detect any 'missing name' report.
Args:
code: A multiline string representing Python code
Returns: a list of names that have been reported missing by Flakes
"""
flakes_stdout = StreamList()
flakes_stderr = StreamList()
rep = pyflakes_reporter.Reporter(
flakes_stdout.reset(),
flakes_stderr.reset())
pyflakes_api.check(code, filename="kale", reporter=rep)
# the stderr stream should be used just for compilation error, so if any
# message is found in the stderr stream, raise an exception
if rep._stderr():
raise RuntimeError("Flakes reported the following error:"
"\n{}".format('\t' + '\t'.join(rep._stderr())))
# Match names
p = r"'(.+?)'"
out = rep._stdout()
# Using a `set` to avoid repeating the same var names in case they are
# reported missing multiple times by flakes
undef_vars = set()
# iterate over all the flakes report output, keeping only lines
# with 'undefined name' reports
"""
Given a filename and some code to be checked, uses the PyFlakesmodule to
return a dictionary describing issues of code quality per line. See:
https://github.com/PyCQA/pyflakes
If a list symbols is passed in as "builtins" these are assumed to be
additional builtins available when run by Mu.
"""
import_all = "from microbit import *" in code
if import_all:
# Massage code so "from microbit import *" is expanded so the symbols
# are known to flake.
code = code.replace("from microbit import *", EXPANDED_IMPORT)
reporter = MuFlakeCodeReporter()
check(code, filename, reporter)
if builtins:
builtins_regex = re.compile(
r"^undefined name '(" + "|".join(builtins) + r")'"
)
feedback = {}
for log in reporter.log:
if import_all:
# Guard to stop unwanted "microbit.* imported but unused" messages.
message = log["message"]
if EXPAND_FALSE_POSITIVE.match(message):
continue
if builtins:
if builtins_regex.match(log["message"]):
continue
if log["line_no"] not in feedback:
feedback[log["line_no"]] = []
def _pyflakes_annotations(path, text):
import pyflakes.api as pyflakes
warning_stream = io.StringIO()
error_stream = io.StringIO()
reporter = pyflakes.modReporter.Reporter(warning_stream, error_stream)
pyflakes.check(text, path, reporter)
warnings = _get_annotations(path, warning_stream, Style.warning)
errors = _get_annotations(path, error_stream, Style.error)
return warnings + errors
def report_pyflakes(document):
"""
Run pyflakes on document and return list of ReporterError instances.
"""
# Run pyflakes on input.
reporter = _FlakesReporter()
pyflakes.api.check(document.text, '', reporter=reporter)
def format_flake_message(message):
return [
('class:flakemessage.prefix', 'pyflakes:'),
('', ' '),
('class:flakemessage', message.message % message.message_args)
]
def message_to_reporter_error(message):
""" Turn pyflakes message into ReporterError. """
start_index = document.translate_row_col_to_index(message.lineno - 1, message.col)
end_index = start_index
while end_index < len(document.text) and document.text[end_index] in WORD_CHARACTERS:
end_index += 1
return ReporterError(lineno=message.lineno - 1,