Skip to content

Commit 7e21dca

Browse files
committed
refactor(cli): split generic parser and help modules
Keep the extracted ccusage-cli crate from becoming another large ccusage-specific lib.rs. Move generic argument tokenization into arg_parser.rs, generic help rendering into help.rs, and build-time help source generation into a tested help_codegen module. Move ccusage command/help shape into cli-commands.json so help.rs only routes generic command pages and option sets. The build script now pre-renders combined option strings and generated help page data from JSON at build time, keeping runtime dependency-free and lookup-based. Also address the review finding where the deprecated global -a agent-filter check rejected the valid blocks active flag. Exact -a is now allowed for ccusage blocks and ccusage claude blocks, with parser regressions for both forms. Validation: direnv exec . cargo test --manifest-path rust/Cargo.toml -p ccusage-cli; direnv exec . env -u CFLAGS cargo check --manifest-path rust/Cargo.toml -p ccusage-cli -p ccusage; direnv exec . env -u CFLAGS pnpm run test; direnv exec . pnpm run format.
1 parent 0ed3c6a commit 7e21dca

9 files changed

Lines changed: 3397 additions & 2784 deletions

File tree

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

Lines changed: 13 additions & 141 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
1-
use std::{collections::BTreeMap, env, fs, path::PathBuf};
1+
use std::{env, fs, path::PathBuf};
22

3-
use serde_json::{Map, Value};
3+
use serde_json::Value;
4+
5+
#[path = "src/help_codegen.rs"]
6+
mod help_codegen;
47

58
const CLI_HELP_JSON: &str = "src/cli-help.json";
9+
const CLI_COMMANDS_JSON: &str = "src/cli-commands.json";
610

711
fn main() {
812
println!("cargo:rerun-if-changed={CLI_HELP_JSON}");
13+
println!("cargo:rerun-if-changed={CLI_COMMANDS_JSON}");
914
generate_cli_help_rs();
1015
}
1116

@@ -14,144 +19,11 @@ fn out_dir_path(file_name: &str) -> PathBuf {
1419
}
1520

1621
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-
}
22+
let option_source = fs::read_to_string(CLI_HELP_JSON).expect("read CLI help spec");
23+
let command_source = fs::read_to_string(CLI_COMMANDS_JSON).expect("read CLI command spec");
24+
let option_sets = serde_json::from_str::<Value>(&option_source).expect("parse CLI help spec");
25+
let command_spec =
26+
serde_json::from_str::<Value>(&command_source).expect("parse CLI command spec");
27+
let output = help_codegen::generate_cli_help_source(&option_sets, &command_spec);
6928
fs::write(out_dir_path("cli-help.rs"), output).expect("write generated CLI help");
7029
}
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-
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
use std::ffi::OsString;
2+
3+
pub(crate) struct ArgParser {
4+
pub(crate) args: Vec<String>,
5+
index: usize,
6+
pending_value: Option<String>,
7+
}
8+
9+
impl ArgParser {
10+
pub(crate) fn new(args: Vec<OsString>) -> Result<Self, String> {
11+
let mut parsed = Vec::with_capacity(args.len());
12+
for arg in args {
13+
parsed.push(
14+
arg.into_string()
15+
.map_err(|_| "Arguments must be valid UTF-8".to_string())?,
16+
);
17+
}
18+
Ok(Self {
19+
args: parsed,
20+
index: 0,
21+
pending_value: None,
22+
})
23+
}
24+
25+
pub(crate) fn peek(&self) -> Option<&str> {
26+
self.args.get(self.index).map(String::as_str)
27+
}
28+
29+
pub(crate) fn next(&mut self) -> Option<String> {
30+
let value = self.args.get(self.index)?.clone();
31+
self.index += 1;
32+
Some(value)
33+
}
34+
35+
pub(crate) fn next_flag(&mut self) -> Result<String, String> {
36+
let arg = self
37+
.next()
38+
.ok_or_else(|| "Expected option but reached end of arguments".to_string())?;
39+
if let Some((flag, value)) = arg.split_once('=') {
40+
self.pending_value = Some(value.to_string());
41+
return Ok(flag.to_string());
42+
}
43+
if arg.starts_with('-') {
44+
Ok(arg)
45+
} else {
46+
Err(format!("Expected option, got '{arg}'"))
47+
}
48+
}
49+
50+
pub(crate) fn value_for(&mut self, flag: &str) -> Result<String, String> {
51+
if let Some(value) = self.pending_value.take() {
52+
if value.is_empty() {
53+
return Err(format!("Missing value for {flag}"));
54+
}
55+
return Ok(value);
56+
}
57+
let value = self
58+
.next()
59+
.ok_or_else(|| format!("Missing value for {flag}"))?;
60+
if value.starts_with('-') {
61+
return Err(format!("Missing value for {flag}"));
62+
}
63+
Ok(value)
64+
}
65+
}

0 commit comments

Comments
 (0)