Skip to main content

agent_first_data/
cli.rs

1#[cfg(any(feature = "cli", feature = "cli-help"))]
2use crate::protocol::build_cli_error;
3use crate::protocol::{
4    BuildError, Event, LogLevel, ProtocolViolation, json_error, json_log, json_progress,
5    json_result, validate_protocol_event,
6};
7use crate::redaction::OutputOptions;
8use serde_json::Value;
9
10// ═══════════════════════════════════════════
11// Public API: CLI Helpers
12// ═══════════════════════════════════════════
13
14/// Output format for CLI and pipe/MCP modes.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum OutputFormat {
17    Json,
18    /// Structure-preserving YAML (same semantics as [`OutputFormat::Json`]).
19    Yaml,
20    Plain,
21}
22
23/// Parsed and normalized log filters (trimmed, lowercased, deduplicated).
24///
25/// Semantics (a stable contract):
26/// - An **empty** set emits no logs (filtering is opt-in, not opt-out).
27/// - The single wildcard word `"all"` emits every log. (`"*"` is not special —
28///   there is one wildcard spelling, not two.)
29/// - Otherwise a log is emitted iff its lowercased event name **starts with**
30///   any filter string (prefix match).
31///
32/// Consequence to know: a mistyped filter simply matches nothing, so it
33/// silently emits no output — that is the documented behavior, not a bug.
34#[derive(Clone, Debug, Default, PartialEq, Eq)]
35pub struct LogFilters(Vec<String>);
36
37impl LogFilters {
38    /// Create a new LogFilters from filter strings. Entries are trimmed,
39    /// lowercased, and de-duplicated; empty entries are dropped.
40    pub fn new<I, S>(filters: I) -> Self
41    where
42        I: IntoIterator<Item = S>,
43        S: AsRef<str>,
44    {
45        let mut out: Vec<String> = Vec::new();
46        for entry in filters {
47            let s = entry.as_ref().trim().to_ascii_lowercase();
48            if !s.is_empty() && !out.contains(&s) {
49                out.push(s);
50            }
51        }
52        Self(out)
53    }
54
55    /// Check if an event should be logged based on these filters.
56    ///
57    /// Returns `false` if empty (no logs). Returns `true` if the set contains
58    /// the wildcard word `"all"`. Otherwise returns `true` iff the lowercased
59    /// event name starts with any filter (prefix match).
60    pub fn enabled(&self, event: &str) -> bool {
61        if self.0.is_empty() {
62            return false;
63        }
64        let event_lower = event.to_ascii_lowercase();
65        if self.0.contains(&"all".to_string()) {
66            return true;
67        }
68        self.0.iter().any(|filter| event_lower.starts_with(filter))
69    }
70
71    /// Check if this filter set is empty (no filters configured).
72    pub fn is_empty(&self) -> bool {
73        self.0.is_empty()
74    }
75
76    /// Access the underlying filter strings as a slice.
77    pub fn as_slice(&self) -> &[String] {
78        &self.0
79    }
80}
81
82/// Parse `--output` flag value into [`OutputFormat`].
83///
84/// Returns `Err` with a message suitable for passing to [`build_cli_error`] on unknown values.
85///
86/// ```
87/// use agent_first_data::{cli_parse_output, OutputFormat};
88/// assert!(matches!(cli_parse_output("json"), Ok(OutputFormat::Json)));
89/// assert!(cli_parse_output("xml").is_err());
90/// ```
91pub fn cli_parse_output(s: &str) -> Result<OutputFormat, String> {
92    match s {
93        "json" => Ok(OutputFormat::Json),
94        "yaml" => Ok(OutputFormat::Yaml),
95        "plain" => Ok(OutputFormat::Plain),
96        _ => Err(format!(
97            "invalid --output format '{s}': expected json, yaml, or plain"
98        )),
99    }
100}
101
102/// Normalize `--log` flag entries: trim, lowercase, deduplicate, remove empty.
103///
104/// Accepts pre-split entries as produced by clap's `value_delimiter = ','`.
105///
106/// ```
107/// use agent_first_data::{cli_parse_log_filters, LogFilters};
108/// let f = cli_parse_log_filters(&["Query", " error ", "query"]);
109/// assert_eq!(f, LogFilters::new(["query", "error"]));
110/// ```
111pub fn cli_parse_log_filters<S: AsRef<str>>(entries: &[S]) -> LogFilters {
112    LogFilters::new(entries.iter().map(AsRef::as_ref))
113}
114
115/// Error returned by [`CliEmitter`].
116#[derive(Debug)]
117pub enum CliEmitterError {
118    /// A protocol-validation failure.
119    Validation(ProtocolViolation),
120    /// An event builder rejected its inputs (empty code/message, reserved field).
121    Build(BuildError),
122    /// An emitter lifecycle rule was violated (terminal ordering).
123    Lifecycle(String),
124    /// Writing the event to the underlying writer failed.
125    Write(std::io::Error),
126}
127
128impl std::fmt::Display for CliEmitterError {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        match self {
131            Self::Validation(v) => write!(f, "{v}"),
132            Self::Build(e) => write!(f, "{e}"),
133            Self::Lifecycle(err) => f.write_str(err),
134            Self::Write(err) => write!(f, "failed to write CLI event: {err}"),
135        }
136    }
137}
138
139impl CliEmitterError {
140    /// Return the underlying writer error, when event emission failed during I/O.
141    pub const fn io_error(&self) -> Option<&std::io::Error> {
142        match self {
143            Self::Write(err) => Some(err),
144            Self::Validation(_) | Self::Build(_) | Self::Lifecycle(_) => None,
145        }
146    }
147
148    /// Return the underlying writer error kind, when available.
149    pub fn io_error_kind(&self) -> Option<std::io::ErrorKind> {
150        self.io_error().map(std::io::Error::kind)
151    }
152}
153
154impl std::error::Error for CliEmitterError {
155    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
156        self.io_error()
157            .map(|err| err as &(dyn std::error::Error + 'static))
158    }
159}
160
161impl From<std::io::Error> for CliEmitterError {
162    fn from(err: std::io::Error) -> Self {
163        Self::Write(err)
164    }
165}
166
167/// Where a [`CliEmitter`] sends its events, selected by `--output-to`.
168///
169/// The stream an event lands on follows the program's *consumption mode*, not
170/// the event's shape (see the spec's CLI Event Framing):
171///
172/// - [`OutputTo::Split`] (the default) is finite one-shot mode: `result` goes
173///   to `stdout`, while `error`/`progress`/`log` go to `stderr`. `stdout`
174///   therefore carries only successful payloads, so a shell capture or pipe
175///   never mistakes a failure for data.
176/// - [`OutputTo::Stdout`] / [`OutputTo::Stderr`] are event-stream mode: every
177///   event, including `error`, is collapsed onto that one stream so a consumer
178///   reading it in order (`kind`-branching) sees preserved ordering.
179#[derive(Clone, Copy, Debug, PartialEq, Eq)]
180pub enum OutputTo {
181    /// Finite one-shot: `result` → stdout, `error`/`progress`/`log` → stderr.
182    Split,
183    /// Event stream: every event onto stdout.
184    Stdout,
185    /// Event stream: every event onto stderr.
186    Stderr,
187}
188
189impl OutputTo {
190    /// Parse an `--output-to` value: `split` (default), `stdout`, or `stderr`.
191    pub fn parse(value: &str) -> Result<Self, String> {
192        match value {
193            "split" => Ok(Self::Split),
194            "stdout" => Ok(Self::Stdout),
195            "stderr" => Ok(Self::Stderr),
196            other => Err(format!(
197                "unsupported --output-to `{other}`; expected split, stdout, or stderr"
198            )),
199        }
200    }
201}
202
203/// Stateful emitter for structured CLI executions.
204///
205/// The output format, redaction policy, and stream routing are fixed when the
206/// emitter is created. Emitting after a terminal event, emitting a repeated
207/// terminal event, and writer failures all return explicit errors.
208///
209/// Routing follows the consumption mode ([`OutputTo`]):
210///
211/// - [`CliEmitter::finite`] / [`CliEmitter::finite_with`] — finite one-shot:
212///   `result` → the primary writer (stdout), `error`/`progress`/`log` → the
213///   diagnostic writer (stderr). This is the recommended default for a
214///   one-shot CLI, so shell capture and pipelines never treat a failure as data.
215/// - [`CliEmitter::stream`] — event stream: every event, including `error`,
216///   goes to the single writer, preserving interleaved ordering.
217/// - [`CliEmitter::from_output_to`] builds either shape from a parsed
218///   [`OutputTo`] selector.
219pub struct CliEmitter<W: std::io::Write> {
220    writer: W,
221    diagnostic: Option<Box<dyn std::io::Write>>,
222    format: OutputFormat,
223    output_options: OutputOptions,
224    strict_protocol: bool,
225    terminal_emitted: bool,
226    log_fields_provider: Option<Box<dyn Fn() -> Value>>,
227}
228
229impl<W: std::io::Write> CliEmitter<W> {
230    /// Create an event-stream emitter: every event goes to `writer`.
231    ///
232    /// Alias for [`CliEmitter::stream`]. Use [`CliEmitter::finite`] for a
233    /// one-shot command that should split `result`/`error` across stdout/stderr.
234    pub fn new(writer: W, format: OutputFormat) -> Self {
235        Self::stream(writer, format)
236    }
237
238    /// Create an event-stream emitter with custom output options.
239    pub fn with_options(writer: W, format: OutputFormat, output_options: OutputOptions) -> Self {
240        Self {
241            writer,
242            diagnostic: None,
243            format,
244            output_options,
245            strict_protocol: false,
246            terminal_emitted: false,
247            log_fields_provider: None,
248        }
249    }
250
251    /// Create an event-stream emitter: every event, including `error`, goes to
252    /// the single `writer`, preserving interleaved ordering. Pick this when the
253    /// consumer reads one ordered stream and branches on `kind`.
254    pub fn stream(writer: W, format: OutputFormat) -> Self {
255        Self::with_options(writer, format, OutputOptions::default())
256    }
257
258    /// Create a finite one-shot emitter with explicit sinks: `result` goes to
259    /// `result_writer`, while `error`/`progress`/`log` go to `diagnostic`.
260    pub fn finite_with(
261        result_writer: W,
262        diagnostic: impl std::io::Write + 'static,
263        format: OutputFormat,
264    ) -> Self {
265        Self::finite_with_options(result_writer, diagnostic, format, OutputOptions::default())
266    }
267
268    /// Create a finite one-shot emitter with explicit sinks and output options.
269    pub fn finite_with_options(
270        result_writer: W,
271        diagnostic: impl std::io::Write + 'static,
272        format: OutputFormat,
273        output_options: OutputOptions,
274    ) -> Self {
275        Self {
276            writer: result_writer,
277            diagnostic: Some(Box::new(diagnostic)),
278            format,
279            output_options,
280            strict_protocol: false,
281            terminal_emitted: false,
282            log_fields_provider: None,
283        }
284    }
285
286    /// Require the AFDATA recommended strict profile for every emitted event.
287    pub fn with_strict_protocol(mut self) -> Self {
288        self.strict_protocol = true;
289        self
290    }
291
292    /// Set a provider for default log fields.
293    ///
294    /// The provider is called for every log event (via emit_log or emit with kind:log).
295    /// Its output is merged as extension fields; explicit call-site fields take precedence.
296    pub fn with_log_fields<F>(mut self, provider: F) -> Self
297    where
298        F: Fn() -> Value + 'static,
299    {
300        self.log_fields_provider = Some(Box::new(provider));
301        self
302    }
303
304    /// Emit a typed Event (unified entry for all event kinds).
305    ///
306    /// Accepts only SDK-constructed Event; for dynamic JSON, use emit_validated_value.
307    pub fn emit(&mut self, event: Event) -> Result<(), CliEmitterError> {
308        let value = event.into_value();
309        self.write_event(value)
310    }
311
312    /// Emit and validate dynamic JSON, then apply redaction/formatting/write.
313    ///
314    /// Runs strict validation first, ensuring the dynamic JSON is safe.
315    pub fn emit_validated_value(&mut self, value: Value) -> Result<(), CliEmitterError> {
316        validate_protocol_event(&value, true).map_err(CliEmitterError::Validation)?;
317        self.write_event(value)
318    }
319
320    /// Convenience: build and emit a result event.
321    pub fn emit_result(&mut self, payload: Value) -> Result<(), CliEmitterError> {
322        self.emit(json_result(payload).build())
323    }
324
325    /// Convenience: build and emit an error event.
326    pub fn emit_error(&mut self, code: &str, message: &str) -> Result<(), CliEmitterError> {
327        match json_error(code, message).build() {
328            Ok(event) => self.emit(event),
329            Err(err) => Err(CliEmitterError::Build(err)),
330        }
331    }
332
333    /// Convenience: build and emit a progress event.
334    pub fn emit_progress(&mut self, message: &str) -> Result<(), CliEmitterError> {
335        self.emit(json_progress(serde_json::json!({ "message": message })).build())
336    }
337
338    /// Convenience: build and emit a log event with default fields.
339    ///
340    /// Applies log_fields_provider if configured; explicit fields take precedence.
341    pub fn emit_log(&mut self, level: LogLevel, message: &str) -> Result<(), CliEmitterError> {
342        let mut event = json_log(serde_json::json!({
343            "level": level.as_str(),
344            "message": message,
345        }))
346        .build()
347        .into_value();
348        if let Some(provider) = &self.log_fields_provider {
349            let provider_fields = provider();
350            if let Some(log_obj) = event.get_mut("log").and_then(|v| v.as_object_mut())
351                && let Value::Object(fields) = provider_fields
352            {
353                for (k, v) in fields {
354                    log_obj.entry(k).or_insert(v);
355                }
356            }
357        }
358        self.write_event(event)
359    }
360
361    /// Emit `event` as the terminal event and resolve the outcome to a process
362    /// exit code, so a one-shot CLI need not hand-roll the emit-then-exit dance.
363    ///
364    /// A successful write returns `success_code`; a broken pipe (the reader hung
365    /// up) returns `0`; any other write or validation failure returns `4`. A
366    /// library never calls `process::exit` itself — return this code from `main`
367    /// (`std::process::ExitCode::from(code)`).
368    pub fn finish(&mut self, event: Event, success_code: u8) -> u8 {
369        match self.emit(event) {
370            Ok(()) => success_code,
371            Err(err) if err.io_error_kind() == Some(std::io::ErrorKind::BrokenPipe) => 0,
372            Err(_) => 4,
373        }
374    }
375
376    /// Convenience over [`CliEmitter::finish`]: emit a `result` payload and
377    /// return `0` on success.
378    ///
379    /// For an error, build it with [`json_error`] (`.hint(…)`, `.retryable(…)`,
380    /// `.field(…)` as needed) and pass the event to [`CliEmitter::finish`] with
381    /// the desired exit code — the builder is the error type, so no separate
382    /// error-emitting convenience is needed.
383    pub fn finish_result(&mut self, payload: Value) -> u8 {
384        self.finish(json_result(payload).build(), 0)
385    }
386
387    /// Access the underlying writer.
388    pub fn into_inner(self) -> W {
389        self.writer
390    }
391
392    fn write_event(&mut self, event: Value) -> Result<(), CliEmitterError> {
393        validate_protocol_event(&event, self.strict_protocol)
394            .map_err(CliEmitterError::Validation)?;
395        let kind = event.get("kind").and_then(Value::as_str).ok_or_else(|| {
396            CliEmitterError::Validation(ProtocolViolation {
397                rule: "kind_invalid",
398                pointer: "/kind".to_string(),
399                message: "event.kind is required".to_string(),
400            })
401        })?;
402        match kind {
403            "log" | "progress" => {
404                if self.terminal_emitted {
405                    return Err(CliEmitterError::Lifecycle(
406                        "cannot emit non-terminal event after terminal event".to_string(),
407                    ));
408                }
409            }
410            "result" | "error" => {
411                if self.terminal_emitted {
412                    return Err(CliEmitterError::Lifecycle(
413                        "cannot emit duplicate terminal event".to_string(),
414                    ));
415                }
416            }
417            _ => {
418                return Err(CliEmitterError::Validation(ProtocolViolation {
419                    rule: "kind_unsupported",
420                    pointer: "/kind".to_string(),
421                    message: format!("unsupported event kind {kind:?}"),
422                }));
423            }
424        }
425        let rendered = crate::formatting::render(&event, self.format, &self.output_options);
426        // Finite mode (a diagnostic sink is present) splits by kind: `result`
427        // stays on the primary writer (stdout), while `error`/`progress`/`log`
428        // are diagnostics routed to the diagnostic writer (stderr). Event-stream
429        // mode (no diagnostic sink) keeps every event on the single writer.
430        match &mut self.diagnostic {
431            Some(diagnostic) if kind != "result" => {
432                write_event_line(diagnostic.as_mut(), &rendered)
433            }
434            _ => write_event_line(&mut self.writer, &rendered),
435        }?;
436        if matches!(kind, "result" | "error") {
437            self.terminal_emitted = true;
438        }
439        Ok(())
440    }
441}
442
443/// Write one rendered event line (payload plus trailing newline) and flush.
444fn write_event_line(writer: &mut dyn std::io::Write, rendered: &str) -> std::io::Result<()> {
445    writer.write_all(rendered.as_bytes())?;
446    writer.write_all(b"\n")?;
447    writer.flush()
448}
449
450// The emitter's own diagnostic sink is the spec's sanctioned exception to the
451// "no ad-hoc stderr" rule (Channel policy): a finite one-shot emitter routes
452// `error`/`progress`/`log` to `std::io::stderr` on purpose, so these wired
453// constructors are allowed to name it directly.
454#[allow(clippy::disallowed_methods)]
455impl CliEmitter<std::io::Stdout> {
456    /// Create a finite one-shot emitter wired to the process streams: `result`
457    /// → `stdout`, `error`/`progress`/`log` → `stderr`. The recommended default
458    /// for a one-shot CLI.
459    pub fn finite(format: OutputFormat) -> Self {
460        Self::finite_with(std::io::stdout(), std::io::stderr(), format)
461    }
462
463    /// Create a finite one-shot emitter wired to the process streams, with
464    /// custom output options.
465    pub fn finite_options(format: OutputFormat, output_options: OutputOptions) -> Self {
466        Self::finite_with_options(std::io::stdout(), std::io::stderr(), format, output_options)
467    }
468}
469
470// Same sanctioned exception as above: `from_output_to` wires the process
471// streams (`std::io::stderr` included) as the emitter's own sinks.
472#[allow(clippy::disallowed_methods)]
473impl CliEmitter<Box<dyn std::io::Write>> {
474    /// Build an emitter from a parsed [`OutputTo`] selector, wired to the
475    /// process streams: `Split` is finite mode (`result` → stdout, everything
476    /// else → stderr); `Stdout`/`Stderr` are event-stream mode onto that stream.
477    pub fn from_output_to(selector: OutputTo, format: OutputFormat) -> Self {
478        Self::from_output_to_with(selector, format, OutputOptions::default())
479    }
480
481    /// As [`CliEmitter::from_output_to`], with custom output options.
482    pub fn from_output_to_with(
483        selector: OutputTo,
484        format: OutputFormat,
485        output_options: OutputOptions,
486    ) -> Self {
487        match selector {
488            OutputTo::Split => Self::finite_with_options(
489                Box::new(std::io::stdout()),
490                std::io::stderr(),
491                format,
492                output_options,
493            ),
494            OutputTo::Stdout => {
495                Self::with_options(Box::new(std::io::stdout()), format, output_options)
496            }
497            OutputTo::Stderr => {
498                Self::with_options(Box::new(std::io::stderr()), format, output_options)
499            }
500        }
501    }
502}
503
504/// Build a standard CLI version event: a `kind:"result"` event whose payload is
505/// `{ "code": "version", "name": <name>, "version": <version> }`, plus
506/// `"display_name"`/`"build"` when given. `name` is the short/bin identity
507/// (e.g. `"afdata"`); `display_name` is an optional human-facing product name
508/// (e.g. `"Agent-First Data"`); `build` is an opaque caller-supplied identifier (a git
509/// commit SHA, for example) — its meaning is entirely up to the caller. Both
510/// are `None` when unavailable, and simply absent from the payload.
511pub fn build_cli_version(
512    name: &str,
513    display_name: Option<&str>,
514    version: &str,
515    build: Option<&str>,
516) -> Event {
517    let mut payload = serde_json::json!({
518        "code": "version",
519        "name": name,
520        "version": version,
521    });
522    if let Some(display_name) = display_name {
523        payload["display_name"] = Value::String(display_name.to_string());
524    }
525    if let Some(build) = build {
526        payload["build"] = Value::String(build.to_string());
527    }
528    json_result(payload).build()
529}
530
531/// Render a CLI version response as a protocol-v1 event in `format`.
532pub fn cli_render_version(
533    name: &str,
534    display_name: Option<&str>,
535    version: &str,
536    build: Option<&str>,
537    format: OutputFormat,
538) -> String {
539    let mut rendered = crate::formatting::render(
540        build_cli_version(name, display_name, version, build).as_value(),
541        format,
542        &OutputOptions::default(),
543    );
544    while rendered.ends_with('\n') {
545        rendered.pop();
546    }
547    rendered.push('\n');
548    rendered
549}
550
551/// Render version output from raw argv if `--version` or `-V` is present.
552///
553/// `raw_args` should be the full argv vector, including argv[0], as produced by
554/// `std::env::args()`. The helper intentionally runs before clap or another
555/// parser so explicit `--output json|yaml|plain` is honored instead of being
556/// bypassed by built-in version handling. `cmd` is the caller's own
557/// `clap::Command` (typically `Cli::command()`) — used to inherit the declared
558/// `--output` default and to look up which flags take a value, so any global
559/// flag the caller defines (`--stdout-file`, or one added later) is recognized
560/// without the pre-parser having to hardcode its name.
561///
562/// Only a *top-level* version request is recognized: scanning stops at the first
563/// positional argument (the subcommand), so `tool sub --version <value>` leaves
564/// `--version` for the subcommand's parser rather than printing the tool version.
565/// That boundary check is unconditional and runs before any flag is inspected —
566/// it is unaffected by `cmd`, which only decides how many argv slots a
567/// *recognized flag* consumes, so a flag's value is never mistaken for it.
568///
569/// The one blessed behavior: `--version` always answers with a protocol-v1
570/// `kind:"result"` version event (payload `{ "code": "version", "name", ...
571/// }`, see [`build_cli_version`]). An explicit `--output` wins;
572/// otherwise the handler inherits the command's declared `--output` default,
573/// falling back to JSON. Returns a standard [`build_cli_error`] event when the
574/// request is malformed, for example `--version --output xml`.
575#[cfg(any(feature = "cli", feature = "cli-help"))]
576pub fn cli_handle_version_or_continue(
577    raw_args: &[String],
578    cmd: &clap::Command,
579    name: &str,
580    display_name: Option<&str>,
581    version: &str,
582    build: Option<&str>,
583) -> Result<Option<String>, Event> {
584    let parsed = parse_version_request(raw_args, cmd);
585    if !parsed.version_requested {
586        return Ok(None);
587    }
588    if let Some(error) = parsed.output_error {
589        let event = build_cli_error(
590            &error,
591            Some("valid version output formats: json, yaml, plain"),
592        );
593        return Err(event);
594    }
595    Ok(Some(cli_render_version(
596        name,
597        display_name,
598        version,
599        build,
600        parsed
601            .output_format
602            .or_else(|| command_output_default(cmd))
603            .unwrap_or(OutputFormat::Json),
604    )))
605}
606
607#[cfg(any(feature = "cli", feature = "cli-help"))]
608fn command_output_default(cmd: &clap::Command) -> Option<OutputFormat> {
609    cmd.get_arguments()
610        .find(|arg| arg.get_long() == Some("output"))
611        .and_then(|arg| arg.get_default_values().first())
612        .and_then(|value| value.to_str())
613        .and_then(|value| cli_parse_output(value).ok())
614}
615
616#[cfg(any(feature = "cli", feature = "cli-help"))]
617struct ParsedVersionRequest {
618    version_requested: bool,
619    output_format: Option<OutputFormat>,
620    output_error: Option<String>,
621}
622
623/// Drop argv[0] from a raw argument vector.
624///
625/// `raw_args` is documented as the full argv, so argv[0] is the program path and
626/// never an argument. The one concession is a caller that passes bare arguments:
627/// argv[0] can never start with `-`, so a leading `-` means the vector is
628/// already stripped. Matching argv[0] against subcommand names would be a
629/// second, unsafe concession — a binary legitimately named after one of its own
630/// subcommands would have its program path parsed as that subcommand.
631#[cfg(any(feature = "cli", feature = "cli-help"))]
632pub(crate) fn strip_argv0(raw_args: &[String]) -> &[String] {
633    match raw_args.first() {
634        Some(first) if first.starts_with('-') => raw_args,
635        _ => raw_args.get(1..).unwrap_or(&[]),
636    }
637}
638
639#[cfg(any(feature = "cli", feature = "cli-help"))]
640fn parse_version_request(raw_args: &[String], cmd: &clap::Command) -> ParsedVersionRequest {
641    let args = strip_argv0(raw_args);
642    let mut version_requested = false;
643    let mut output_format = None;
644    let mut output_error = None;
645
646    let mut i = 0usize;
647    while i < args.len() {
648        let arg = args[i].as_str();
649        if arg == "--" {
650            break;
651        }
652        // The first positional argument marks the subcommand boundary. Past it,
653        // `--version` (and `-V`) belong to the subcommand's own parser, matching
654        // git/cargo/clap: the pre-parser only owns a top-level version request.
655        if !arg.starts_with('-') {
656            break;
657        }
658
659        let (flag_name, inline_value) = split_flag(arg);
660        if arg == "--version" {
661            version_requested = true;
662            i += 1;
663            continue;
664        }
665
666        // `--output-to` takes a value but does not affect version text output.
667        // Consume its space-separated value so it is not mistaken for the
668        // subcommand boundary (which would hide a later `--version`/`--output`).
669        if flag_name == Some("output-to") {
670            let has_space_value = inline_value.is_none()
671                && args
672                    .get(i + 1)
673                    .map(|next| !next.starts_with('-'))
674                    .unwrap_or(false);
675            i += if has_space_value { 2 } else { 1 };
676            continue;
677        }
678
679        if flag_name == Some("output") {
680            let value = inline_value.or_else(|| {
681                args.get(i + 1)
682                    .map(String::as_str)
683                    .filter(|next| !next.starts_with('-'))
684            });
685            if let Some(value) = value {
686                match cli_parse_output(value) {
687                    Ok(format) => set_version_output_format(
688                        &mut output_format,
689                        format,
690                        &format!("--output {value}"),
691                        &mut output_error,
692                    ),
693                    Err(err) => output_error = Some(err),
694                }
695            } else {
696                output_error =
697                    Some("missing value for --output: expected json, yaml, or plain".to_string());
698            }
699            i += if inline_value.is_some() || value.is_none() {
700                1
701            } else {
702                2
703            };
704            continue;
705        }
706
707        // Any other flag: ask the caller's real Command whether it takes a
708        // value (covers `--stdout-file`/`--stderr-file` and any other global
709        // flag the caller defines) so its value is never mistaken for the
710        // subcommand boundary above.
711        let has_space_value = inline_value.is_none()
712            && args
713                .get(i + 1)
714                .map(|next| !next.starts_with('-'))
715                .unwrap_or(false);
716        i += if has_space_value && flag_takes_value(cmd, arg) {
717            2
718        } else {
719            1
720        };
721    }
722
723    ParsedVersionRequest {
724        version_requested,
725        output_format,
726        output_error,
727    }
728}
729
730#[cfg(any(feature = "cli", feature = "cli-help"))]
731fn set_version_output_format(
732    current: &mut Option<OutputFormat>,
733    next: OutputFormat,
734    source: &str,
735    output_error: &mut Option<String>,
736) {
737    if let Some(existing) = current
738        && *existing != next
739    {
740        *output_error = Some(format!(
741            "conflicting output formats: {source} conflicts with previous output format"
742        ));
743        return;
744    }
745    *current = Some(next);
746}
747
748#[cfg(any(feature = "cli", feature = "cli-help"))]
749fn split_flag(arg: &str) -> (Option<&str>, Option<&str>) {
750    if !arg.starts_with('-') || arg == "-" {
751        return (None, None);
752    }
753    let (flag, value) = arg.split_once('=').unwrap_or((arg, ""));
754    let name = flag.trim_start_matches('-');
755    if name.is_empty() {
756        (None, None)
757    } else if arg.contains('=') {
758        (Some(name), Some(value))
759    } else {
760        (Some(name), None)
761    }
762}
763
764// A local copy, not a shared import from `help` (gated behind the stricter
765// `cli-help` alone): this parser only requires the more basic `cli` feature,
766// mirroring how `split_flag` above is already duplicated rather than shared.
767#[cfg(any(feature = "cli", feature = "cli-help"))]
768fn flag_takes_value(cmd: &clap::Command, raw_flag: &str) -> bool {
769    let Some(flag) = raw_flag.strip_prefix('-') else {
770        return false;
771    };
772    let name = flag.trim_start_matches('-');
773    cmd.get_arguments().any(|arg| {
774        let long_matches = arg.get_long().is_some_and(|long| long == name);
775        let short_matches =
776            name.len() == 1 && arg.get_short().is_some_and(|short| name.starts_with(short));
777        (long_matches || short_matches)
778            && matches!(
779                arg.get_action(),
780                clap::ArgAction::Set | clap::ArgAction::Append
781            )
782    })
783}