Skip to content

Commit 24c21dc

Browse files
authored
Add --scalar flag to CLI (#280)
* initial test and impl of --scalar * fix packaging tox job
1 parent 5cef407 commit 24c21dc

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

glom/cli.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,14 @@
4343
CommandLineError,
4444
UsageError)
4545
from face.utils import isatty
46+
from boltons.iterutils import is_scalar
4647

4748
import glom
4849
from glom import Path, GlomError, Inspect
4950

50-
# TODO: --target-format scalar = unquoted if single value, error otherwise, maybe even don't output newline
51-
# TODO: --default
51+
# TODO: --default?
5252

53-
def glom_cli(target, spec, indent, debug, inspect):
53+
def glom_cli(target, spec, indent, debug, inspect, scalar):
5454
"""Command-line interface to the glom library, providing nested data
5555
access and data restructuring with the power of Python.
5656
"""
@@ -70,7 +70,11 @@ def glom_cli(target, spec, indent, debug, inspect):
7070

7171
if not indent:
7272
indent = None
73-
print(json.dumps(result, indent=indent, sort_keys=True))
73+
74+
if scalar and is_scalar(result):
75+
print(result, end='')
76+
else:
77+
print(json.dumps(result, indent=indent, sort_keys=True))
7478
return
7579

7680

@@ -86,7 +90,10 @@ def get_command():
8690

8791
cmd.add('--indent', int, missing=2,
8892
doc='number of spaces to indent the result, 0 to disable pretty-printing')
89-
93+
94+
cmd.add('--scalar', parse_as=True,
95+
doc="if the result is a single value (not a collection), output it"
96+
" without quotes or whitespace, for easier usage in scripts")
9097
cmd.add('--debug', parse_as=True, doc='interactively debug any errors that come up')
9198
cmd.add('--inspect', parse_as=True, doc='interactively explore the data')
9299
return cmd

glom/test/test_cli.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,14 @@ def test_cli_spec_argv_target_stdin_basic(cc):
6363
assert res.stdout == BASIC_OUT
6464

6565

66+
def test_cli_scalar(cc):
67+
res = cc.run(['glom', 'a.b.c', '{"a": {"b": {"c": "d"}}}'])
68+
assert res.stdout == '"d"\n'
69+
70+
res = cc.run(['glom', '--scalar', 'a.b.c', '{"a": {"b": {"c": "d"}}}'])
71+
assert res.stdout == 'd'
72+
73+
6674
def test_cli_spec_target_files_basic(cc, basic_spec_path, basic_target_path):
6775
res = cc.run(['glom', '--indent', '0', '--target-file',
6876
basic_target_path, '--spec-file', basic_spec_path])

0 commit comments

Comments
 (0)