-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·214 lines (168 loc) · 7.48 KB
/
Copy pathcli.py
File metadata and controls
executable file
·214 lines (168 loc) · 7.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env python3
"""jsonfold_cli.py - hybrid pretty/compact JSON output.
jsonfold wraps Python's standard json.dump/json.dumps output and keeps the
normal pretty-printed structure, but selectively compacts small containers and
runs of scalar items when they fit within a configured line width.
The goal is readable JSON:
- large or complex structures stay expanded;
- small lists and objects can stay on one line;
- adjacent scalar items can be packed together;
- nested folding is controlled by explicit depth limits.
Configuration
-------------
width
Maximum target line width. Lines are only packed/folded when the result
fits within this width.
pack_array_items / pack_obj_items
Maximum number of scalar list items or object properties that may be
packed onto one physical line.
pack_nesting
Maximum container depth where scalar packing is allowed.
fold_array_items / fold_obj_items
Maximum number of items/properties allowed when folding a container
onto one line.
fold_nesting
Maximum nested-container depth allowed in a folded line.
Presets
-------
Default ("")
Balanced default settings.
Up to 8 array elements, up to 4 key/value pairs, max nesting = 1
"none"
Disable all packing and folding.
"low":
Same as default, No nested structures in fold/join
"med":
Same as default, No nested structures in "join"
"classic":
Balanced default settings. Replicate traditional pretty-printing.
Up to 8 array elements, up to 4 key/value pairs, max nesting = 1
"default":
Balanced default setting - including conservative grid.
"high":
aggressive setting. Up to 16 array elements, up to key/value pairs, max nesting = 2
"max"
Unlimited packing, folding, grid and join subject to line width only.
Test Presets
-------------
"pack"
Enable packing only; disable folding.
"fold"
Enable folding only; disable packing.
"join"
Enable folding and joining.
"grid"
Enable packing/folding/grid (no join).
Streaming behavior
------------------
The implementation is designed as a streaming filter around json.dump().
It buffers only the currently open container frames needed to decide whether
packing/folding is still possible. Once a frame can no longer fold, older lines
are streamed forward.
Limitations
-----------
- Input must be normal json.dump(..., indent=N) style output.
- The filter assumes standard JSON syntax emitted by Python's json module.
- It is a formatting filter, not a validating JSON parser.
- Folding decisions are based on physical line structure, indentation,
item counts, nesting limits, and width.
CLI
---
jsonfold --demo
jsonfold < input.json
jsonfold --compact=max --width=100 < input.json
python jsonfold.py --pack-items=20 --fold-items=8 < input.json
"""
import sys
import argparse
from typing import Any
from dataclasses import replace
import json
from jsonfold import jsonfold_config, write_json, JSONFoldConfig, demo_data
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(
description="Read JSON from stdin; write folded JSON to stdout.")
p.add_argument("--demo", action="store_true")
p.add_argument("--compact", choices=JSONFoldConfig.PRESETS.keys(), default="default")
p.add_argument("--width", type=int, default=None, help="line width limit (default: terminal width/80)")
p.add_argument("--verbose", "-v", action="store_true", help="Enable verbose/debug output")
p.add_argument("--input", "-i", metavar="FILE", help="Read JSON input from file instead of stdin")
# Pack phase
g = p.add_argument_group("pack phase (combine scalars N-per-line)")
g.add_argument("--pack-items", type=int, default=None,
help="set both --pack-array-items and --pack-obj-items")
g.add_argument("--pack-array-items", type=int, default=None)
g.add_argument("--pack-obj-items", type=int, default=None)
g.add_argument("--pack-nesting", type=int, default=None)
# Fold phase
g = p.add_argument_group("fold phase (collapse single-content-line containers)")
g.add_argument("--fold-items", type=int, default=None,
help="set both --fold-array-items and --fold-obj-items")
g.add_argument("--fold-array-items", type=int, default=None)
g.add_argument("--fold-obj-items", type=int, default=None)
g.add_argument("--fold-nesting", type=int, default=None)
# Grid phase
g = p.add_argument_group("Grid phase (align folded lines on grid)")
g.add_argument("--grid-items", type=int, default=None,
help="set both --grid-array-items and --grid-obj-items")
g.add_argument("--grid-array-items", type=int, default=None)
g.add_argument("--grid-obj-items", type=int, default=None)
g.add_argument("--grid-min-lines", type=int, default=None)
g.add_argument("--grid-max-lines", type=int, default=None)
# Join phase
g = p.add_argument_group("Join phase (combine scalars/folded containers)")
g.add_argument("--join-items", type=int, default=None,
help="set both --join-array-items and --join-obj-items")
g.add_argument("--join-array-items", type=int, default=None)
g.add_argument("--join-obj-items", type=int, default=None)
g.add_argument("--join-nesting", type=int, default=None)
p.add_argument("--indent", type=int, default=2)
p.add_argument("--sort-keys", action="store_true")
args = p.parse_args(argv)
overrides: dict[str, int] = {}
# Convenience shorthands (lower priority than individual flags).
if args.pack_items is not None:
overrides["pack_array_items"] = args.pack_items
overrides["pack_obj_items"] = args.pack_items
if args.fold_items is not None:
overrides["fold_array_items"] = args.fold_items
overrides["fold_obj_items"] = args.fold_items
if args.join_items is not None:
overrides["join_array_items"] = args.join_items
overrides["join_obj_items"] = args.join_items
# Individual flags (higher priority — applied after shorthands).
for key in (
"pack_array_items", "pack_obj_items", "pack_nesting",
"fold_array_items", "fold_obj_items", "fold_nesting",
"join_array_items", "join_obj_items", "join_nesting",
):
val = getattr(args, key)
if val is not None:
overrides[key] = val
width = args.width
if width is None:
if sys.stdout.isatty():
import shutil
columns = shutil.get_terminal_size(fallback=(0,0)).columns
if columns:
width = columns
overrides["width"] = width
cfg = jsonfold_config(args.compact, **overrides)
if args.verbose:
print(cfg, file= sys.stderr)
if args.demo:
data = demo_data()
else:
fp = open(args.input) if args.input else sys.stdin
with fp:
data = json.load(fp)
info = write_json(data, sys.stdout, width = width, config=cfg, indent=args.indent,
sort_keys=args.sort_keys)
if args.verbose:
print(info, file=sys.stderr)
return 0
if __name__ == "__main__":
raise SystemExit(main())