-
Notifications
You must be signed in to change notification settings - Fork 87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support inferred values when linting sys path - saved #1863
Closed
Closed
Changes from 11 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f7e4bbc
move tests to dedicated file
ericvergnaud 3caa312
formatting
ericvergnaud 7b1e8f5
support multiple inferred values
ericvergnaud b245148
fix typo
ericvergnaud 91bce51
register loadable dependencies
ericvergnaud f3323ca
more tests
ericvergnaud 757d5d8
formatting
ericvergnaud 3f5e621
Merge branch 'main' into more-inference-tests
ericvergnaud d4d7389
more test coverage
ericvergnaud 01c213f
factorize code
ericvergnaud b9bd6e8
raise advice for unresolved paths
ericvergnaud adaba42
address comments
ericvergnaud File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||||
---|---|---|---|---|---|---|---|---|
|
@@ -9,10 +9,12 @@ | |||||||
Attribute, | ||||||||
Call, | ||||||||
Const, | ||||||||
InferenceError, | ||||||||
Import, | ||||||||
ImportFrom, | ||||||||
Name, | ||||||||
NodeNG, | ||||||||
Uninferable, | ||||||||
) | ||||||||
|
||||||||
from databricks.labs.ucx.source_code.base import Linter, Advice, Advisory | ||||||||
|
@@ -83,12 +85,23 @@ class NotebookRunCall(NodeBase): | |||||||
def __init__(self, node: Call): | ||||||||
super().__init__(node) | ||||||||
|
||||||||
def get_notebook_path(self) -> str | None: | ||||||||
node = DbutilsLinter.get_dbutils_notebook_run_path_arg(cast(Call, self.node)) | ||||||||
inferred = next(node.infer(), None) | ||||||||
if isinstance(inferred, Const): | ||||||||
return inferred.value.strip().strip("'").strip('"') | ||||||||
return None | ||||||||
def get_notebook_paths(self) -> list[str | None]: | ||||||||
node = DbutilsLinter.get_dbutils_notebook_run_path_arg(self.node) | ||||||||
try: | ||||||||
return self._get_notebook_paths(node.infer()) | ||||||||
except InferenceError: | ||||||||
logger.debug(f"Can't infer value(s) of {node.as_string()}") | ||||||||
return [None] | ||||||||
|
||||||||
@classmethod | ||||||||
def _get_notebook_paths(cls, nodes: Iterable[NodeNG]) -> list[str | None]: | ||||||||
paths: list[str | None] = [] | ||||||||
for node in nodes: | ||||||||
if isinstance(node, Const): | ||||||||
paths.append(node.as_string().strip("'").strip('"')) | ||||||||
continue | ||||||||
paths.append(None) | ||||||||
return paths | ||||||||
|
||||||||
|
||||||||
T = TypeVar("T", bound=Callable) | ||||||||
|
@@ -104,19 +117,20 @@ def lint(self, code: str) -> Iterable[Advice]: | |||||||
@classmethod | ||||||||
def _convert_dbutils_notebook_run_to_advice(cls, node: NodeNG) -> Advisory: | ||||||||
assert isinstance(node, Call) | ||||||||
path = cls.get_dbutils_notebook_run_path_arg(node) | ||||||||
if isinstance(path, Const): | ||||||||
call = NotebookRunCall(cast(Call, node)) | ||||||||
paths = call.get_notebook_paths() | ||||||||
if None in paths: | ||||||||
return Advisory( | ||||||||
'dbutils-notebook-run-literal', | ||||||||
"Call to 'dbutils.notebook.run' will be migrated automatically", | ||||||||
'dbutils-notebook-run-dynamic', | ||||||||
"Path for 'dbutils.notebook.run' is too complex and requires adjusting the notebook path(s)", | ||||||||
node.lineno, | ||||||||
node.col_offset, | ||||||||
node.end_lineno or 0, | ||||||||
node.end_col_offset or 0, | ||||||||
) | ||||||||
return Advisory( | ||||||||
'dbutils-notebook-run-dynamic', | ||||||||
"Path for 'dbutils.notebook.run' is not a constant and requires adjusting the notebook path", | ||||||||
'dbutils-notebook-run-literal', | ||||||||
"Call to 'dbutils.notebook.run' will be migrated automatically", | ||||||||
nfx marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||
node.lineno, | ||||||||
node.col_offset, | ||||||||
node.end_lineno or 0, | ||||||||
|
@@ -172,6 +186,11 @@ class RelativePath(SysPathChange): | |||||||
pass | ||||||||
|
||||||||
|
||||||||
class UnresolvedPath(SysPathChange): | ||||||||
# path added to sys.path that cannot be inferred | ||||||||
pass | ||||||||
|
||||||||
|
||||||||
class SysPathChangesVisitor(TreeVisitor): | ||||||||
|
||||||||
def __init__(self): | ||||||||
|
@@ -204,10 +223,26 @@ def visit_call(self, node: Call): | |||||||
return | ||||||||
is_append = func.attrname == "append" | ||||||||
changed = node.args[0] if is_append else node.args[1] | ||||||||
if isinstance(changed, Const): | ||||||||
self.sys_path_changes.append(AbsolutePath(node, changed.value, is_append)) | ||||||||
elif isinstance(changed, Call): | ||||||||
self._visit_relative_path(changed, is_append) | ||||||||
relative = False | ||||||||
if isinstance(changed, Call): | ||||||||
if not self._match_aliases(changed.func, ["os", "path", "abspath"]): | ||||||||
return | ||||||||
relative = True | ||||||||
changed = changed.args[0] | ||||||||
try: | ||||||||
all_inferred = changed.inferred() | ||||||||
for inferred in all_inferred: | ||||||||
self._visit_inferred(changed, inferred, relative, is_append) | ||||||||
except InferenceError: | ||||||||
self.sys_path_changes.append(UnresolvedPath(changed, changed.as_string(), is_append)) | ||||||||
|
||||||||
def _visit_inferred(self, changed: NodeNG, inferred: NodeNG, is_relative: bool, is_append: bool): | ||||||||
if inferred is Uninferable or not isinstance(inferred, Const): | ||||||||
self.sys_path_changes.append(UnresolvedPath(changed, changed.as_string(), is_append)) | ||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Can we explicitly return, so that branches won't fall through accidentally? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||||||||
if is_relative: | ||||||||
self.sys_path_changes.append(RelativePath(changed, inferred.value, is_append)) | ||||||||
else: | ||||||||
self.sys_path_changes.append(AbsolutePath(changed, inferred.value, is_append)) | ||||||||
|
||||||||
def _match_aliases(self, node: NodeNG, names: list[str]): | ||||||||
if isinstance(node, Attribute): | ||||||||
|
@@ -221,11 +256,3 @@ def _match_aliases(self, node: NodeNG, names: list[str]): | |||||||
alias = self._aliases.get(full_name, full_name) | ||||||||
return node.name == alias | ||||||||
return False | ||||||||
|
||||||||
def _visit_relative_path(self, node: Call, is_append: bool): | ||||||||
# check for 'os.path.abspath' | ||||||||
if not self._match_aliases(node.func, ["os", "path", "abspath"]): | ||||||||
return | ||||||||
changed = node.args[0] | ||||||||
if isinstance(changed, Const): | ||||||||
self.sys_path_changes.append(RelativePath(changed, changed.value, is_append)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
import functools | ||
import operator | ||
|
||
import pytest | ||
from astroid import Attribute, Call, Const, Expr # type: ignore | ||
|
||
from databricks.labs.ucx.source_code.linters.imports import DbutilsLinter | ||
from databricks.labs.ucx.source_code.linters.python_ast import Tree | ||
|
||
|
||
def test_extract_call_by_name(): | ||
tree = Tree.parse("o.m1().m2().m3()") | ||
stmt = tree.first_statement() | ||
assert isinstance(stmt, Expr) | ||
assert isinstance(stmt.value, Call) | ||
act = Tree.extract_call_by_name(stmt.value, "m2") | ||
assert isinstance(act, Call) | ||
assert isinstance(act.func, Attribute) | ||
assert act.func.attrname == "m2" | ||
|
||
|
||
def test_extract_call_by_name_none(): | ||
tree = Tree.parse("o.m1().m2().m3()") | ||
stmt = tree.first_statement() | ||
assert isinstance(stmt, Expr) | ||
assert isinstance(stmt.value, Call) | ||
act = Tree.extract_call_by_name(stmt.value, "m5000") | ||
assert act is None | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"code, arg_index, arg_name, expected", | ||
[ | ||
("o.m1()", 1, "second", None), | ||
("o.m1(3)", 1, "second", None), | ||
("o.m1(first=3)", 1, "second", None), | ||
("o.m1(4, 3)", None, None, None), | ||
("o.m1(4, 3)", None, "second", None), | ||
("o.m1(4, 3)", 1, "second", 3), | ||
("o.m1(4, 3)", 1, None, 3), | ||
("o.m1(first=4, second=3)", 1, "second", 3), | ||
("o.m1(second=3, first=4)", 1, "second", 3), | ||
("o.m1(second=3, first=4)", None, "second", 3), | ||
("o.m1(second=3)", 1, "second", 3), | ||
("o.m1(4, 3, 2)", 1, "second", 3), | ||
], | ||
) | ||
def test_linter_gets_arg(code, arg_index, arg_name, expected): | ||
tree = Tree.parse(code) | ||
stmt = tree.first_statement() | ||
assert isinstance(stmt, Expr) | ||
assert isinstance(stmt.value, Call) | ||
act = Tree.get_arg(stmt.value, arg_index, arg_name) | ||
if expected is None: | ||
assert act is None | ||
else: | ||
assert isinstance(act, Const) | ||
assert act.value == expected | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"code, expected", | ||
[ | ||
("o.m1()", 0), | ||
("o.m1(3)", 1), | ||
("o.m1(first=3)", 1), | ||
("o.m1(3, 3)", 2), | ||
("o.m1(first=3, second=3)", 2), | ||
("o.m1(3, second=3)", 2), | ||
("o.m1(3, *b, **c, second=3)", 4), | ||
], | ||
) | ||
def test_args_count(code, expected): | ||
tree = Tree.parse(code) | ||
stmt = tree.first_statement() | ||
assert isinstance(stmt, Expr) | ||
assert isinstance(stmt.value, Call) | ||
act = Tree.args_count(stmt.value) | ||
assert act == expected | ||
|
||
|
||
def test_tree_walks_nodes_once(): | ||
nodes = set() | ||
count = 0 | ||
tree = Tree.parse("o.m1().m2().m3()") | ||
for node in tree.walk(): | ||
nodes.add(node) | ||
count += 1 | ||
assert len(nodes) == count | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"code, expected", | ||
[ | ||
( | ||
""" | ||
name = "xyz" | ||
dbutils.notebook.run(name) | ||
""", | ||
["xyz"], | ||
), | ||
( | ||
""" | ||
name = "xyz" + "-" + "abc" | ||
dbutils.notebook.run(name) | ||
""", | ||
["xyz-abc"], | ||
), | ||
( | ||
""" | ||
names = ["abc", "xyz"] | ||
for name in names: | ||
dbutils.notebook.run(name) | ||
""", | ||
["abc", "xyz"], | ||
), | ||
], | ||
) | ||
def test_infers_dbutils_notebook_run_dynamic_value(code, expected): | ||
tree = Tree.parse(code) | ||
calls = DbutilsLinter.list_dbutils_notebook_run_calls(tree) | ||
actual = functools.reduce(operator.iconcat, list(call.get_notebook_paths() for call in calls), []) | ||
assert expected == actual |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Error logs fail the workflow
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done