Skip to content

Commit

Permalink
Catch exceptions during eval()
Browse files Browse the repository at this point in the history
  • Loading branch information
arkq committed Nov 29, 2017
1 parent c50fe8e commit de3aeee
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/flake8_requirements/checker.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import ast
import os
import re
import sys
from collections import namedtuple
from logging import getLogger
from os import path

from pkg_resources import parse_requirements

Expand Down Expand Up @@ -139,12 +139,32 @@ def __init__(self, tree):
return

def setup(**kw):
"""Setup() arguments hijacking."""
self.keywords = kw

eval(
compile(ast.fix_missing_locations(tree), "<str>", mode='exec'),
{'__file__': "setup.py", '__f8r_setup': setup},
)
# XXX: If evaluated script (setup.py) depends on local modules we
# have to add its root directory to the import search path.
# Note however, that this hack might break further imports
# for OUR Python instance (we're changing our own sys.path)!
sys.path.insert(0, os.getcwd())

try:
tree = ast.fix_missing_locations(tree)
eval(compile(tree, "<str>", mode='exec'), {
'__name__': "__main__",
'__file__': "setup.py",
'__f8r_setup': setup,
})
except Exception as e:
# XXX: Exception during setup.py evaluation might not necessary
# mean "fatal error". This exception might occur if e.g.
# we have hijacked local setup() function (due to matching
# heuristic for function arguments). Anyway, we shall not
# break flake8 execution due to out eval() usage.
LOG.exception("Couldn't evaluate setup.py: %s", e)

# Restore import search path.
sys.path.pop(0)

def get_requirements(self, install=True, extras=True, setup=False):
"""Get package requirements."""
Expand Down Expand Up @@ -216,6 +236,7 @@ def __init__(self, tree, filename, lines=None):
"""Initialize requirements checker."""
self.tree = tree
self.filename = filename
self.lines = lines
self.setup = self.get_setup()

@classmethod
Expand Down Expand Up @@ -260,7 +281,7 @@ def get_setup(cls):
def processing_setup_py(self):
"""Determine whether we are processing setup.py file."""
try:
return path.samefile(self.filename, "setup.py")
return os.path.samefile(self.filename, "setup.py")
except OSError:
return False

Expand Down

0 comments on commit de3aeee

Please sign in to comment.