1use crate::ast::{Arg, Expr, StepKind};
2use crate::error::{ParseError, SpanContext};
3use anyhow::{Result, anyhow, bail};
4
5pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ArgType {
27 String,
28 Path,
29 Int,
30 Duration,
31 List,
34 Any,
38 OneOf(&'static [&'static str]),
41 Rest(&'static ArgType),
43}
44
45impl ArgType {
46 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum CheckOutcome {
145 Static,
147 Deferred,
150}
151
152pub 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 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
236pub 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
253pub 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
332fn split_leading_newline(s: &str) -> Option<&str> {
334 let trimmed = s.trim_start_matches([' ', '\t']);
335 trimmed.strip_prefix('\n')
336}
337
338fn 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
347pub 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
364pub 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
393pub 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
409pub 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
440fn 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
468pub 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 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
524pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
559pub enum IoDirection {
560 Read,
561 Write,
562}
563
564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
566pub enum Stream {
567 Stdin,
568 Stdout,
569 Stderr,
570}
571
572pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
583pub enum FlagValueType {
584 Flag,
586 String,
588 Int,
590}
591
592impl FlagValueType {
593 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
604pub 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 pub in_index: bool,
618}
619
620#[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
628pub 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(name.to_string()))
651 }
652
653 #[test]
654 fn validate_literal_covers_each_variant() {
655 ArgType::String.check_arg(&lit("anything at all")).unwrap();
656 ArgType::Path.check_arg(&lit("a/b/../c")).unwrap();
657 ArgType::Int.check_arg(&lit("3")).unwrap();
658 assert!(ArgType::Int.check_arg(&lit("banana")).is_err());
659 ArgType::Duration.check_arg(&lit("10s")).unwrap();
660 ArgType::Duration.check_arg(&lit("30")).unwrap();
661 assert!(ArgType::Duration.check_arg(&lit("banana")).is_err());
662 assert!(ArgType::Duration.check_arg(&lit("0s")).is_err());
663 ArgType::List.check_arg(&lit("$x")).unwrap();
664 assert!(ArgType::List.check_arg(&lit("x")).is_err());
665 assert_eq!(ArgType::Any.label(), "<any>");
667 ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
668 .check_arg(&lit("LOCAL"))
669 .unwrap();
670 assert!(
672 ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
673 .check_arg(&lit("local"))
674 .is_err()
675 );
676 assert!(
677 ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
678 .check_arg(&lit("REMOTE"))
679 .is_err()
680 );
681 }
682
683 #[test]
684 fn check_arg_defers_dynamics_and_enforces_var() {
685 assert_eq!(
687 ArgType::Duration.check_arg(&lit("{{ $d }}")).unwrap(),
688 CheckOutcome::Deferred
689 );
690 assert_eq!(
692 ArgType::List.check_arg(&var("x")).unwrap(),
693 CheckOutcome::Static
694 );
695 assert_eq!(
696 ArgType::Duration.check_arg(&var("d")).unwrap(),
697 CheckOutcome::Deferred
698 );
699 let list = Arg::Expr(Expr::List(vec![]));
701 assert!(ArgType::List.check_arg(&list).is_err());
702 assert_eq!(
703 ArgType::String.check_arg(&list).unwrap(),
704 CheckOutcome::Deferred
705 );
706 assert_eq!(ArgType::List.label(), "LIST");
707 assert_eq!(
710 ArgType::String.check_arg(&lit("x")).unwrap(),
711 CheckOutcome::Static
712 );
713 }
714
715 fn spec(index: usize, required: bool, arg_type: ArgType) -> ArgSpec {
716 ArgSpec {
717 name: "p",
718 arg_type,
719 description: "",
720 io: IoDirection::Write,
721 index,
722 required,
723 fallback_stream: None,
724 }
725 }
726
727 #[test]
728 fn positionals_enforce_required_and_rest_tails() {
729 let specs = [spec(0, true, ArgType::Int)];
730 assert!(validate_positionals_against_meta("T", &specs, &[]).is_err());
731 assert!(validate_positionals_against_meta("T", &specs, &[lit("3")]).is_ok());
732 assert!(validate_positionals_against_meta("T", &specs, &[lit("banana")]).is_err());
733
734 let specs = [ArgSpec {
736 arg_type: ArgType::Rest(&ArgType::Int),
737 ..spec(0, true, ArgType::Int)
738 }];
739 assert!(
740 validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2"), lit("banana")])
741 .is_err()
742 );
743 assert!(validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2")]).is_ok());
744 let specs = [spec(0, true, ArgType::Int)];
746 let err = validate_positionals_against_meta("T", &specs, &[lit("1"), lit("extra")])
747 .expect_err("extras must fail");
748 assert!(
749 err.to_string().contains("at most 1"),
750 "unexpected error: {err:#}"
751 );
752 }
753}