Skip to content

Commit cee4d2f

Browse files
committed
refactor(cli): extract parser crate
Move the hand-written ccusage CLI parser, help spec, and parser snapshots into a new internal ccusage-cli workspace crate. This keeps parser tests focused and gives future parser experiments a narrow crate boundary without adding a runtime parser dependency. Keep the main ccusage crate responsible for config discovery by passing ConfigContext through the new CliConfig trait. Move CLI help generation into the new crate build script and pre-render merged option sections at build time to avoid runtime option concatenation for common contextual help output. The runtime crate now re-exports the extracted CLI types through its existing cli module and uses a local TerminalStyle helper where the extracted SharedArgs type can no longer satisfy the orphan rules.
1 parent bf84d4b commit cee4d2f

22 files changed

Lines changed: 2909 additions & 2706 deletions

‎rust/Cargo.lock‎

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rust/Cargo.toml‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
[workspace]
2-
members = ["crates/ccusage", "crates/ccusage-terminal", "crates/ccusage-test-support"]
2+
members = [
3+
"crates/ccusage",
4+
"crates/ccusage-cli",
5+
"crates/ccusage-terminal",
6+
"crates/ccusage-test-support",
7+
]
38
resolver = "2"
49

510
[profile.release]

‎rust/crates/ccusage-cli/Cargo.toml‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[package]
2+
name = "ccusage-cli"
3+
version = "20.0.4"
4+
edition = "2021"
5+
build = "build.rs"
6+
7+
[dependencies]
8+
9+
[build-dependencies]
10+
serde_json = "1"
11+
12+
[dev-dependencies]
13+
insta = { version = "1.47.2", features = ["json"] }
14+
serde_json = "1"

‎rust/crates/ccusage-cli/build.rs‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
use std::{collections::BTreeMap, env, fs, path::PathBuf};
2+
3+
use serde_json::{Map, Value};
4+
5+
const CLI_HELP_JSON: &str = "src/cli-help.json";
6+
7+
fn main() {
8+
println!("cargo:rerun-if-changed={CLI_HELP_JSON}");
9+
generate_cli_help_rs();
10+
}
11+
12+
fn out_dir_path(file_name: &str) -> PathBuf {
13+
PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR is set by cargo")).join(file_name)
14+
}
15+
16+
fn generate_cli_help_rs() {
17+
let source = fs::read_to_string(CLI_HELP_JSON).expect("read CLI help spec");
18+
let Value::Object(option_sets) =
19+
serde_json::from_str::<Value>(&source).expect("parse CLI help spec")
20+
else {
21+
panic!("CLI help spec must be a JSON object");
22+
};
23+
24+
let mut output = String::from("// @generated by build.rs\n\n");
25+
let mut rendered_options = BTreeMap::new();
26+
let mut option_sets = option_sets.iter().collect::<Vec<_>>();
27+
option_sets.sort_by(|(left, _), (right, _)| left.cmp(right));
28+
for (function_name, options) in option_sets {
29+
let rendered = render_options(options);
30+
rendered_options.insert(function_name.to_string(), rendered.clone());
31+
output.push_str(&format!(
32+
"#[allow(dead_code)]\nfn {function_name}() -> &'static str {{\n {}\n}}\n\n",
33+
rust_string_literal(&rendered)
34+
));
35+
}
36+
for (function_name, parts) in [
37+
(
38+
"all_agent_session_options",
39+
&["all_agent_options", "session_options"][..],
40+
),
41+
(
42+
"claude_daily_options",
43+
&["shared_claude_options", "daily_options"][..],
44+
),
45+
(
46+
"claude_weekly_options",
47+
&["shared_claude_options", "weekly_options"][..],
48+
),
49+
(
50+
"claude_session_options",
51+
&["shared_claude_options", "session_options"][..],
52+
),
53+
(
54+
"blocks_combined_options",
55+
&["shared_claude_options", "blocks_options"][..],
56+
),
57+
("pi_combined_options", &["agent_options", "pi_options"][..]),
58+
(
59+
"openclaw_combined_options",
60+
&["agent_options", "openclaw_options"][..],
61+
),
62+
] {
63+
let rendered = render_combined_options(&rendered_options, parts);
64+
output.push_str(&format!(
65+
"#[allow(dead_code)]\nfn {function_name}() -> &'static str {{\n {}\n}}\n\n",
66+
rust_string_literal(&rendered)
67+
));
68+
}
69+
fs::write(out_dir_path("cli-help.rs"), output).expect("write generated CLI help");
70+
}
71+
72+
fn render_options(options: &Value) -> String {
73+
let Value::Array(options) = options else {
74+
panic!("CLI help option set must be an array");
75+
};
76+
let width = options
77+
.iter()
78+
.map(|option| {
79+
let Value::Object(option) = option else {
80+
panic!("CLI help option must be an object");
81+
};
82+
string_field(option, "flags").len()
83+
})
84+
.max()
85+
.unwrap_or(36)
86+
.max(36);
87+
let mut lines = vec!["OPTIONS:".to_string()];
88+
for option in options {
89+
let Value::Object(option) = option else {
90+
panic!("CLI help option must be an object");
91+
};
92+
let flags = string_field(option, "flags");
93+
let description = string_field(option, "description");
94+
let mut line = format!(" {flags:<width$} {description}");
95+
let mut details = Vec::new();
96+
if let Some(default) = optional_string_field(option, "default") {
97+
details.push(format!("default: {default}"));
98+
}
99+
if let Some(choices) = option.get("choices") {
100+
let Value::Array(choices) = choices else {
101+
panic!("CLI help choices must be an array");
102+
};
103+
if !choices.is_empty() {
104+
details.push(format!(
105+
"choices: {}",
106+
choices
107+
.iter()
108+
.map(|choice| {
109+
choice
110+
.as_str()
111+
.expect("CLI help choice must be a string")
112+
.to_string()
113+
})
114+
.collect::<Vec<_>>()
115+
.join(" | ")
116+
));
117+
}
118+
}
119+
if !details.is_empty() {
120+
line.push_str(&format!(" ({})", details.join(", ")));
121+
}
122+
lines.push(line);
123+
}
124+
lines.join("\n")
125+
}
126+
127+
fn render_combined_options(options: &BTreeMap<String, String>, parts: &[&str]) -> String {
128+
let option_lines = parts
129+
.iter()
130+
.flat_map(|part| {
131+
options
132+
.get(*part)
133+
.unwrap_or_else(|| panic!("missing generated option set {part}"))
134+
.lines()
135+
.skip(1)
136+
})
137+
.collect::<Vec<_>>()
138+
.join("\n");
139+
format!("OPTIONS:\n{option_lines}")
140+
}
141+
142+
fn string_field(object: &Map<String, Value>, field: &str) -> String {
143+
optional_string_field(object, field).unwrap_or_else(|| panic!("missing CLI help field {field}"))
144+
}
145+
146+
fn optional_string_field(object: &Map<String, Value>, field: &str) -> Option<String> {
147+
object.get(field).map(|value| {
148+
value
149+
.as_str()
150+
.unwrap_or_else(|| panic!("CLI help field {field} must be a string"))
151+
.to_string()
152+
})
153+
}
154+
155+
fn rust_string_literal(value: &str) -> String {
156+
serde_json::to_string(value).expect("encode Rust string literal")
157+
}

0 commit comments

Comments
 (0)