Skip to main content

cpa_plugin/
cli.rs

1//! Command-line plugins (internal/pluginhost/command_line.go).
2//!
3//! Plugins declare flags before the main parse; the binary's Go-rules flag parser asks
4//! [`Host::command_line_flag`] for names it does not know and records values with
5//! [`Host::set_command_line_flag`]. When any plugin flag was given,
6//! [`Host::execute_command_line`] runs the owning plugins instead of the server.
7
8use cpa_core::gostr::GoStr;
9use std::collections::BTreeMap;
10
11use bytes::Bytes;
12
13use crate::abi::method;
14use crate::api::{
15    CommandLineExecutionRequest, CommandLineExecutionResponse, CommandLineFlagValue, CommandLineRegistrationRequest,
16    CommandLineRegistrationResponse,
17};
18use crate::auth::PluginAuth;
19use crate::host::Host;
20use cpa_core::config::parse_duration;
21
22/// One registered plugin flag (Go `commandLineFlagRecord`).
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct CliFlag {
25    pub plugin_id: String,
26    pub name: String,
27    pub usage: String,
28    /// bool, string, int, int64, float64 or duration.
29    pub kind: String,
30    pub default_value: String,
31    pub value: String,
32    pub set: bool,
33}
34
35/// Output of one plugin command, in the order Go writes it.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum Output {
38    Stdout(Bytes),
39    Stderr(Bytes),
40}
41
42/// Go `validCommandLineFlagName`.
43pub fn valid_flag_name(name: &str) -> bool {
44    !name.is_empty()
45        && !name.starts_with('-')
46        && name != "help"
47        && name != "h"
48        && !name.contains([' ', '\t', '\r', '\n', '='])
49}
50
51/// Go `normalizeCommandLineFlagType`.
52pub fn normalize_flag_type(kind: &str) -> Option<&'static str> {
53    Some(match kind.trim().go_lower().as_str() {
54        "" | "bool" => "bool",
55        "string" => "string",
56        "int" => "int",
57        "int64" => "int64",
58        "float64" => "float64",
59        "duration" => "duration",
60        _ => return None,
61    })
62}
63
64/// Go `strconv.ParseBool`.
65pub fn parse_bool(s: &str) -> Option<bool> {
66    match s {
67        "1" | "t" | "T" | "TRUE" | "true" | "True" => Some(true),
68        "0" | "f" | "F" | "FALSE" | "false" | "False" => Some(false),
69        _ => None,
70    }
71}
72
73/// Go `normalizeCommandLineFlagValue`.
74pub fn normalize_flag_value(kind: &str, value: &str) -> Option<String> {
75    let blank = value.trim().is_empty();
76    match kind {
77        "bool" if blank => Some("false".into()),
78        "bool" => parse_bool(value).map(|b| b.to_string()),
79        "string" => Some(value.to_owned()),
80        "int" | "int64" if blank => Some("0".into()),
81        "int" | "int64" => value.parse::<i64>().ok().map(|n| n.to_string()),
82        "float64" if blank => Some("0".into()),
83        "float64" => parse_float(value).map(format_float_g),
84        "duration" if blank => Some("0s".into()),
85        "duration" => parse_duration(value).map(format_duration),
86        _ => None,
87    }
88}
89
90/// Go `strconv.ParseFloat(s, 64)`: out of range is an error rather than ±Inf, NaN takes
91/// no sign, and underscores may separate digits.
92/// ponytail: Go's hexadecimal form (`0x1p-2`) is rejected; plugin flags are decimal in
93/// practice. Upgrade by porting `atofHex` if a plugin needs it.
94pub fn parse_float(s: &str) -> Option<f64> {
95    let unsigned = s.strip_prefix(['+', '-']).unwrap_or(s);
96    if unsigned.len() != s.len() && unsigned.eq_ignore_ascii_case("nan") {
97        return None;
98    }
99    let digits;
100    let text = if s.contains('_') {
101        if !underscore_ok(s) {
102            return None;
103        }
104        digits = s.replace('_', "");
105        digits.as_str()
106    } else {
107        s
108    };
109    let f = text.parse::<f64>().ok()?;
110    let literal_inf = unsigned.to_ascii_lowercase().starts_with("inf");
111    (!f.is_infinite() || literal_inf).then_some(f)
112}
113
114/// Go `strconv.underscoreOK` for a decimal number: each underscore sits between digits.
115fn underscore_ok(s: &str) -> bool {
116    let s = s.strip_prefix(['+', '-']).unwrap_or(s);
117    let mut saw = '^';
118    for c in s.chars() {
119        if c.is_ascii_digit() {
120            saw = '0';
121        } else if c == '_' {
122            if saw != '0' {
123                return false;
124            }
125            saw = '_';
126        } else if saw == '_' {
127            return false;
128        } else {
129            saw = '!';
130        }
131    }
132    saw != '_'
133}
134
135/// Go `strconv.FormatFloat(f, 'g', -1, 64)`.
136pub fn format_float_g(f: f64) -> String {
137    if f.is_nan() {
138        return "NaN".into();
139    }
140    if f.is_infinite() {
141        return if f > 0.0 { "+Inf".into() } else { "-Inf".into() };
142    }
143    if f == 0.0 {
144        return if f.is_sign_negative() { "-0".into() } else { "0".into() };
145    }
146    // Shortest round-trip digits and decimal exponent from Rust's `{:e}`.
147    let e = format!("{:e}", f.abs());
148    let (mantissa, exp) = e.split_once('e').expect("{:e} has an exponent");
149    let exp: i32 = exp.parse().expect("integer exponent");
150    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
151    let sign = if f < 0.0 { "-" } else { "" };
152    if !(-4..6).contains(&exp) {
153        let (first, rest) = digits.split_at(1);
154        let frac = if rest.is_empty() {
155            String::new()
156        } else {
157            format!(".{rest}")
158        };
159        let esign = if exp < 0 { '-' } else { '+' };
160        return format!("{sign}{first}{frac}e{esign}{:02}", exp.abs());
161    }
162    let dp = exp + 1;
163    let out = if dp <= 0 {
164        format!("0.{}{digits}", "0".repeat((-dp) as usize))
165    } else if (dp as usize) >= digits.len() {
166        format!("{digits}{}", "0".repeat(dp as usize - digits.len()))
167    } else {
168        format!("{}.{}", &digits[..dp as usize], &digits[dp as usize..])
169    };
170    format!("{sign}{out}")
171}
172
173/// Go `time.Duration.String`.
174pub fn format_duration(d: i64) -> String {
175    if d == 0 {
176        return "0s".into();
177    }
178    let neg = d < 0;
179    let u = d.unsigned_abs();
180    let sign = if neg { "-" } else { "" };
181    if u < 1_000_000_000 {
182        let (unit, scale) = match u {
183            0..1_000 => return format!("{sign}{u}ns"),
184            1_000..1_000_000 => ("µs", 1_000u64),
185            _ => ("ms", 1_000_000u64),
186        };
187        return format!("{sign}{}{unit}", frac(u, scale));
188    }
189    let secs = u / 1_000_000_000;
190    let nanos = u % 1_000_000_000;
191    let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60);
192    let mut out = String::from(sign);
193    if h > 0 {
194        out.push_str(&format!("{h}h"));
195    }
196    if h > 0 || m > 0 {
197        out.push_str(&format!("{m}m"));
198    }
199    out.push_str(&frac(s * 1_000_000_000 + nanos, 1_000_000_000));
200    out.push('s');
201    out
202}
203
204/// `v / scale` with the fractional digits Go prints (trailing zeros dropped).
205fn frac(v: u64, scale: u64) -> String {
206    let whole = v / scale;
207    let rem = v % scale;
208    if rem == 0 {
209        return whole.to_string();
210    }
211    let width = scale.ilog10() as usize;
212    let digits = format!("{rem:0width$}");
213    format!("{whole}.{}", digits.trim_end_matches('0'))
214}
215
216impl Host {
217    /// Go `RegisterCommandLineFlags`: asks every active command-line plugin for its flags
218    /// and keeps valid ones that clash neither with a built-in flag (`builtin`) nor with a
219    /// higher-priority plugin. Returns the flags accepted now.
220    pub async fn register_command_line_flags(&self, builtin: &dyn Fn(&str) -> bool) -> Vec<CliFlag> {
221        let mut accepted = Vec::new();
222        for record in self.active_records() {
223            if !record.plugin.caps.command_line_plugin || self.is_fused(&record.id) || !self.record_current(&record) {
224                continue;
225            }
226            let req = CommandLineRegistrationRequest {
227                plugin: record.plugin.metadata.clone(),
228            };
229            let resp: CommandLineRegistrationResponse =
230                match self.call(&record, method::COMMAND_LINE_REGISTER, &req).await {
231                    Ok(resp) => resp,
232                    Err(e) => {
233                        tracing::warn!("pluginhost: command-line registrar {} failed: {e}", record.id);
234                        continue;
235                    }
236                };
237            for item in resp.flags {
238                let name = item.name.trim().to_owned();
239                if !valid_flag_name(&name) {
240                    tracing::warn!(
241                        "pluginhost: plugin {} declared invalid command-line flag {:?}",
242                        record.id,
243                        item.name
244                    );
245                    continue;
246                }
247                let Some(kind) = normalize_flag_type(&item.flag_type) else {
248                    tracing::warn!(
249                        "pluginhost: plugin {} declared unsupported command-line flag type {:?} for {name}",
250                        record.id,
251                        item.flag_type
252                    );
253                    continue;
254                };
255                let Some(value) = normalize_flag_value(kind, &item.default_value) else {
256                    tracing::warn!(
257                        "pluginhost: plugin {} declared invalid default value {:?} for {name}",
258                        record.id,
259                        item.default_value
260                    );
261                    continue;
262                };
263                // Go looks the name up on the FlagSet, which already holds the built-in
264                // flags and every plugin flag registered before this one.
265                let mut state = self.state();
266                if builtin(&name) || state.command_line_flags.contains_key(&name) {
267                    tracing::warn!(
268                        "pluginhost: plugin {} command-line flag {name} conflicts with an existing flag and was skipped",
269                        record.id
270                    );
271                    continue;
272                }
273                let flag = CliFlag {
274                    plugin_id: record.id.clone(),
275                    name: name.clone(),
276                    usage: item.usage,
277                    kind: kind.into(),
278                    default_value: value.clone(),
279                    value,
280                    set: false,
281                };
282                state.command_line_flags.insert(name, flag.clone());
283                accepted.push(flag);
284            }
285        }
286        accepted
287    }
288
289    /// A registered plugin flag.
290    pub fn command_line_flag(&self, name: &str) -> Option<CliFlag> {
291        self.state().command_line_flags.get(name).cloned()
292    }
293
294    /// Go `commandLineFlagValue.Set`.
295    pub fn set_command_line_flag(&self, name: &str, raw: &str) -> Result<(), String> {
296        let mut state = self.state();
297        let Some(flag) = state.command_line_flags.get_mut(name) else {
298            return Ok(());
299        };
300        let value = normalize_flag_value(&flag.kind, raw)
301            .ok_or_else(|| format!("invalid {} value {}", flag.kind, cpa_common::gostr::quote(raw)))?;
302        flag.value = value;
303        flag.set = true;
304        state.command_line_hits.insert(name.to_owned());
305        Ok(())
306    }
307
308    /// Go `HasTriggeredCommandLineFlags`.
309    pub fn has_triggered_command_line_flags(&self) -> bool {
310        !self.state().command_line_hits.is_empty()
311    }
312
313    /// Go `ExecuteCommandLine`. `builtin` lists the host's own flags as
314    /// `(name, current value)`; `persist` saves an auth a command produced and
315    /// returns its path. Returns the exit code, whether any plugin ran, and the output to
316    /// write in order.
317    pub async fn execute_command_line(
318        &self,
319        program: &str,
320        args: &[String],
321        config_path: &str,
322        builtin: &[(String, String)],
323        persist: &dyn Fn(PluginAuth) -> Result<String, String>,
324    ) -> (i32, bool, Vec<Output>) {
325        let mut all: BTreeMap<String, CommandLineFlagValue> = builtin
326            .iter()
327            .map(|(name, value)| {
328                (
329                    name.clone(),
330                    CommandLineFlagValue {
331                        name: name.clone(),
332                        flag_type: String::new(),
333                        value: value.clone(),
334                        set: false,
335                    },
336                )
337            })
338            .collect();
339        let mut triggered: BTreeMap<String, BTreeMap<String, CommandLineFlagValue>> = BTreeMap::new();
340        {
341            let state = self.state();
342            for (name, flag) in &state.command_line_flags {
343                let value = CommandLineFlagValue {
344                    name: name.clone(),
345                    flag_type: flag.kind.clone(),
346                    value: flag.value.clone(),
347                    set: flag.set,
348                };
349                all.insert(name.clone(), value.clone());
350                if state.command_line_hits.contains(name) {
351                    triggered
352                        .entry(flag.plugin_id.clone())
353                        .or_default()
354                        .insert(name.clone(), value);
355                }
356            }
357        }
358        if triggered.is_empty() {
359            return (0, false, Vec::new());
360        }
361        let mut exit = 0;
362        let mut handled = false;
363        let mut output = Vec::new();
364        let auth_dir = self.host_config_summary().auth_dir;
365        for record in self.active_records() {
366            if !record.plugin.caps.command_line_plugin || self.is_fused(&record.id) {
367                continue;
368            }
369            let Some(mine) = triggered.get(&record.id) else {
370                continue;
371            };
372            handled = true;
373            if !self.record_current(&record) {
374                continue;
375            }
376            let req = CommandLineExecutionRequest {
377                plugin: record.plugin.metadata.clone(),
378                program: program.into(),
379                args: args.to_vec(),
380                config_path: config_path.into(),
381                host: self.host_config_summary(),
382                flags: all.clone(),
383                triggered_flags: mine.clone(),
384            };
385            let mut resp: CommandLineExecutionResponse =
386                match self.call(&record, method::COMMAND_LINE_EXECUTE, &req).await {
387                    Ok(resp) => resp,
388                    Err(e) => {
389                        tracing::warn!("pluginhost: command-line plugin {} failed: {e}", record.id);
390                        if exit == 0 {
391                            exit = 1;
392                        }
393                        continue;
394                    }
395                };
396            if resp.exit_code == 0 && !resp.auths.is_empty() {
397                let mut saved = Vec::new();
398                let mut failure = None;
399                for (index, data) in std::mem::take(&mut resp.auths).into_iter().enumerate() {
400                    let Some(auth) = PluginAuth::from_auth_data(data, "", "", &auth_dir) else {
401                        failure = Some(format!("pluginhost: command-line auth {} is invalid", index + 1));
402                        break;
403                    };
404                    let id = auth.id.clone();
405                    match persist(auth) {
406                        Ok(path) if !path.trim().is_empty() => saved.push(path),
407                        Ok(_) => {}
408                        Err(e) => {
409                            failure = Some(format!("pluginhost: save command-line auth {id}: {e}"));
410                            break;
411                        }
412                    }
413                }
414                if let Some(message) = failure {
415                    push_output(&mut output, Output::Stdout(resp.stdout));
416                    push_output(&mut output, Output::Stderr(resp.stderr));
417                    push_output(&mut output, Output::Stderr(Bytes::from(format!("{message}\n"))));
418                    if exit == 0 {
419                        exit = 1;
420                    }
421                    continue;
422                }
423                if !saved.is_empty() {
424                    let mut stdout = resp.stdout.to_vec();
425                    if stdout.last().is_some_and(|b| *b != b'\n') {
426                        stdout.push(b'\n');
427                    }
428                    for path in saved {
429                        stdout.extend_from_slice(format!("Authentication saved to {path}\n").as_bytes());
430                    }
431                    resp.stdout = Bytes::from(stdout);
432                }
433            }
434            push_output(&mut output, Output::Stdout(resp.stdout));
435            push_output(&mut output, Output::Stderr(resp.stderr));
436            if resp.exit_code != 0 && exit == 0 {
437                exit = resp.exit_code as i32;
438            }
439        }
440        (exit, handled, output)
441    }
442}
443
444fn push_output(out: &mut Vec<Output>, item: Output) {
445    let empty = match &item {
446        Output::Stdout(b) | Output::Stderr(b) => b.is_empty(),
447    };
448    if !empty {
449        out.push(item);
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456
457    /// Expected values printed by Go 1.26 (`strconv.ParseFloat` + `FormatFloat(f, 'g',
458    /// -1, 64)`, `time.ParseDuration` + `Duration.String`) for the same inputs.
459    #[test]
460    fn go_value_formats() {
461        for (s, want) in [
462            ("0.5", Some("0.5")),
463            ("100000", Some("100000")),
464            ("1e6", Some("1e+06")),
465            ("1234567", Some("1.234567e+06")),
466            ("0.0001", Some("0.0001")),
467            ("0.00001", Some("1e-05")),
468            ("-2.5e-7", Some("-2.5e-07")),
469            ("3", Some("3")),
470            ("123456789", Some("1.23456789e+08")),
471            ("1e21", Some("1e+21")),
472            ("1e400", None),
473            ("inf", Some("+Inf")),
474            ("-Infinity", Some("-Inf")),
475            ("1e-400", Some("0")),
476            ("+7.25", Some("7.25")),
477            ("5e-324", Some("5e-324")),
478            ("NaN", Some("NaN")),
479            ("nan", Some("NaN")),
480            ("+NaN", None),
481            ("-nan", None),
482            ("-infinity", Some("-Inf")),
483            ("+infinity", Some("+Inf")),
484            ("infx", None),
485            ("1_0", Some("10")),
486            ("1__0", None),
487            ("_1", None),
488            ("1e1_0", Some("1e+10")),
489        ] {
490            assert_eq!(normalize_flag_value("float64", s).as_deref(), want, "{s}");
491        }
492        for (s, want) in [
493            ("1h30m", Some("1h30m0s")),
494            ("1.5s", Some("1.5s")),
495            ("300ms", Some("300ms")),
496            ("-1h", Some("-1h0m0s")),
497            ("2µs", Some("2µs")),
498            ("1500us", Some("1.5ms")),
499            ("90s", Some("1m30s")),
500            ("0", Some("0s")),
501            ("7ns", Some("7ns")),
502            ("1", None),
503            ("1x", None),
504            (".s", None),
505            ("-", None),
506            ("+0", Some("0s")),
507            ("1.0000000001h", Some("1h0m0.00000036s")),
508            ("0.333333333333333333333h", Some("20m0s")),
509            ("2562047h47m16.854775807s", Some("2562047h47m16.854775807s")),
510            ("2562047h47m16.854775808s", None),
511            ("-2562047h47m16.854775808s", Some("-2562047h47m16.854775808s")),
512            ("1h-2m", None),
513            ("3.h", Some("3h0m0s")),
514            (".5m", Some("30s")),
515            ("1.23456789012345678901234567890s", Some("1.23456789s")),
516        ] {
517            assert_eq!(parse_duration(s).map(format_duration).as_deref(), want, "{s}");
518        }
519        assert_eq!(parse_duration(""), None);
520        assert_eq!(normalize_flag_value("duration", " ").as_deref(), Some("0s"));
521        assert_eq!(normalize_flag_value("bool", "T").as_deref(), Some("true"));
522        assert_eq!(normalize_flag_value("bool", "yes"), None);
523        assert_eq!(normalize_flag_value("int", " "), Some("0".into()));
524        assert_eq!(normalize_flag_value("int", "+7").as_deref(), Some("7"));
525        assert!(valid_flag_name("x") && !valid_flag_name("-x") && !valid_flag_name("a=b") && !valid_flag_name("help"));
526    }
527}