-
Notifications
You must be signed in to change notification settings - Fork 79
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
DEV: Add Notebook AST Pre-Commit Hook (#417)
- Adds a simple pre-commit check which iterates over code cells in each notebook file and checks that any lines which don't start with a ! are valid python, i.e. that they parse to an abstract syntax tree (AST). - Also removes a broken and unused old hook.
- Loading branch information
Showing
2 changed files
with
38 additions
and
8 deletions.
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 |
---|---|---|
@@ -0,0 +1,33 @@ | ||
"""Simple check to ensure each code cell in a notebook is valid Python.""" | ||
import argparse | ||
import ast | ||
import json | ||
import sys | ||
from pathlib import Path | ||
from typing import List | ||
|
||
|
||
def main(files: List[Path]) -> bool: | ||
"""Check each file in the list of files for valid Python.""" | ||
passed = True | ||
for path in files: | ||
with open(path) as fh: | ||
notebook = json.load(fh) | ||
for n, cell in enumerate(notebook["cells"]): | ||
if cell["cell_type"] != "code": | ||
continue | ||
source = "".join([x for x in cell["source"] if not x.startswith("!")]) | ||
try: | ||
ast.parse(source) | ||
except SyntaxError as e: | ||
passed = False | ||
print(f"{path.name}: {e.msg} (cell {n}, line {e.lineno})") | ||
break | ||
return passed # noqa: R504 | ||
|
||
|
||
if __name__ == "__main__": | ||
parser = argparse.ArgumentParser(description="Check notebook AST") | ||
parser.add_argument("files", nargs="+", help="Path to notebook(s)", type=Path) | ||
args = parser.parse_args() | ||
sys.exit(1 - main(args.files)) |