From 1df9ef8734b6474e120debce1274d9a449354cd5 Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Mon, 29 May 2023 17:05:48 -0700 Subject: [PATCH] Add edit command --- intake/cli.py | 43 ++++++++++++++++++++++++++++++++++++++ tests/source02/intake.json | 9 ++++++++ 2 files changed, 52 insertions(+) create mode 100644 tests/source02/intake.json diff --git a/intake/cli.py b/intake/cli.py index 315a56c..754a366 100644 --- a/intake/cli.py +++ b/intake/cli.py @@ -1,7 +1,9 @@ from pathlib import Path import argparse +import json import os import os.path +import subprocess import sys from .source import fetch_items, LocalSource, update_items @@ -15,6 +17,47 @@ def intake_data_dir() -> Path: return intake_data +def cmd_edit(cmd_args): + """Open a source's config for editing.""" + parser = argparse.ArgumentParser( + prog="intake edit", + description=cmd_edit.__doc__, + ) + parser.add_argument( + "--base", + default=intake_data_dir(), + help="Path to the intake data directory containing source directories", + ) + parser.add_argument( + "--source", + help="Source name to edit", + ) + args = parser.parse_args(cmd_args) + + editor_cmd = os.environ.get("EDITOR") + if not editor_cmd: + print("Cannot edit, no EDITOR set") + return 1 + + # Make a copy of the config + source = LocalSource(Path(args.base), args.source) + tmp_path = source.source_path / "intake.json.tmp" + tmp_path.write_text(json.dumps(source.get_config(), indent=2)) + + # Edit the config + subprocess.run([editor_cmd, tmp_path]) + + # Commit the change if the new config is valid + try: + json.load(tmp_path.open()) + except json.JSONDecodeError: + print("Invalid JSON") + return 1 + tmp_path.replace(source.source_path / "intake.json") + + return 0 + + def cmd_update(cmd_args): """Fetch items for a source and update it.""" parser = argparse.ArgumentParser( diff --git a/tests/source02/intake.json b/tests/source02/intake.json new file mode 100644 index 0000000..17cdb70 --- /dev/null +++ b/tests/source02/intake.json @@ -0,0 +1,9 @@ +{ + "fetch": { + "exe": "sh", + "args": [ + "-c", + "echo {\\\"id\\\": \\\"$(date +%Y-%m-%d-%H-%M)\\\"}" + ] + } +}