1use crate::ast::{Arg, Expr, StepKind};
2use crate::diagnostics as dsl_diag;
3use crate::error::{ParseError, ParseErrorKind, ParseResult, SpanContext};
4use crate::{
5 BOOL_TYPE_NAME, DURATION_TYPE_NAME, INT_TYPE_NAME, LIST_TYPE_NAME, PATH_TYPE_NAME,
6 STRING_TYPE_NAME, VAR_SIGIL_CHAR,
7};
8use oxdock_diagnostics::DiagnosticResult;
9
10pub struct ArgSpec {
12 pub name: &'static str,
13 pub arg_type: ArgType,
14 pub description: &'static str,
15 pub io: IoDirection,
16 pub index: usize,
17 pub required: bool,
18 pub fallback_stream: Option<Stream>,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum ArgType {
32 String,
33 Path,
34 Int,
35 Duration,
36 List,
39 Any,
43 OneOf(&'static [&'static str]),
46 Rest(&'static ArgType),
48}
49
50impl ArgType {
51 pub fn label(&self) -> String {
59 match self {
60 ArgType::String => STRING_TYPE_NAME.to_string(),
61 ArgType::Path => PATH_TYPE_NAME.to_string(),
62 ArgType::Int => INT_TYPE_NAME.to_string(),
63 ArgType::Duration => DURATION_TYPE_NAME.to_string(),
64 ArgType::List => LIST_TYPE_NAME.to_string(),
65 ArgType::Any => "<any>".to_string(),
66 ArgType::OneOf(options) => options.join("|"),
67 ArgType::Rest(inner) => format!("{}...", inner.label()),
68 }
69 }
70
71 pub fn anchor(&self) -> Option<String> {
75 match self {
76 ArgType::String => Some(crate::value::type_anchor(STRING_TYPE_NAME)),
77 ArgType::Path => Some(crate::value::type_anchor(PATH_TYPE_NAME)),
78 ArgType::Int => Some(crate::value::type_anchor(INT_TYPE_NAME)),
79 ArgType::Duration => Some(crate::value::type_anchor(DURATION_TYPE_NAME)),
80 ArgType::List => Some(crate::value::type_anchor(LIST_TYPE_NAME)),
81 ArgType::Any => None,
82 ArgType::OneOf(_) => None,
83 ArgType::Rest(inner) => inner.anchor(),
84 }
85 }
86
87 pub fn validate_literal(&self, literal: &str) -> DiagnosticResult<()> {
90 match self {
91 ArgType::String | ArgType::Path | ArgType::Any => Ok(()),
92 ArgType::Int => strip_digit_separators(literal)
93 .parse::<i64>()
94 .map(|_| ())
95 .map_err(|_| dsl_diag::expected_int(literal)),
96 ArgType::Duration => parse_duration(literal).map(|_| ()),
97 ArgType::List => {
98 if literal.starts_with(VAR_SIGIL_CHAR) {
99 Ok(())
100 } else {
101 Err(dsl_diag::expected_var(literal))
102 }
103 }
104 ArgType::OneOf(options) => {
105 if options.contains(&literal) {
108 Ok(())
109 } else {
110 Err(dsl_diag::expected_one_of(options, literal))
111 }
112 }
113 ArgType::Rest(inner) => inner.validate_literal(literal),
114 }
115 }
116
117 pub fn check_arg(&self, arg: &Arg) -> DiagnosticResult<CheckOutcome> {
122 match arg {
123 Arg::String(s, _) if !s.contains("{{") => {
124 self.validate_literal(s)?;
125 Ok(CheckOutcome::Static)
126 }
127 Arg::String(_, _) => Ok(CheckOutcome::Deferred),
128 Arg::Parts(_) => Ok(CheckOutcome::Deferred),
129 Arg::Expr(Expr::Var { .. }) => {
130 if matches!(*self, ArgType::List) {
131 Ok(CheckOutcome::Static)
132 } else {
133 Ok(CheckOutcome::Deferred)
134 }
135 }
136 Arg::Expr(_) => {
137 if matches!(*self, ArgType::List) {
138 Err(dsl_diag::expected_var_expression(&arg.render()))
139 } else {
140 Ok(CheckOutcome::Deferred)
141 }
142 }
143 }
144 }
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum CheckOutcome {
150 Static,
152 Deferred,
155}
156
157pub fn validate_positionals_against_meta(
163 cmd_name: &str,
164 specs: &[ArgSpec],
165 args: &[Arg],
166) -> ParseResult<()> {
167 let has_rest = specs
168 .last()
169 .is_some_and(|s| matches!(s.arg_type, ArgType::Rest(_)));
170
171 if !has_rest && args.len() > specs.len() {
172 return Err(ParseError::from_diagnostic(
173 ParseErrorKind::Validation {
174 command: cmd_name.to_string(),
175 },
176 dsl_diag::too_many_positionals(cmd_name, specs.len(), args.len()),
177 &SpanContext::line_only(0),
178 ));
179 }
180
181 for spec in specs {
182 if let ArgType::Rest(inner) = spec.arg_type {
183 let tail = args.get(spec.index..).unwrap_or(&[]);
186 if tail.is_empty() && spec.required {
187 return Err(ParseError::from_diagnostic(
188 ParseErrorKind::Validation {
189 command: cmd_name.to_string(),
190 },
191 dsl_diag::missing_argument(cmd_name, spec.name),
192 &SpanContext::line_only(0),
193 ));
194 }
195 for arg in tail {
196 check_one(cmd_name, spec, inner, arg)?;
197 }
198 return Ok(());
199 }
200 match args.get(spec.index) {
201 Some(arg) => check_one(cmd_name, spec, &spec.arg_type, arg)?,
202 None if spec.required => {
203 return Err(ParseError::from_diagnostic(
204 ParseErrorKind::Validation {
205 command: cmd_name.to_string(),
206 },
207 dsl_diag::missing_argument(cmd_name, spec.name),
208 &SpanContext::line_only(0),
209 ));
210 }
211 None => {}
212 }
213 }
214 Ok(())
215}
216
217fn check_one(cmd_name: &str, spec: &ArgSpec, arg_type: &ArgType, arg: &Arg) -> ParseResult<()> {
218 match arg_type.check_arg(arg) {
219 Ok(_) => Ok(()),
220 Err(e) => Err(ParseError::from_diagnostic(
221 ParseErrorKind::Validation {
222 command: cmd_name.to_string(),
223 },
224 dsl_diag::arg_type_mismatch(cmd_name, spec.name, &arg.render(), e),
225 &SpanContext::line_only(0),
226 )),
227 }
228}
229
230pub fn strip_surrounding_quotes(value: &str) -> &str {
234 if let Some(inner) = value
235 .strip_prefix("\"\"\"")
236 .and_then(|s| s.strip_suffix("\"\"\""))
237 {
238 return inner;
239 }
240 value
241 .strip_prefix('"')
242 .and_then(|s| s.strip_suffix('"'))
243 .or_else(|| value.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
244 .unwrap_or(value)
245}
246
247pub fn lower_block_string(s: &str) -> String {
266 let inner = s.strip_prefix("\"\"\"").unwrap_or(s);
267 let inner = inner.strip_suffix("\"\"\"").unwrap_or(inner);
268 let norm = inner.replace("\r\n", "\n").replace('\r', "\n");
269 let (body, inline_first) = match split_leading_newline(&norm) {
270 Some(rest) => (rest.to_string(), false),
271 None => (norm.clone(), true),
272 };
273 if body.is_empty() {
274 return String::new();
275 }
276 let mut lines: Vec<&str> = body.split('\n').collect();
277 let closing_own_line = norm.contains('\n') && lines.last().is_some_and(|l| l.trim().is_empty());
278 let closing_indent = if closing_own_line {
279 lines.pop().unwrap_or("").to_string()
280 } else {
281 String::new()
282 };
283 let content: &[&str] = if inline_first && !lines.is_empty() {
284 &lines[1..]
285 } else {
286 &lines[..]
287 };
288 if inline_first && lines.len() == 1 && lines[0].trim().is_empty() {
289 return String::new();
290 }
291 if !(inline_first && !lines.is_empty() && !lines[0].trim().is_empty())
292 && !content.iter().any(|l| !l.trim().is_empty())
293 {
294 return String::new();
295 }
296 let mut candidates: Vec<&str> = Vec::new();
297 if closing_own_line {
298 candidates.push(closing_indent.as_str());
299 }
300 for line in content {
301 if line.trim().is_empty() {
302 continue;
303 }
304 let len = line
305 .char_indices()
306 .find(|(_, c)| *c != ' ' && *c != '\t')
307 .map(|(i, _)| i)
308 .unwrap_or(line.len());
309 candidates.push(&line[..len]);
310 }
311 let mut prefix = candidates.first().copied().unwrap_or("").to_string();
312 for indent in candidates.iter().skip(1) {
313 prefix = common_prefix(&prefix, indent);
314 }
315 let mut out: Vec<&str> = Vec::with_capacity(lines.len());
316 for (idx, line) in lines.iter().enumerate() {
317 if (inline_first && idx == 0) || line.trim().is_empty() {
318 out.push(line);
319 } else {
320 out.push(line.strip_prefix(prefix.as_str()).unwrap_or(line));
321 }
322 }
323 out.join("\n")
324}
325
326fn split_leading_newline(s: &str) -> Option<&str> {
328 let trimmed = s.trim_start_matches([' ', '\t']);
329 trimmed.strip_prefix('\n')
330}
331
332fn common_prefix(a: &str, b: &str) -> String {
334 a.chars()
335 .zip(b.chars())
336 .take_while(|(x, y)| x == y)
337 .map(|(x, _)| x)
338 .collect()
339}
340
341pub fn split_assignment(text: &str) -> DiagnosticResult<Option<(String, Arg)>> {
346 let Some((key, raw)) = text.split_once('=') else {
347 return Ok(None);
348 };
349 if key.is_empty() {
350 return Err(dsl_diag::assignment_requires_key_value());
351 }
352 Ok(Some((
353 key.to_string(),
354 Arg::String(strip_surrounding_quotes(raw).to_string(), false),
355 )))
356}
357
358pub fn parse_duration(s: &str) -> DiagnosticResult<std::time::Duration> {
363 let s = join_single_space(s)?;
364 let (digits, unit_ms): (&str, u64) = if let Some(v) = s.strip_suffix("ms") {
365 (v, 1)
366 } else if let Some(v) = s.strip_suffix('s') {
367 (v, 1_000)
368 } else if let Some(v) = s.strip_suffix('m') {
369 (v, 60_000)
370 } else if let Some(v) = s.strip_suffix('h') {
371 (v, 3_600_000)
372 } else {
373 (s.as_str(), 1_000)
374 };
375 let n: u64 = digits
376 .parse()
377 .map_err(|_| dsl_diag::invalid_timeout_duration(&s))?;
378 let millis = n
379 .checked_mul(unit_ms)
380 .ok_or_else(|| dsl_diag::timeout_duration_out_of_range(&s))?;
381 if millis == 0 {
382 return Err(dsl_diag::timeout_duration_not_positive(&s));
383 }
384 Ok(std::time::Duration::from_millis(millis))
385}
386
387pub fn format_duration(d: &std::time::Duration) -> String {
391 let millis = d.as_millis();
392 if millis.is_multiple_of(3_600_000) {
393 format!("{}h", millis / 3_600_000)
394 } else if millis.is_multiple_of(60_000) {
395 format!("{}m", millis / 60_000)
396 } else if millis.is_multiple_of(1_000) {
397 format!("{}s", millis / 1_000)
398 } else {
399 format!("{millis}ms")
400 }
401}
402
403pub fn strip_digit_separators(text: &str) -> String {
414 let body = text
415 .strip_prefix('+')
416 .or_else(|| text.strip_prefix('-'))
417 .unwrap_or(text);
418 let bytes = body.as_bytes();
419 let well_formed = !body.is_empty()
420 && bytes[0].is_ascii_digit()
421 && bytes[bytes.len() - 1].is_ascii_digit()
422 && bytes
423 .iter()
424 .all(|b| b.is_ascii_digit() || *b == b'_' || *b == b'.')
425 && !body.contains("__")
426 && body.bytes().filter(|b| *b == b'.').count() <= 1;
427 if well_formed {
428 text.replace('_', "")
429 } else {
430 text.to_string()
431 }
432}
433
434fn join_single_space(s: &str) -> DiagnosticResult<String> {
441 let mut parts = s.split_whitespace();
442 let (first, second) = (parts.next(), parts.next());
443 if parts.next().is_some() {
444 return Err(dsl_diag::invalid_numeric_token(s));
445 }
446 match (first, second) {
447 (Some(digits), None) => Ok(digits.to_string()),
448 (Some(digits), Some(unit))
449 if digits
450 .strip_prefix('+')
451 .unwrap_or(digits)
452 .bytes()
453 .all(|b| b.is_ascii_digit() || b == b'_')
454 && unit.bytes().all(|b| b.is_ascii_alphabetic()) =>
455 {
456 Ok(format!("{digits}{unit}"))
457 }
458 _ => Err(dsl_diag::invalid_numeric_token(s)),
459 }
460}
461
462pub fn parse_byte_count(s: &str) -> DiagnosticResult<u64> {
475 let compact = join_single_space(s)?;
476 let s = compact.as_str();
477 let lower = s.to_ascii_lowercase();
478 let (digits, unit): (&str, u64) = if let Some(v) = lower.strip_suffix("kib") {
479 (v, 1 << 10)
480 } else if let Some(v) = lower.strip_suffix("mib") {
481 (v, 1 << 20)
482 } else if let Some(v) = lower.strip_suffix("gib") {
483 (v, 1 << 30)
484 } else if let Some(v) = lower.strip_suffix("tib") {
485 (v, 1 << 40)
486 } else if let Some(v) = lower.strip_suffix("kb") {
487 (v, 1_000)
488 } else if let Some(v) = lower.strip_suffix("mb") {
489 (v, 1_000_000)
490 } else if let Some(v) = lower.strip_suffix("gb") {
491 (v, 1_000_000_000)
492 } else if let Some(v) = lower.strip_suffix("tb") {
493 (v, 1_000_000_000_000)
494 } else if let Some(v) = lower.strip_suffix('b') {
495 (v, 1)
496 } else {
497 (lower.as_str(), 1)
498 };
499 let digits = strip_digit_separators(&s[..digits.len()]);
505 let digits = digits.strip_prefix('+').unwrap_or(&digits);
506 let n: u64 = digits
507 .parse()
508 .map_err(|_| dsl_diag::invalid_byte_count(s))?;
509 let bytes = n
510 .checked_mul(unit)
511 .ok_or_else(|| dsl_diag::byte_count_out_of_range(s))?;
512 if bytes == 0 {
513 return Err(dsl_diag::byte_count_not_positive(s));
514 }
515 Ok(bytes)
516}
517
518pub fn format_byte_count(n: u64) -> String {
522 const TIB: u64 = 1 << 40;
523 const TB: u64 = 1_000_000_000_000;
524 const GIB: u64 = 1 << 30;
525 const GB: u64 = 1_000_000_000;
526 const MIB: u64 = 1 << 20;
527 const MB: u64 = 1_000_000;
528 const KIB: u64 = 1 << 10;
529 const KB: u64 = 1_000;
530 if n >= TIB && n.is_multiple_of(TIB) {
531 format!("{}TiB", n / TIB)
532 } else if n >= TB && n.is_multiple_of(TB) {
533 format!("{}TB", n / TB)
534 } else if n >= GIB && n.is_multiple_of(GIB) {
535 format!("{}GiB", n / GIB)
536 } else if n >= GB && n.is_multiple_of(GB) {
537 format!("{}GB", n / GB)
538 } else if n >= MIB && n.is_multiple_of(MIB) {
539 format!("{}MiB", n / MIB)
540 } else if n >= MB && n.is_multiple_of(MB) {
541 format!("{}MB", n / MB)
542 } else if n >= KIB && n.is_multiple_of(KIB) {
543 format!("{}KiB", n / KIB)
544 } else if n >= KB && n.is_multiple_of(KB) {
545 format!("{}KB", n / KB)
546 } else {
547 format!("{n}B")
548 }
549}
550
551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553pub enum IoDirection {
554 Read,
555 Write,
556}
557
558#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum Stream {
561 Stdin,
562 Stdout,
563 Stderr,
564}
565
566pub struct FlagSpec {
568 pub name: &'static str,
569 pub long: &'static str,
570 pub value_type: FlagValueType,
571 pub required: bool,
572 pub description: &'static str,
573}
574
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
577pub enum FlagValueType {
578 Flag,
580 String,
582 Int,
584}
585
586impl FlagValueType {
587 pub fn label(&self) -> &'static str {
590 match self {
591 FlagValueType::Flag => BOOL_TYPE_NAME,
592 FlagValueType::String => STRING_TYPE_NAME,
593 FlagValueType::Int => INT_TYPE_NAME,
594 }
595 }
596}
597
598pub struct CommandMeta {
600 pub name: &'static str,
601 pub syntax: &'static str,
602 pub summary: &'static str,
603 pub description: &'static str,
604 pub args: &'static [ArgSpec],
605 pub flags: &'static [FlagSpec],
606 pub default_output: Option<Stream>,
607 pub examples: &'static [Example],
608 pub in_index: bool,
612}
613
614#[derive(Debug, Clone, Copy, PartialEq, Eq)]
616pub struct Example {
617 pub name: &'static str,
618 pub fence_meta: Option<&'static str>,
619 pub code: &'static str,
620}
621
622pub trait CommandSpec {
628 const NAME: &'static str;
629
630 fn metadata() -> CommandMeta;
631 fn lower(flags: Vec<(String, Arg)>, args: Vec<Arg>) -> ParseResult<StepKind>;
632}
633
634#[cfg(test)]
635mod tests {
636 use super::*;
637 use crate::ast::Expr;
638
639 fn lit(text: &str) -> Arg {
640 Arg::String(text.to_string(), false)
641 }
642
643 fn var(name: &str) -> Arg {
644 Arg::Expr(Expr::Var {
645 name: name.to_string(),
646 })
647 }
648
649 #[test]
650 fn validate_literal_covers_each_variant() {
651 ArgType::String.check_arg(&lit("anything at all")).unwrap();
652 ArgType::Path.check_arg(&lit("a/b/../c")).unwrap();
653 ArgType::Int.check_arg(&lit("3")).unwrap();
654 assert!(ArgType::Int.check_arg(&lit("banana")).is_err());
655 ArgType::Duration.check_arg(&lit("10s")).unwrap();
656 ArgType::Duration.check_arg(&lit("30")).unwrap();
657 assert!(ArgType::Duration.check_arg(&lit("banana")).is_err());
658 assert!(ArgType::Duration.check_arg(&lit("0s")).is_err());
659 ArgType::List.check_arg(&lit("$x")).unwrap();
660 assert!(ArgType::List.check_arg(&lit("x")).is_err());
661 assert_eq!(ArgType::Any.label(), "<any>");
663 ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
664 .check_arg(&lit("LOCAL"))
665 .unwrap();
666 assert!(
668 ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
669 .check_arg(&lit("local"))
670 .is_err()
671 );
672 assert!(
673 ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
674 .check_arg(&lit("REMOTE"))
675 .is_err()
676 );
677 }
678
679 #[test]
680 fn check_arg_defers_dynamics_and_enforces_var() {
681 assert_eq!(
683 ArgType::Duration.check_arg(&lit("{{ $d }}")).unwrap(),
684 CheckOutcome::Deferred
685 );
686 assert_eq!(
688 ArgType::List.check_arg(&var("x")).unwrap(),
689 CheckOutcome::Static
690 );
691 assert_eq!(
692 ArgType::Duration.check_arg(&var("d")).unwrap(),
693 CheckOutcome::Deferred
694 );
695 let list = Arg::Expr(Expr::List(vec![]));
697 assert!(ArgType::List.check_arg(&list).is_err());
698 assert_eq!(
699 ArgType::String.check_arg(&list).unwrap(),
700 CheckOutcome::Deferred
701 );
702 assert_eq!(ArgType::List.label(), "LIST");
703 assert_eq!(
706 ArgType::String.check_arg(&lit("x")).unwrap(),
707 CheckOutcome::Static
708 );
709 }
710
711 fn spec(index: usize, required: bool, arg_type: ArgType) -> ArgSpec {
712 ArgSpec {
713 name: "p",
714 arg_type,
715 description: "",
716 io: IoDirection::Write,
717 index,
718 required,
719 fallback_stream: None,
720 }
721 }
722
723 #[test]
724 fn positionals_enforce_required_and_rest_tails() {
725 let specs = [spec(0, true, ArgType::Int)];
726 assert!(validate_positionals_against_meta("T", &specs, &[]).is_err());
727 assert!(validate_positionals_against_meta("T", &specs, &[lit("3")]).is_ok());
728 assert!(validate_positionals_against_meta("T", &specs, &[lit("banana")]).is_err());
729
730 let specs = [ArgSpec {
732 arg_type: ArgType::Rest(&ArgType::Int),
733 ..spec(0, true, ArgType::Int)
734 }];
735 assert!(
736 validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2"), lit("banana")])
737 .is_err()
738 );
739 assert!(validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2")]).is_ok());
740 let specs = [spec(0, true, ArgType::Int)];
742 let err = validate_positionals_against_meta("T", &specs, &[lit("1"), lit("extra")])
743 .expect_err("extras must fail");
744 assert!(
745 err.to_string().contains("at most 1"),
746 "unexpected error: {err:#}"
747 );
748 }
749}