From eed98ddd29ef3a95a7b0625d042cf81e0da16c71 Mon Sep 17 00:00:00 2001 From: Mahmoud Hashemi Date: Sun, 17 Dec 2023 17:51:38 -0800 Subject: [PATCH] initial test and impl of --scalar --- glom/cli.py | 17 ++++++++++++----- glom/test/test_cli.py | 8 ++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/glom/cli.py b/glom/cli.py index 3f8f744..21488f5 100644 --- a/glom/cli.py +++ b/glom/cli.py @@ -43,14 +43,14 @@ CommandLineError, UsageError) from face.utils import isatty +from boltons.iterutils import is_scalar import glom from glom import Path, GlomError, Inspect -# TODO: --target-format scalar = unquoted if single value, error otherwise, maybe even don't output newline -# TODO: --default +# TODO: --default? -def glom_cli(target, spec, indent, debug, inspect): +def glom_cli(target, spec, indent, debug, inspect, scalar): """Command-line interface to the glom library, providing nested data access and data restructuring with the power of Python. """ @@ -70,7 +70,11 @@ def glom_cli(target, spec, indent, debug, inspect): if not indent: indent = None - print(json.dumps(result, indent=indent, sort_keys=True)) + + if scalar and is_scalar(result): + print(result, end='') + else: + print(json.dumps(result, indent=indent, sort_keys=True)) return @@ -86,7 +90,10 @@ def get_command(): cmd.add('--indent', int, missing=2, doc='number of spaces to indent the result, 0 to disable pretty-printing') - + + cmd.add('--scalar', parse_as=True, + doc="if the result is a single value (not a collection), output it" + " without quotes or whitespace, for easier usage in scripts") cmd.add('--debug', parse_as=True, doc='interactively debug any errors that come up') cmd.add('--inspect', parse_as=True, doc='interactively explore the data') return cmd diff --git a/glom/test/test_cli.py b/glom/test/test_cli.py index 54607a3..bfd78c7 100644 --- a/glom/test/test_cli.py +++ b/glom/test/test_cli.py @@ -63,6 +63,14 @@ def test_cli_spec_argv_target_stdin_basic(cc): assert res.stdout == BASIC_OUT +def test_cli_scalar(cc): + res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == '"d"\n' + + res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}']) + assert res.stdout == 'd' + + def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path): res = cc.run(['glom', '--indent', '0', '--target-file', basic_target_path, '--spec-file', basic_spec_path])