Skip to content

Commit

Permalink
Merge pull request #35 from datarootsio/add-confirm-prompt
Browse files Browse the repository at this point in the history
Add confirm prompt
  • Loading branch information
murilo-cunha committed Oct 6, 2022
2 parents 680107c + 3c5afb0 commit 5c64295
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 25 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-hooks.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name: databooks-meta
description:
"Remove Jupyter notebook metadata using `databooks`."
entry: databooks meta --overwrite
entry: databooks meta --yes
language: python
minimum_pre_commit_version: 2.9.2
types: [jupyter]
Expand Down
18 changes: 11 additions & 7 deletions databooks/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
TextColumn,
TimeElapsedColumn,
)
from rich.prompt import Confirm
from typer import Argument, BadParameter, Context, Exit, Option, Typer, echo

from databooks.affirm import affirm_all
Expand Down Expand Up @@ -107,9 +108,7 @@ def meta(
(),
help="Other (excluding `execution_counts` and `outputs`) cell fields to keep",
),
overwrite: bool = Option(
False, "--overwrite", "-w", help="Confirm overwrite of files"
),
overwrite: bool = Option(False, "--yes", "-y", help="Confirm overwrite of files"),
check: bool = Option(
False,
"--check",
Expand Down Expand Up @@ -140,11 +139,16 @@ def meta(
nb_paths = _check_paths(paths=paths, ignore=ignore)

if not bool(prefix + suffix) and not check:
if not overwrite:
raise BadParameter(
"No prefix nor suffix were passed."
" Please specify `--overwrite` or `-w` to overwrite files."
overwrite = (
Confirm.ask(
f"{len(nb_paths)} files will be overwritten"
" (no prefix nor suffix was passed). Continue?"
)
if not overwrite
else overwrite
)
if not overwrite:
raise Exit()
else:
logger.warning(f"{len(nb_paths)} files will be overwritten")

Expand Down
9 changes: 5 additions & 4 deletions databooks/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ def get_logger(name: str) -> logging.Logger:
def set_verbose(logger: logging.Logger) -> None:
"""Set logger to DEBUG level when user requests verbosity."""
verbose_level = logging.DEBUG
logger.setLevel(verbose_level)
logger.debug(
f"Verbose mode: setting log level to {logging.getLevelName(verbose_level)}"
)
if logger.level < verbose_level:
logger.setLevel(logging.DEBUG)
logger.debug(
f"Verbose mode: setting log level to {logging.getLevelName(verbose_level)}"
)
2 changes: 1 addition & 1 deletion docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ $ databooks meta [OPTIONS] PATHS...
* `--nb-meta-keep TEXT`: Notebook metadata fields to keep [default: ]
* `--cell-meta-keep TEXT`: Cells metadata fields to keep [default: ]
* `--cell-fields-keep TEXT`: Other (excluding `execution_counts` and `outputs`) cell fields to keep [default: ]
* `-w, --overwrite`: Confirm overwrite of files [default: False]
* `-y, --yes`: Confirm overwrite of files [default: False]
* `--check`: Don't write files but check whether there is unwanted metadata [default: False]
* `-v, --verbose`: Log processed files in console [default: False]
* `-c, --config PATH`: Get CLI options from configuration file
Expand Down
10 changes: 5 additions & 5 deletions tests/files/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
[tool.databooks.meta]
rm-outs=true
rm_exec=false
overwrite=true
rm-outs = true
rm_exec = false
overwrite = true

[tool.databooks.fix]
metadata-head=false
metadata-head = false

[tool.databooks.assert]
expr = ["[c.execution_count for c in exec_cells] == list(range(1, len(exec_cells) + 1))"]
recipe = ["seq-exec", "has-tags"]
ignore=[".ipynb_checkpoints/*"]
ignore = [".ipynb_checkpoints/*"]

[tool.databooks.test-config]
config-default = "config-value"
33 changes: 26 additions & 7 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def test_meta(tmpdir: LocalPath) -> None:
TestJupyterNotebook().jupyter_notebook.write(read_path)

nb_read = JupyterNotebook.parse_file(path=read_path)
result = runner.invoke(app, ["meta", str(read_path), "--overwrite"])
result = runner.invoke(app, ["meta", str(read_path), "--yes"])
nb_write = JupyterNotebook.parse_file(path=read_path)

assert result.exit_code == 0
Expand Down Expand Up @@ -88,7 +88,7 @@ def test_meta__check(tmpdir: LocalPath, caplog: LogCaptureFixture) -> None:
assert logs[0].message == "Found unwanted metadata in 1 out of 1 files."

# Clean notebook and check again
runner.invoke(app, ["meta", str(read_path), "--overwrite"])
runner.invoke(app, ["meta", str(read_path), "--yes"])
result = runner.invoke(app, ["meta", str(read_path), "--check"])

logs = list(caplog.records)
Expand Down Expand Up @@ -138,15 +138,34 @@ def test_meta__script(tmpdir: LocalPath) -> None:
)


def test_meta__no_overwrite(tmpdir: LocalPath) -> None:
"""Raise `typer.BadParameter` when no `--overwrite` and no prefix nor suffix."""
def test_meta__no_confirm(tmpdir: LocalPath) -> None:
"""Don't make any changes without confirmation to overwrite files (prompt)."""
nb_path = tmpdir.mkdir("notebooks") / "test_meta_nb.ipynb" # type: ignore
TestJupyterNotebook().jupyter_notebook.write(nb_path)

result = runner.invoke(app, ["meta", str(nb_path)])
assert (
"No prefix nor suffix were passed. Please specify `--overwrite` or `-w` to"
" overwrite files." in result.output

assert result.exit_code == 1
assert JupyterNotebook.parse_file(nb_path) == TestJupyterNotebook().jupyter_notebook
assert result.output == (
"1 files will be overwritten (no prefix nor suffix was passed)."
" Continue? [y/n]: \nAborted!\n"
)


def test_meta__confirm(tmpdir: LocalPath) -> None:
"""Make changes when confirming overwrite via the prompt."""
nb_path = tmpdir.mkdir("notebooks") / "test_meta_nb.ipynb" # type: ignore
TestJupyterNotebook().jupyter_notebook.write(nb_path)

result = runner.invoke(app, ["meta", str(nb_path)], input="y")

assert result.exit_code == 0
assert JupyterNotebook.parse_file(nb_path) != TestJupyterNotebook().jupyter_notebook
assert result.output == (
"1 files will be overwritten (no prefix nor suffix was passed)."
" Continue? [y/n]:"
" Removing metadata ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00\n"
)


Expand Down

0 comments on commit 5c64295

Please sign in to comment.