Skip to content

Commit

Permalink
fix(imports): remove invalid lines when parsing notebooks (#656)
Browse files Browse the repository at this point in the history
  • Loading branch information
mkniewallner committed Apr 2, 2024
1 parent 5494d09 commit a40f47b
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
13 changes: 13 additions & 0 deletions src/imports/ipynb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,19 @@ fn _extract_code_from_notebook_cells(cells: &[serde_json::Value]) -> String {
.filter_map(|cell| cell["source"].as_array())
.flatten()
.filter_map(|line| line.as_str())
.map(|line| {
// https://ipython.readthedocs.io/en/stable/interactive/magics.html
// We want to skip lines using magics, as they are not valid Python. We replace the
// lines with empty strings instead of completely removing them, to ensure that the
// violation reporters show the correct line location for imports made below those
// lines.
if line.starts_with('%') || line.starts_with('!') {
""
} else {
line
}
})
.map(|s| s.strip_suffix('\n').unwrap_or(s))
.map(str::to_owned)
.collect();

Expand Down
7 changes: 6 additions & 1 deletion tests/data/example_project/src/notebook.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@
"metadata": {},
"outputs": [],
"source": [
"!ls\n",
"%timeit\n",
"%%timeit\n",
"import click\n",
"from urllib3 import contrib\n",
"import toml"
"import toml\n",
"1 +\\\n",
" 2"
]
}
],
Expand Down
2 changes: 1 addition & 1 deletion tests/functional/cli/test_cli_requirements_txt.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def test_cli_single_requirements_files(pip_venv_factory: PipVenvFactory) -> None
"module": "urllib3",
"location": {
"file": str(Path("src/notebook.ipynb")),
"line": 3,
"line": 2,
"column": 1,
},
},
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/imports/test_extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ def test_import_parser_ipynb() -> None:
notebook_path = Path("tests/data/example_project/src/notebook.ipynb")

assert get_imported_modules_from_list_of_files([notebook_path]) == {
"click": [Location(notebook_path, 1, 8)],
"toml": [Location(notebook_path, 5, 8)],
"urllib3": [Location(notebook_path, 3, 1)],
"click": [Location(notebook_path, 4, 8)],
"toml": [Location(notebook_path, 6, 8)],
"urllib3": [Location(notebook_path, 5, 1)],
}


Expand Down

0 comments on commit a40f47b

Please sign in to comment.