Skip to main content

oxdock_parser/
command.rs

1use crate::ast::{Arg, Expr, StepKind};
2use crate::error::{ParseError, SpanContext};
3use anyhow::{Result, anyhow, bail};
4
5/// Metadata for a single command argument.
6pub struct ArgSpec {
7    pub name: &'static str,
8    pub arg_type: ArgType,
9    pub description: &'static str,
10    pub io: IoDirection,
11    pub index: usize,
12    pub required: bool,
13    pub fallback_stream: Option<Stream>,
14}
15
16/// Closed vocabulary for argument value types: every variant names a
17/// type explicitly present in the app, so the reference table never
18/// lists a type that does not exist. Shapes (`$var` targets, `KEY=value`
19/// pairs) are not types: the central validator only checks value types
20/// and arity, while each command's `lower` enforces its own shapes with
21/// command-specific errors.
22/// [`ArgType::Any`] is the single exception: it renders as `<any>`,
23/// visibly a placeholder rather than a type name.
24/// [`ArgType::OneOf`] renders its inline options, likewise self-describing.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ArgType {
27    String,
28    Path,
29    Int,
30    Duration,
31    /// A `$variable` that must hold a LIST at runtime. Non-variable
32    /// expressions fail at lower time; renders linked as `LIST`.
33    List,
34    /// Any evaluated value (plus stream markers like `stdout` where the
35    /// command accepts them). Renders unlinked as `<any>`, visibly a
36    /// placeholder rather than a type name.
37    Any,
38    /// Inline alternation for one-off enums (e.g. `SNAPSHOT|LOCAL`).
39    /// Self-describing, so it renders unlinked.
40    OneOf(&'static [&'static str]),
41    /// Trailing variadic repetition (e.g. `RUN`'s `string...`).
42    Rest(&'static ArgType),
43}
44
45impl ArgType {
46    /// Table-cell label for the argument table's Type column.
47    /// Canonical value types use their descriptor names; `ANY` renders
48    /// as `<any>` and inline alternations render their options, so
49    /// neither reads as a standalone type. Shapes (`$var` targets,
50    /// `KEY=value` pairs) are validated in each command's `lower`, and
51    /// the shape requirement lives in the argument description and
52    /// command syntax.
53    pub fn label(&self) -> String {
54        match self {
55            ArgType::String => "STRING".to_string(),
56            ArgType::Path => "PATH".to_string(),
57            ArgType::Int => "INT".to_string(),
58            ArgType::Duration => "DURATION".to_string(),
59            ArgType::List => "LIST".to_string(),
60            ArgType::Any => "<any>".to_string(),
61            ArgType::OneOf(options) => options.join("|"),
62            ArgType::Rest(inner) => format!("{}...", inner.label()),
63        }
64    }
65
66    /// Anchor of the type's reference section. Only types with a value-type
67    /// reference section link; `<any>` and inline alternations render
68    /// unlinked.
69    pub fn anchor(&self) -> Option<String> {
70        match self {
71            ArgType::String => Some(crate::value::type_anchor("STRING")),
72            ArgType::Path => Some(crate::value::type_anchor("PATH")),
73            ArgType::Int => Some(crate::value::type_anchor("INT")),
74            ArgType::Duration => Some(crate::value::type_anchor("DURATION")),
75            ArgType::List => Some(crate::value::type_anchor("LIST")),
76            ArgType::Any => None,
77            ArgType::OneOf(_) => None,
78            ArgType::Rest(inner) => inner.anchor(),
79        }
80    }
81
82    /// Validate a statically-known literal against this type.
83    /// Templates and variables are never passed here : see `check_arg`.
84    pub fn validate_literal(&self, literal: &str) -> Result<()> {
85        match self {
86            ArgType::String | ArgType::Path | ArgType::Any => Ok(()),
87            ArgType::Int => strip_digit_separators(literal)
88                .parse::<i64>()
89                .map(|_| ())
90                .map_err(|_| anyhow!("expected int, got {literal:?}")),
91            ArgType::Duration => parse_duration(literal).map(|_| ()),
92            ArgType::List => {
93                if literal.starts_with('$') {
94                    Ok(())
95                } else {
96                    bail!("expected $var, got {literal:?}")
97                }
98            }
99            ArgType::OneOf(options) => {
100                // Exact match only: lowercase spellings are rejected so
101                // keyword arguments stay uppercase across the DSL.
102                if options.contains(&literal) {
103                    Ok(())
104                } else {
105                    bail!("expected one of {}, got {literal:?}", options.join("|"))
106                }
107            }
108            ArgType::Rest(inner) => inner.validate_literal(literal),
109        }
110    }
111
112    /// Classify one positional arg for lower-time checking.
113    /// `Static` literals validate now; templates, variables (except a
114    /// `$var` where `List` is required), and mixed fragments defer to the
115    /// runtime resolvers, which see interpolated values.
116    pub fn check_arg(&self, arg: &Arg) -> Result<CheckOutcome> {
117        match arg {
118            Arg::String(s, _) if !s.contains("{{") => {
119                self.validate_literal(s)?;
120                Ok(CheckOutcome::Static)
121            }
122            Arg::String(_, _) => Ok(CheckOutcome::Deferred),
123            Arg::Parts(_) => Ok(CheckOutcome::Deferred),
124            Arg::Expr(Expr::Var { .. }) => {
125                if matches!(*self, ArgType::List) {
126                    Ok(CheckOutcome::Static)
127                } else {
128                    Ok(CheckOutcome::Deferred)
129                }
130            }
131            Arg::Expr(_) => {
132                if matches!(*self, ArgType::List) {
133                    bail!("expected $var, got expression {}", arg.render())
134                } else {
135                    Ok(CheckOutcome::Deferred)
136                }
137            }
138        }
139    }
140}
141
142/// Lower-time checking outcome for one positional arg.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum CheckOutcome {
145    /// Validated now; nothing deferred.
146    Static,
147    /// Unknowable until runtime (template, variable, or fragment);
148    /// runtime resolvers enforce the type on the resolved value.
149    Deferred,
150}
151
152/// Validate positional args against a command's declared specs.
153/// Missing required positionals, statically-known type violations, and
154/// trailing positionals beyond a fixed-arity spec all fail here;
155/// templates, variables, and fragments defer to the runtime resolvers.
156/// A trailing `Rest` spec absorbs any number of positionals.
157pub fn validate_positionals_against_meta(
158    cmd_name: &str,
159    specs: &[ArgSpec],
160    args: &[Arg],
161) -> Result<(), ParseError> {
162    let has_rest = specs
163        .last()
164        .is_some_and(|s| matches!(s.arg_type, ArgType::Rest(_)));
165
166    if !has_rest && args.len() > specs.len() {
167        return Err(ParseError::validation(
168            cmd_name,
169            format!(
170                "invalid syntax for command {cmd_name}: expects at most {} positional argument(s), got {}",
171                specs.len(),
172                args.len()
173            ),
174            &SpanContext::line_only(0),
175        ));
176    }
177
178    for spec in specs {
179        if let ArgType::Rest(inner) = spec.arg_type {
180            // Variadic tail: every trailing positional checks against
181            // the inner type, not just the first.
182            let tail = args.get(spec.index..).unwrap_or(&[]);
183            if tail.is_empty() && spec.required {
184                return Err(ParseError::validation(
185                    cmd_name,
186                    format!(
187                        "invalid syntax for command {cmd_name}: requires argument `{}`",
188                        spec.name
189                    ),
190                    &SpanContext::line_only(0),
191                ));
192            }
193            for arg in tail {
194                check_one(cmd_name, spec, inner, arg)?;
195            }
196            return Ok(());
197        }
198        match args.get(spec.index) {
199            Some(arg) => check_one(cmd_name, spec, &spec.arg_type, arg)?,
200            None if spec.required => {
201                return Err(ParseError::validation(
202                    cmd_name,
203                    format!(
204                        "invalid syntax for command {cmd_name}: requires argument `{}`",
205                        spec.name
206                    ),
207                    &SpanContext::line_only(0),
208                ));
209            }
210            None => {}
211        }
212    }
213    Ok(())
214}
215
216fn check_one(
217    cmd_name: &str,
218    spec: &ArgSpec,
219    arg_type: &ArgType,
220    arg: &Arg,
221) -> Result<(), ParseError> {
222    match arg_type.check_arg(arg) {
223        Ok(_) => Ok(()),
224        Err(e) => Err(ParseError::validation(
225            cmd_name,
226            format!(
227                "invalid syntax for command {cmd_name}: argument `{}` got {} — {e:#}",
228                spec.name,
229                arg.render()
230            ),
231            &SpanContext::line_only(0),
232        )),
233    }
234}
235
236/// Strip one layer of surrounding quotes (`"`, `'`, or `"""` block).
237/// Block delimiters strip without dedenting: callers holding a block
238/// spelling route through [`lower_block_string`] instead.
239pub fn strip_surrounding_quotes(value: &str) -> &str {
240    if let Some(inner) = value
241        .strip_prefix("\"\"\"")
242        .and_then(|s| s.strip_suffix("\"\"\""))
243    {
244        return inner;
245    }
246    value
247        .strip_prefix('"')
248        .and_then(|s| s.strip_suffix('"'))
249        .or_else(|| value.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
250        .unwrap_or(value)
251}
252
253/// Lower a `"""..."""` block literal to its string value. Escapes and
254/// `{{ }}` pass through verbatim for runtime `expand_string`. Steps:
255/// 1. Strip the delimiters, normalize `\r\n` and lone `\r` to `\n`.
256/// 2. Leading newline: if the opening `"""` is followed only by
257///    spaces/tabs then a newline, drop through that newline
258///    (`split_leading_newline`). Otherwise the opening line holds
259///    inline text (`"""text`), kept verbatim at zero indent and
260///    excluded from prefix computation.
261/// 3. Closing line: if the text holds a newline and the last line is
262///    whitespace-only, the closing `"""` sits on its own line. Pop
263///    that line (with its newline) and seat its whitespace as the
264///    indentation baseline among the prefix candidates.
265/// 4. Common prefix: longest shared leading-whitespace run across all
266///    non-blank content lines. Blank lines never vote. No qualifying
267///    line means an empty value.
268/// 5. Strip the prefix from every non-blank line. The inline first
269///    line and blank lines pass through untouched.
270/// 6. Rejoin the lines with `\n`.
271pub fn lower_block_string(s: &str) -> String {
272    let inner = s.strip_prefix("\"\"\"").unwrap_or(s);
273    let inner = inner.strip_suffix("\"\"\"").unwrap_or(inner);
274    let norm = inner.replace("\r\n", "\n").replace('\r', "\n");
275    let (body, inline_first) = match split_leading_newline(&norm) {
276        Some(rest) => (rest.to_string(), false),
277        None => (norm.clone(), true),
278    };
279    if body.is_empty() {
280        return String::new();
281    }
282    let mut lines: Vec<&str> = body.split('\n').collect();
283    let closing_own_line = norm.contains('\n') && lines.last().is_some_and(|l| l.trim().is_empty());
284    let closing_indent = if closing_own_line {
285        lines.pop().unwrap_or("").to_string()
286    } else {
287        String::new()
288    };
289    let content: &[&str] = if inline_first && !lines.is_empty() {
290        &lines[1..]
291    } else {
292        &lines[..]
293    };
294    if inline_first && lines.len() == 1 && lines[0].trim().is_empty() {
295        return String::new();
296    }
297    if !(inline_first && !lines.is_empty() && !lines[0].trim().is_empty())
298        && !content.iter().any(|l| !l.trim().is_empty())
299    {
300        return String::new();
301    }
302    let mut candidates: Vec<&str> = Vec::new();
303    if closing_own_line {
304        candidates.push(closing_indent.as_str());
305    }
306    for line in content {
307        if line.trim().is_empty() {
308            continue;
309        }
310        let len = line
311            .char_indices()
312            .find(|(_, c)| *c != ' ' && *c != '\t')
313            .map(|(i, _)| i)
314            .unwrap_or(line.len());
315        candidates.push(&line[..len]);
316    }
317    let mut prefix = candidates.first().copied().unwrap_or("").to_string();
318    for indent in candidates.iter().skip(1) {
319        prefix = common_prefix(&prefix, indent);
320    }
321    let mut out: Vec<&str> = Vec::with_capacity(lines.len());
322    for (idx, line) in lines.iter().enumerate() {
323        if (inline_first && idx == 0) || line.trim().is_empty() {
324            out.push(line);
325        } else {
326            out.push(line.strip_prefix(prefix.as_str()).unwrap_or(line));
327        }
328    }
329    out.join("\n")
330}
331
332/// Split one leading newline preceded only by spaces/tabs.
333fn split_leading_newline(s: &str) -> Option<&str> {
334    let trimmed = s.trim_start_matches([' ', '\t']);
335    trimmed.strip_prefix('\n')
336}
337
338/// Longest shared prefix of two indent strings.
339fn common_prefix(a: &str, b: &str) -> String {
340    a.chars()
341        .zip(b.chars())
342        .take_while(|(x, y)| x == y)
343        .map(|(x, _)| x)
344        .collect()
345}
346
347/// Single-token `KEY=value` split for direct `lower_command` callers and
348/// exotic keys the grammar cannot classify (single tokens only : no whitespace
349/// reassembly, so the quoted-space corruption class cannot arise here).
350/// Returns `Ok(None)` when there is no `=`.
351pub fn split_assignment(text: &str) -> Result<Option<(String, Arg)>> {
352    let Some((key, raw)) = text.split_once('=') else {
353        return Ok(None);
354    };
355    if key.is_empty() {
356        bail!("assignment requires KEY=value format");
357    }
358    Ok(Some((
359        key.to_string(),
360        Arg::String(strip_surrounding_quotes(raw).to_string(), false),
361    )))
362}
363
364/// Parse a TIMEOUT duration token (`500ms`, `10s`, `2m`, `1h`; a bare
365/// number means seconds). One optional space may separate the number
366/// from its unit (`30 s`), like byte counts: bare DSL tokens still
367/// split upstream, so this covers quoted strings and variables.
368pub fn parse_duration(s: &str) -> Result<std::time::Duration> {
369    let s = join_single_space(s)?;
370    let (digits, unit_ms): (&str, u64) = if let Some(v) = s.strip_suffix("ms") {
371        (v, 1)
372    } else if let Some(v) = s.strip_suffix('s') {
373        (v, 1_000)
374    } else if let Some(v) = s.strip_suffix('m') {
375        (v, 60_000)
376    } else if let Some(v) = s.strip_suffix('h') {
377        (v, 3_600_000)
378    } else {
379        (s.as_str(), 1_000)
380    };
381    let n: u64 = digits
382        .parse()
383        .map_err(|_| anyhow!("invalid TIMEOUT duration: {s}"))?;
384    let millis = n
385        .checked_mul(unit_ms)
386        .ok_or_else(|| anyhow!("TIMEOUT duration out of range: {s}"))?;
387    if millis == 0 {
388        bail!("TIMEOUT duration must be positive, got: {s}");
389    }
390    Ok(std::time::Duration::from_millis(millis))
391}
392
393/// Canonical display for a duration: largest exact unit (`500ms`, `10s`,
394/// `2m`, `1h`), falling back to milliseconds. Round-trips through
395/// [`parse_duration`].
396pub fn format_duration(d: &std::time::Duration) -> String {
397    let millis = d.as_millis();
398    if millis.is_multiple_of(3_600_000) {
399        format!("{}h", millis / 3_600_000)
400    } else if millis.is_multiple_of(60_000) {
401        format!("{}m", millis / 60_000)
402    } else if millis.is_multiple_of(1_000) {
403        format!("{}s", millis / 1_000)
404    } else {
405        format!("{millis}ms")
406    }
407}
408
409/// Strip Rust-style `_` digit separators when well-formed (digits and
410/// at most one `.`, separators only between digits, never leading,
411/// trailing, or doubled, with an optional leading `+`/`-` sign passing
412/// through for signed domains); otherwise return the text untouched so
413/// the caller's own parse decides. The single rule behind every
414/// string-to-number coercion (`INT` validation, assertion operands,
415/// byte counts), so `1_000_000` and `-1_000` read identically everywhere
416/// while `1__0` and `1_` never silently become numbers. Unsigned
417/// callers still reject `-` at parse time; `+` parses like every other
418/// Rust-parsed number in the DSL.
419pub fn strip_digit_separators(text: &str) -> String {
420    let body = text
421        .strip_prefix('+')
422        .or_else(|| text.strip_prefix('-'))
423        .unwrap_or(text);
424    let bytes = body.as_bytes();
425    let well_formed = !body.is_empty()
426        && bytes[0].is_ascii_digit()
427        && bytes[bytes.len() - 1].is_ascii_digit()
428        && bytes
429            .iter()
430            .all(|b| b.is_ascii_digit() || *b == b'_' || *b == b'.')
431        && !body.contains("__")
432        && body.bytes().filter(|b| *b == b'.').count() <= 1;
433    if well_formed {
434        text.replace('_', "")
435    } else {
436        text.to_string()
437    }
438}
439
440/// Join a numeric token whose unit may ride separated by one space
441/// (`1 GB`, `30 s`): surrounding whitespace trims, and exactly two
442/// whitespace-separated parts rejoin digit-run plus unit. Anything else
443/// (three parts, a split digit run like `1 0`, an empty string) fails:
444/// the space may only separate the number from its unit, never split
445/// the digits themselves.
446fn join_single_space(s: &str) -> Result<String> {
447    let mut parts = s.split_whitespace();
448    let (first, second) = (parts.next(), parts.next());
449    if parts.next().is_some() {
450        bail!("invalid numeric token: {s}");
451    }
452    match (first, second) {
453        (Some(digits), None) => Ok(digits.to_string()),
454        (Some(digits), Some(unit))
455            if digits
456                .strip_prefix('+')
457                .unwrap_or(digits)
458                .bytes()
459                .all(|b| b.is_ascii_digit() || b == b'_')
460                && unit.bytes().all(|b| b.is_ascii_alphabetic()) =>
461        {
462            Ok(format!("{digits}{unit}"))
463        }
464        _ => bail!("invalid numeric token: {s}"),
465    }
466}
467
468/// Parse a byte-count token (`500`, `500B`, `10KB`, `2MB`, `1GB`, `1TB`
469/// decimal; `10KIB`, `2MIB`, `1GIB`, `1TIB` binary; a bare number means
470/// bytes). Digit runs may group with `_` separators (`1_000_000`),
471/// Rust-literal style: leading, trailing, and doubled separators fail.
472/// One optional space may separate the number from its unit (`1 GB`);
473/// anything more stays rejected, and bare DSL tokens still split
474/// upstream (this covers quoted strings, variables, and flag values).
475/// Fractions stay rejected by design (`1.5GB` fails: float parsing
476/// cannot hold exact byte boundaries past 2^53, and every sub-unit has
477/// an exact integer spelling like `1500MB`). Matching is
478/// case-insensitive (`1gb`, `1GB`, and `1Gb` agree), mirroring
479/// [`parse_duration`]: digits only, no fractions, no signs.
480pub fn parse_byte_count(s: &str) -> Result<u64> {
481    let compact = join_single_space(s)?;
482    let s = compact.as_str();
483    let lower = s.to_ascii_lowercase();
484    let (digits, unit): (&str, u64) = if let Some(v) = lower.strip_suffix("kib") {
485        (v, 1 << 10)
486    } else if let Some(v) = lower.strip_suffix("mib") {
487        (v, 1 << 20)
488    } else if let Some(v) = lower.strip_suffix("gib") {
489        (v, 1 << 30)
490    } else if let Some(v) = lower.strip_suffix("tib") {
491        (v, 1 << 40)
492    } else if let Some(v) = lower.strip_suffix("kb") {
493        (v, 1_000)
494    } else if let Some(v) = lower.strip_suffix("mb") {
495        (v, 1_000_000)
496    } else if let Some(v) = lower.strip_suffix("gb") {
497        (v, 1_000_000_000)
498    } else if let Some(v) = lower.strip_suffix("tb") {
499        (v, 1_000_000_000_000)
500    } else if let Some(v) = lower.strip_suffix('b') {
501        (v, 1)
502    } else {
503        (lower.as_str(), 1)
504    };
505    // Suffixes strip from the lowercased copy; slice the original at
506    // the same boundary so errors echo the caller's spelling.
507    // Separators follow the shared rule, so `1_0KB` parses while
508    // `1__0KB` fails like everywhere else. A leading `+` strips before
509    // the unsigned parse (`u64` rejects it; `-` still fails below).
510    let digits = strip_digit_separators(&s[..digits.len()]);
511    let digits = digits.strip_prefix('+').unwrap_or(&digits);
512    let n: u64 = digits
513        .parse()
514        .map_err(|_| anyhow!("invalid byte count: {s}"))?;
515    let bytes = n
516        .checked_mul(unit)
517        .ok_or_else(|| anyhow!("byte count out of range: {s}"))?;
518    if bytes == 0 {
519        bail!("byte count must be positive, got: {s}");
520    }
521    Ok(bytes)
522}
523
524/// Canonical display for a byte count: largest exact unit (`500B`,
525/// `10KB`, `2MB`, `1GB`, binary `10KIB` and friends), falling back to
526/// bytes. Round-trips through [`parse_byte_count`].
527pub fn format_byte_count(n: u64) -> String {
528    const TIB: u64 = 1 << 40;
529    const TB: u64 = 1_000_000_000_000;
530    const GIB: u64 = 1 << 30;
531    const GB: u64 = 1_000_000_000;
532    const MIB: u64 = 1 << 20;
533    const MB: u64 = 1_000_000;
534    const KIB: u64 = 1 << 10;
535    const KB: u64 = 1_000;
536    if n >= TIB && n.is_multiple_of(TIB) {
537        format!("{}TiB", n / TIB)
538    } else if n >= TB && n.is_multiple_of(TB) {
539        format!("{}TB", n / TB)
540    } else if n >= GIB && n.is_multiple_of(GIB) {
541        format!("{}GiB", n / GIB)
542    } else if n >= GB && n.is_multiple_of(GB) {
543        format!("{}GB", n / GB)
544    } else if n >= MIB && n.is_multiple_of(MIB) {
545        format!("{}MiB", n / MIB)
546    } else if n >= MB && n.is_multiple_of(MB) {
547        format!("{}MB", n / MB)
548    } else if n >= KIB && n.is_multiple_of(KIB) {
549        format!("{}KiB", n / KIB)
550    } else if n >= KB && n.is_multiple_of(KB) {
551        format!("{}KB", n / KB)
552    } else {
553        format!("{n}B")
554    }
555}
556
557/// Data direction for an argument.
558#[derive(Debug, Clone, Copy, PartialEq, Eq)]
559pub enum IoDirection {
560    Read,
561    Write,
562}
563
564/// Stream type for fallback or default output.
565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
566pub enum Stream {
567    Stdin,
568    Stdout,
569    Stderr,
570}
571
572/// Metadata for a single flag.
573pub struct FlagSpec {
574    pub name: &'static str,
575    pub long: &'static str,
576    pub value_type: FlagValueType,
577    pub required: bool,
578    pub description: &'static str,
579}
580
581/// Type of value a flag accepts.
582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
583pub enum FlagValueType {
584    /// Boolean flag (no value required).
585    Flag,
586    /// String-valued flag.
587    String,
588    /// Integer-valued flag.
589    Int,
590}
591
592impl FlagValueType {
593    /// Display label using the type vocabulary. A bare `Flag`
594    /// switch carries no value; `BOOL` names what its presence asserts.
595    pub fn label(&self) -> &'static str {
596        match self {
597            FlagValueType::Flag => "BOOL",
598            FlagValueType::String => "STRING",
599            FlagValueType::Int => "INT",
600        }
601    }
602}
603
604/// Complete metadata for a command.
605pub struct CommandMeta {
606    pub name: &'static str,
607    pub syntax: &'static str,
608    pub summary: &'static str,
609    pub description: &'static str,
610    pub args: &'static [ArgSpec],
611    pub flags: &'static [FlagSpec],
612    pub default_output: Option<Stream>,
613    pub examples: &'static [Example],
614    /// Whether the entry lists in the command index table. Structural
615    /// pseudo-entries with no typable keyword (e.g. `MUTATION` for
616    /// `$var = <expr>`) document in the body but stay out of the index.
617    pub in_index: bool,
618}
619
620/// An executable example for a command or function.
621#[derive(Debug, Clone, Copy, PartialEq, Eq)]
622pub struct Example {
623    pub name: &'static str,
624    pub fence_meta: Option<&'static str>,
625    pub code: &'static str,
626}
627
628/// Trait for command metadata and lowering. No execution types.
629///
630/// This trait lives in `oxdock-parser` and has zero dependencies on
631/// `oxdock-core`. Execution dispatch is handled separately by the
632/// `define_pipeline!` macro in `oxdock-core`.
633pub trait CommandSpec {
634    const NAME: &'static str;
635
636    fn metadata() -> CommandMeta;
637    fn lower(flags: Vec<(String, Arg)>, args: Vec<Arg>) -> Result<StepKind>;
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643    use crate::ast::Expr;
644
645    fn lit(text: &str) -> Arg {
646        Arg::String(text.to_string(), false)
647    }
648
649    fn var(name: &str) -> Arg {
650        Arg::Expr(Expr::Var {
651            name: name.to_string(),
652        })
653    }
654
655    #[test]
656    fn validate_literal_covers_each_variant() {
657        ArgType::String.check_arg(&lit("anything at all")).unwrap();
658        ArgType::Path.check_arg(&lit("a/b/../c")).unwrap();
659        ArgType::Int.check_arg(&lit("3")).unwrap();
660        assert!(ArgType::Int.check_arg(&lit("banana")).is_err());
661        ArgType::Duration.check_arg(&lit("10s")).unwrap();
662        ArgType::Duration.check_arg(&lit("30")).unwrap();
663        assert!(ArgType::Duration.check_arg(&lit("banana")).is_err());
664        assert!(ArgType::Duration.check_arg(&lit("0s")).is_err());
665        ArgType::List.check_arg(&lit("$x")).unwrap();
666        assert!(ArgType::List.check_arg(&lit("x")).is_err());
667        // Only app types plus the visibly-marked placeholder remain.
668        assert_eq!(ArgType::Any.label(), "<any>");
669        ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
670            .check_arg(&lit("LOCAL"))
671            .unwrap();
672        // Lowercase spellings are rejected: keyword arguments stay uppercase.
673        assert!(
674            ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
675                .check_arg(&lit("local"))
676                .is_err()
677        );
678        assert!(
679            ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
680                .check_arg(&lit("REMOTE"))
681                .is_err()
682        );
683    }
684
685    #[test]
686    fn check_arg_defers_dynamics_and_enforces_var() {
687        // Templates defer: their values only exist after interpolation.
688        assert_eq!(
689            ArgType::Duration.check_arg(&lit("{{ $d }}")).unwrap(),
690            CheckOutcome::Deferred
691        );
692        // Variables satisfy List statically and defer for everything else.
693        assert_eq!(
694            ArgType::List.check_arg(&var("x")).unwrap(),
695            CheckOutcome::Static
696        );
697        assert_eq!(
698            ArgType::Duration.check_arg(&var("d")).unwrap(),
699            CheckOutcome::Deferred
700        );
701        // Non-variable expressions where a $var is required fail at lower.
702        let list = Arg::Expr(Expr::List(vec![]));
703        assert!(ArgType::List.check_arg(&list).is_err());
704        assert_eq!(
705            ArgType::String.check_arg(&list).unwrap(),
706            CheckOutcome::Deferred
707        );
708        assert_eq!(ArgType::List.label(), "LIST");
709        // `$var` shapes are enforced per command in `lower`, not here:
710        // a bare word passes the String check and fails lowering.
711        assert_eq!(
712            ArgType::String.check_arg(&lit("x")).unwrap(),
713            CheckOutcome::Static
714        );
715    }
716
717    fn spec(index: usize, required: bool, arg_type: ArgType) -> ArgSpec {
718        ArgSpec {
719            name: "p",
720            arg_type,
721            description: "",
722            io: IoDirection::Write,
723            index,
724            required,
725            fallback_stream: None,
726        }
727    }
728
729    #[test]
730    fn positionals_enforce_required_and_rest_tails() {
731        let specs = [spec(0, true, ArgType::Int)];
732        assert!(validate_positionals_against_meta("T", &specs, &[]).is_err());
733        assert!(validate_positionals_against_meta("T", &specs, &[lit("3")]).is_ok());
734        assert!(validate_positionals_against_meta("T", &specs, &[lit("banana")]).is_err());
735
736        // Rest validates EVERY trailing positional, not just the first.
737        let specs = [ArgSpec {
738            arg_type: ArgType::Rest(&ArgType::Int),
739            ..spec(0, true, ArgType::Int)
740        }];
741        assert!(
742            validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2"), lit("banana")])
743                .is_err()
744        );
745        assert!(validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2")]).is_ok());
746        // Extras beyond fixed-arity specs fail (no silent truncation).
747        let specs = [spec(0, true, ArgType::Int)];
748        let err = validate_positionals_against_meta("T", &specs, &[lit("1"), lit("extra")])
749            .expect_err("extras must fail");
750        assert!(
751            err.to_string().contains("at most 1"),
752            "unexpected error: {err:#}"
753        );
754    }
755}