Skip to main content

yaml2cmd_build/
lib.rs

1use std::fmt::Write;
2use std::fs;
3use std::path::Path;
4
5#[derive(serde::Deserialize, Debug)]
6struct Config {
7    commands: Vec<CommandDef>,
8}
9
10#[derive(serde::Deserialize, Debug, Clone)]
11struct CommandDef {
12    name: String,
13    about: String,
14    args: Option<Vec<ArgDef>>,
15    hidden: Option<bool>,
16    subcommands: Option<Vec<Self>>,
17    multiple_values: Option<bool>,
18
19    #[cfg(not(debug_assertions))]
20    #[serde(default)]
21    debug_only: bool,
22
23    aliases: Option<Vec<String>>,
24}
25
26#[derive(serde::Deserialize, Debug, Clone)]
27struct ArgDef {
28    name: String,
29    short: Option<char>,
30    long: Option<String>,
31    help: Option<String>,
32    value_name: Option<String>,
33    required: Option<bool>,
34    num_args: Option<String>,
35    action: Option<String>,
36    default_value: Option<String>,
37    conflicts_with: Option<String>,
38    value_parser: Option<String>,
39}
40
41/// 映射action字符串到clap枚举
42fn map_action(s: &str) -> &'static str {
43    match s {
44        "set_true" => "clap::ArgAction::SetTrue",
45        "append" => "clap::ArgAction::Append",
46        "set_false" => "clap::ArgAction::SetFalse",
47        "count" => "clap::ArgAction::Count",
48        _ => "clap::ArgAction::Set",
49    }
50}
51
52/// 解析 `num_args` 范围字符串,转为rust合法代码
53fn parse_num_args(s: &str) -> String {
54    match s {
55        "0.." => "0..".to_string(),
56        "1.." => "1..".to_string(),
57        "0..1" => "0..1".to_string(),
58        "0..=" => "0..=".to_string(),
59        val if val.parse::<usize>().is_ok() => val.to_string(),
60        _ => panic!("invalid num_args range: {s}"),
61    }
62}
63
64/// 转义字符串
65fn escape_str(s: &str) -> String {
66    s.replace('\\', "\\\\").replace('"', "\\\"")
67}
68
69/// 递归构建Command代码字符串
70fn build_command(c: &CommandDef) -> String {
71    let mut code = String::new();
72    let about = escape_str(&c.about);
73    write!(code, "Command::new(\"{}\").about(\"{}\")", escape_str(&c.name), about).unwrap();
74
75    if let Some(aliases) = &c.aliases {
76        for alias in aliases {
77            write!(code, ".alias(\"{}\")", escape_str(alias)).unwrap();
78        }
79    }
80
81    if c.hidden == Some(true) {
82        code.push_str(".hide(true)");
83    }
84
85    if c.multiple_values == Some(false)
86        && let Some(args) = &c.args
87    {
88        let mut group =
89            format!("clap::ArgGroup::new(\"{}_exclusive\").multiple(false)", escape_str(&c.name));
90        for arg in args {
91            write!(group, ".arg(\"{}\")", escape_str(&arg.name)).unwrap();
92        }
93        write!(code, ".group({group})").unwrap();
94    }
95
96    if let Some(args) = &c.args {
97        for a in args {
98            let mut arg = format!("Arg::new(\"{}\")", escape_str(&a.name));
99
100            if let Some(c) = a.short {
101                write!(arg, ".short('{c}')").unwrap();
102            }
103            if let Some(l) = &a.long {
104                write!(arg, ".long(\"{}\")", escape_str(l)).unwrap();
105            }
106            if let Some(h) = &a.help {
107                write!(arg, ".help(\"{}\")", escape_str(h)).unwrap();
108            }
109            if let Some(vn) = &a.value_name {
110                write!(arg, ".value_name(\"{}\")", escape_str(vn)).unwrap();
111            }
112            if a.required == Some(true) {
113                arg.push_str(".required(true)");
114            }
115            if let Some(n) = &a.num_args {
116                let range = parse_num_args(n);
117                write!(arg, ".num_args({range})").unwrap();
118            }
119            if let Some(act) = &a.action {
120                write!(arg, ".action({})", map_action(act)).unwrap();
121            }
122            if let Some(dv) = &a.default_value {
123                write!(arg, ".default_value(\"{}\")", escape_str(dv)).unwrap();
124            }
125
126            if let Some(vp) = &a.value_parser {
127                write!(arg, ".value_parser(clap::value_parser!({vp}))").unwrap();
128            }
129
130            if let Some(cf) = &a.conflicts_with {
131                write!(arg, ".conflicts_with(\"{}\")", escape_str(cf)).unwrap();
132            }
133
134            write!(code, ".arg({arg})").unwrap();
135        }
136    }
137
138    if let Some(mut subcommands) = c.subcommands.clone() {
139        subcommands.sort_by(|a, b| a.name.cmp(&b.name));
140        for sub in subcommands {
141            let sub_code = build_command(&sub);
142            write!(code, ".subcommand({sub_code})").unwrap();
143        }
144    }
145
146    code
147}
148
149/// 从 YAML 生成 clap 命令代码
150///
151/// # Panics
152///
153/// 如果 `OUT_DIR` 环境变量未设置,或 YAML 解析失败,或文件写入失败。
154pub fn build_with_yaml(yaml: &str) {
155    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR environment variable not set");
156    let dest = Path::new(&out_dir).join("command.rs");
157    if let Some(parent) = dest.parent() {
158        fs::create_dir_all(parent).expect("Failed create command dir");
159    }
160
161    // let yaml_path = Path::new("./commands.yaml");
162    // let yaml = fs::read_to_string(yaml_path).expect("Cannot read ./commands.yaml, file missing");
163    let config: Config =
164        serde_yaml::from_str(yaml).expect("commands.yaml yaml parse failed, check syntax");
165
166    let mut commands = config.commands;
167
168    #[cfg(not(debug_assertions))]
169    commands.retain(|c| !c.debug_only);
170
171    commands.sort_by(|a, b| a.name.cmp(&b.name));
172
173    let mut code = String::new();
174    code.push_str("use clap::{Arg, Command};\n");
175    code.push_str("pub fn add_commands(mut cmd: Command) -> Command {\n");
176
177    for c in commands {
178        let cmd_code = build_command(&c);
179        writeln!(code, "    cmd = cmd.subcommand({cmd_code});").unwrap();
180    }
181
182    code.push_str("    cmd\n");
183    code.push_str("}\n");
184
185    let need_write = if dest.exists() {
186        fs::read_to_string(&dest).ok().is_none_or(|old| old != code)
187    } else {
188        true
189    };
190
191    if need_write {
192        fs::write(&dest, code).expect("Failed write generated cmd code");
193    }
194
195    // println!("cargo:rerun-if-changed={}", yaml_path.display());
196}