-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathcli.py
More file actions
238 lines (200 loc) Β· 6.1 KB
/
cli.py
File metadata and controls
238 lines (200 loc) Β· 6.1 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# Copyright (c) 2025 TOON Format Organization
# SPDX-License-Identifier: MIT
"""Command-line interface for TOON encoding/decoding.
Provides the `toon` command-line tool for converting between JSON and TOON formats.
Supports auto-detection based on file extensions and content, with options for
delimiters, indentation, and validation modes.
"""
import argparse
import json
import sys
from pathlib import Path
from . import decode, encode
from .types import DecodeOptions, EncodeOptions
from .utils import compare_formats
def main() -> int:
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
prog="toon",
description="Convert between JSON and TOON formats",
)
parser.add_argument(
"input",
type=str,
help="Input file path (or - for stdin)",
)
parser.add_argument(
"-o",
"--output",
type=str,
help="Output file path (prints to stdout if omitted)",
)
parser.add_argument(
"-e",
"--encode",
action="store_true",
help="Force encode mode (overrides auto-detection)",
)
parser.add_argument(
"-d",
"--decode",
action="store_true",
help="Force decode mode (overrides auto-detection)",
)
parser.add_argument(
"--delimiter",
type=str,
choices=[",", "\t", "|"],
default=",",
help='Array delimiter: , (comma), \\t (tab), | (pipe) (default: ",")',
)
parser.add_argument(
"--indent",
type=int,
default=2,
help="Indentation size (default: 2)",
)
parser.add_argument(
"--length-marker",
action="store_true",
help="Add # prefix to array lengths (e.g., items[#3])",
)
parser.add_argument(
"--no-strict",
action="store_true",
help="Disable strict validation when decoding",
)
parser.add_argument(
"--stats",
action="store_true",
help="Show token count estimates and savings (encode only)",
)
args = parser.parse_args()
# Read input
try:
if args.input == "-":
input_text = sys.stdin.read()
input_path = None
else:
input_path = Path(args.input)
if not input_path.exists():
print(f"Error: Input file not found: {args.input}", file=sys.stderr)
return 1
input_text = input_path.read_text(encoding="utf-8")
except Exception as e:
print(f"Error reading input: {e}", file=sys.stderr)
return 1
# Determine operation mode
if args.encode and args.decode:
print("Error: Cannot specify both --encode and --decode", file=sys.stderr)
return 1
if args.encode:
mode = "encode"
elif args.decode:
mode = "decode"
else:
# Auto-detect based on file extension
if input_path:
if input_path.suffix.lower() == ".json":
mode = "encode"
elif input_path.suffix.lower() == ".toon":
mode = "decode"
else:
# Try to detect by content
try:
json.loads(input_text)
mode = "encode"
except json.JSONDecodeError:
mode = "decode"
else:
# No file path, try to detect by content
try:
json.loads(input_text)
mode = "encode"
except json.JSONDecodeError:
mode = "decode"
# Handle --stats with decode mode
if args.stats and mode == "decode":
print("Warning: --stats is only available in encode mode", file=sys.stderr)
args.stats = False
# Process
try:
if mode == "encode":
output_text = encode_json_to_toon(
input_text,
delimiter=args.delimiter,
indent=args.indent,
length_marker=args.length_marker,
)
# Show stats if requested
if args.stats:
try:
data = json.loads(input_text)
print("\n" + compare_formats(data))
except RuntimeError as e:
# tiktoken not installed
print(f"\n {e}", file=sys.stderr)
else:
output_text = decode_toon_to_json(
input_text,
indent=args.indent,
strict=not args.no_strict,
)
except Exception as e:
print(f"Error during {mode}: {e}", file=sys.stderr)
return 1
# Write output
try:
if args.output:
output_path = Path(args.output)
output_path.write_text(output_text, encoding="utf-8")
else:
print(output_text)
except Exception as e:
print(f"Error writing output: {e}", file=sys.stderr)
return 1
return 0
def encode_json_to_toon(
json_text: str,
delimiter: str = ",",
indent: int = 2,
length_marker: bool = False,
) -> str:
"""Encode JSON text to TOON format.
Args:
json_text: JSON input string
delimiter: Delimiter character
indent: Indentation size
length_marker: Whether to add # prefix
Returns:
TOON-formatted string
Raises:
json.JSONDecodeError: If JSON is invalid
"""
data = json.loads(json_text)
options: EncodeOptions = {
"indent": indent,
"delimiter": delimiter,
"lengthMarker": "#" if length_marker else False,
}
return encode(data, options)
def decode_toon_to_json(
toon_text: str,
indent: int = 2,
strict: bool = True,
) -> str:
"""Decode TOON text to JSON format.
Args:
toon_text: TOON input string
indent: Indentation size
strict: Whether to use strict validation
Returns:
JSON-formatted string
Raises:
ToonDecodeError: If TOON is invalid
"""
options = DecodeOptions(indent=indent, strict=strict)
data = decode(toon_text, options)
return json.dumps(data, indent=2, ensure_ascii=False)
if __name__ == "__main__":
sys.exit(main())