Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def scan(self, code, filename=''):
code = utils.sanitize_code(code)
self.code = code.splitlines()
self.filename = filename
try:
node = ast.parse(code, filename=self.filename)
except SyntaxError as err:
text = ' at "{}"'.format(err.text.strip()) if err.text else ''
print('{}:{:d}: {}{}'.format(
utils.format_path(filename), err.lineno, err.msg, text),
file=sys.stderr)
self.found_dead_code_or_error = True
except (TypeError, ValueError) as err:
# Python < 3.5 raises TypeError and Python >= 3.5 raises
# ValueError if source contains null bytes.
print('{}: invalid source code "{}"'.format(
utils.format_path(filename), err), file=sys.stderr)
self.found_dead_code_or_error = True
else:
self.visit(node)
code = utils.sanitize_code(code)
self.code = code.splitlines()
self.filename = filename
try:
node = ast.parse(code, filename=self.filename)
except SyntaxError as err:
text = ' at "{}"'.format(err.text.strip()) if err.text else ''
print('{}:{:d}: {}{}'.format(
utils.format_path(filename), err.lineno, err.msg, text),
file=sys.stderr)
self.found_dead_code_or_error = True
except (TypeError, ValueError) as err:
# Python < 3.5 raises TypeError and Python >= 3.5 raises
# ValueError if source contains null bytes.
print('{}: invalid source code "{}"'.format(
utils.format_path(filename), err), file=sys.stderr)
self.found_dead_code_or_error = True
else:
self.visit(node)
def get_report(self, add_size=False):
if add_size:
line_format = 'line' if self.size == 1 else 'lines'
size_report = ', {:d} {}'.format(self.size, line_format)
else:
size_report = ''
return "{}:{:d}: {} ({}% confidence{})".format(
utils.format_path(self.filename), self.first_lineno,
self.message, self.confidence, size_report)
def get_whitelist_string(self):
filename = utils.format_path(self.filename)
if self.typ == 'unreachable_code':
return ('# {} ({}:{})'.format(
self.message, filename, self.first_lineno))
else:
prefix = '_.' if self.typ in ['attribute', 'property'] else ''
return "{}{} # unused {} ({}:{:d})".format(
prefix, self.name, self.typ, filename, self.first_lineno)