Skip to content

Commit

Permalink
Add --scalar flag to CLI (#280)
Browse files Browse the repository at this point in the history
* initial test and impl of --scalar

* fix packaging tox job
  • Loading branch information
mahmoud authored Nov 2, 2024
1 parent 5cef407 commit 24c21dc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
17 changes: 12 additions & 5 deletions glom/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand All @@ -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


Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions glom/test/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down

0 comments on commit 24c21dc

Please sign in to comment.