Skip to content

Commit a216e3d

Browse files
Add PR action to validate notebook format
1 parent 48e5e70 commit a216e3d

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

.github/scripts/check_notebooks.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import subprocess
2+
import sys
3+
from pathlib import Path
4+
5+
import nbformat
6+
7+
8+
def get_changed_notebooks(base_ref: str = "origin/main") -> list[Path]:
9+
"""
10+
Returns a list of changed notebook paths in the current git branch
11+
compared to the specified base reference.
12+
"""
13+
result = subprocess.run(
14+
["git", "diff", "--name-only", base_ref, "--", "*.ipynb"],
15+
capture_output=True,
16+
text=True,
17+
check=True,
18+
)
19+
return [Path(line.strip()) for line in result.stdout.splitlines() if line.strip()]
20+
21+
22+
def is_valid_notebook(path: Path) -> bool:
23+
"""
24+
Checks if the notebook at the given path is valid by attempting to read it
25+
with nbformat.
26+
"""
27+
try:
28+
with open(path, "r", encoding="utf-8") as f:
29+
nbformat.read(f, as_version=4)
30+
return True
31+
except Exception as e:
32+
print(f"{path}: INVALID - {e}")
33+
return False
34+
35+
36+
if __name__ == "__main__":
37+
changed_notebooks = get_changed_notebooks()
38+
if not changed_notebooks:
39+
print("No changed .ipynb files to validate.")
40+
sys.exit(0)
41+
42+
print(f"Validating {len(changed_notebooks)} notebook(s)...")
43+
errors = 0
44+
for path in changed_notebooks:
45+
if not path.exists():
46+
continue # skip deleted files
47+
if not is_valid_notebook(path):
48+
errors += 1
49+
50+
if errors:
51+
print(f"{errors} invalid notebook(s) found.")
52+
sys.exit(1)
53+
else:
54+
print("All changed notebooks are valid.")
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
name: Validate Changed Notebooks
2+
3+
on: [pull_request]
4+
5+
jobs:
6+
validate-notebooks:
7+
name: Validate Notebooks
8+
runs-on: ubuntu-latest
9+
10+
steps:
11+
- name: Checkout code
12+
uses: actions/checkout@v3
13+
with:
14+
fetch-depth: 0 # needed for git diff to work
15+
16+
- name: Set up Python
17+
uses: actions/setup-python@v4
18+
with:
19+
python-version: '3.12'
20+
21+
- name: Install dependencies
22+
run: pip install nbformat
23+
24+
- name: Validate changed .ipynb files
25+
run: python .github/scripts/check_notebooks.py

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,3 +140,6 @@ examples/fine-tuned_qa/local_cache/*
140140

141141
# PyCharm files
142142
.idea/
143+
144+
# VS Code files
145+
.vscode/

0 commit comments

Comments
 (0)