|
| 1 | +"""Remove tags metadata from notebook cells if they are empty.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import sys |
| 7 | +from typing import TYPE_CHECKING |
| 8 | + |
| 9 | +import nbformat |
| 10 | + |
| 11 | +from compwa_policy.errors import PrecommitError |
| 12 | +from compwa_policy.utilities.executor import Executor |
| 13 | +from compwa_policy.utilities.notebook import load_notebook |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + from collections.abc import Sequence |
| 17 | + |
| 18 | + |
| 19 | +def main(argv: Sequence[str] | None = None) -> int: |
| 20 | + parser = argparse.ArgumentParser(__doc__) |
| 21 | + parser.add_argument("filenames", nargs="*", help="Filenames to check.") |
| 22 | + args = parser.parse_args(argv) |
| 23 | + |
| 24 | + with Executor(raise_exception=False) as do: |
| 25 | + for filename in args.filenames: |
| 26 | + do(_set_nb_display_name, filename) |
| 27 | + return 1 if do.error_messages else 0 |
| 28 | + |
| 29 | + |
| 30 | +def _set_nb_display_name(filename: str) -> None: |
| 31 | + notebook = load_notebook(filename) |
| 32 | + display_name = ( |
| 33 | + notebook.get("metadata", {}) |
| 34 | + .get("kernelspec", {}) # cspell:ignore kernelspec |
| 35 | + .get("display_name") |
| 36 | + ) |
| 37 | + expected_display_name = "Python 3 (ipykernel)" |
| 38 | + if display_name != expected_display_name: |
| 39 | + if "metadata" not in notebook: |
| 40 | + notebook["metadata"] = {} |
| 41 | + metadata = notebook["metadata"] |
| 42 | + if "kernelspec" not in metadata: |
| 43 | + metadata["kernelspec"] = {} |
| 44 | + metadata["kernelspec"]["display_name"] = expected_display_name |
| 45 | + nbformat.write(notebook, filename) |
| 46 | + msg = f"Set display name to {expected_display_name!r} in {filename}" |
| 47 | + raise PrecommitError(msg) |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + sys.exit(main()) |
0 commit comments