-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·63 lines (51 loc) · 1.83 KB
/
cli.py
File metadata and controls
executable file
·63 lines (51 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
import pathlib
import zipfile
import click
import yaml
from nbconvert.exporters import NotebookExporter
from nbconvert.preprocessors import ClearOutputPreprocessor
def get_materials() -> dict:
with open("course.yml", "r", encoding="utf8") as f:
course = yaml.safe_load(f)
materials = {
lesson["slug"]: lesson.get("materials", []) for lesson in course["plan"]
}
return materials
def clear_notebook(path: pathlib.Path) -> bytes:
exporter = NotebookExporter()
exporter.register_preprocessor(ClearOutputPreprocessor(), enabled=True)
output = exporter.from_filename(str(path))
return output[0]
@click.group()
def cli():
pass
@cli.command()
@click.argument("slug")
def export(slug: str) -> None:
"""Export all material folders for a lesson as a single zip file.
Clears the output of ipynb jupyter notebook files.
"""
materials = get_materials()
dirs = [
"lessons" / pathlib.Path(material["lesson"]) for material in materials[slug]
]
with zipfile.ZipFile(f"{slug}.zip", "w") as zip:
for dir in dirs:
for file in dir.glob("**/*"):
if not file.is_file():
continue
if file.name == "info.yml":
continue
if "checkpoint" in file.stem:
continue
click.echo(f" {file}")
if file.suffix == ".ipynb":
content = clear_notebook(file)
zip.writestr(str(file.relative_to(dir.parent)), content)
else:
zip.write(file, arcname=file.relative_to(dir.parent))
click.echo(" lessons/pyproject.toml")
zip.write("lessons/pyproject.toml", arcname="pyproject.toml")
if __name__ == "__main__":
cli()