1use std::fmt;
16
17use crate::ast::{
18 Arg, ArgPart, Expr, IoBinding, IoStream, PipeTarget, Step, Value, WorkspaceTarget,
19};
20use crate::command::{
21 ArgSpec, ArgType, CommandMeta, Example, FlagSpec, FlagValueType, IoDirection, Stream,
22 split_assignment,
23};
24use crate::constants::{KEYWORD_EXPORT, KEYWORD_IMPORT};
25use crate::error::{ParseError, ParseResult, SpanContext};
26use indoc::indoc;
27
28pub const REMOTE_RESERVED_WORDS: &[&str] = &["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM", "REMOTE"];
38
39pub fn is_valid_remote_target(target: &str) -> bool {
43 if target.is_empty() || target.len() > 64 {
44 return false;
45 }
46 if REMOTE_RESERVED_WORDS.contains(&target) {
47 return false;
48 }
49 let mut chars = target.chars();
50 match chars.next() {
51 Some(first) if first.is_ascii_alphanumeric() => {}
52 _ => return false,
53 }
54 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
55}
56
57fn join_value(args: Vec<Arg>, cmd_name: &str) -> ParseResult<Arg> {
62 if args.is_empty() {
63 return Err(ParseError::validation(
64 cmd_name,
65 format!("{cmd_name} requires at least one argument"),
66 &SpanContext::line_only(0),
67 ));
68 }
69 if args.len() == 1 {
70 return Ok(args.into_iter().next().unwrap());
71 }
72 if args.iter().all(|a| matches!(a, Arg::String(..))) {
73 return Ok(Arg::String(
74 args.iter()
75 .map(|a| a.as_str())
76 .collect::<Vec<_>>()
77 .join(" "),
78 false,
79 ));
80 }
81 let mut parts = Vec::new();
82 for (index, arg) in args.into_iter().enumerate() {
83 if index > 0 {
84 parts.push(ArgPart::Text(" ".to_string(), false));
85 }
86 match arg {
87 Arg::String(text, quoted) => parts.push(ArgPart::Text(text, quoted)),
88 Arg::Expr(expr) => parts.push(ArgPart::Expr(expr)),
89 Arg::Parts(inner) => parts.extend(inner),
90 }
91 }
92 Ok(Arg::Parts(parts))
93}
94
95pub fn lower_env_assignment(args: Vec<Arg>) -> ParseResult<StepKind> {
99 let arg = args.into_iter().next().ok_or_else(|| {
100 ParseError::validation(
101 "ENV",
102 "ENV requires KEY=value".to_string(),
103 &SpanContext::line_only(0),
104 )
105 })?;
106 let Some((key, value)) = split_assignment(arg.as_str())
107 .map_err(|e| ParseError::validation("ENV", e.to_string(), &SpanContext::line_only(0)))?
108 else {
109 return Err(ParseError::validation(
110 "ENV",
111 "ENV requires KEY=value format".to_string(),
112 &SpanContext::line_only(0),
113 ));
114 };
115 Ok(StepKind::Env { key, value })
116}
117
118pub(crate) fn canonical_assignment_arg(key: &str, value: &Arg) -> Arg {
123 Arg::String(format!("{key}={}", value.render()), false)
124}
125
126fn fmt_assert_target(target: &AssertTarget) -> String {
129 match target {
130 AssertTarget::Value(arg) => fmt_value(arg, quote_msg),
131 _ => target.render(),
132 }
133}
134
135fn fmt_value(arg: &Arg, quote: fn(&str) -> String) -> String {
140 match arg {
141 Arg::Expr(_) => arg.render(),
142 Arg::String(text, _) => quote(text),
143 Arg::Parts(_) => {
144 let rendered = arg.render();
145 if rendered.contains(';')
146 || rendered.contains('}')
147 || rendered.contains('\n')
148 || rendered.contains('\r')
149 {
150 quote(&rendered)
151 } else {
152 rendered
153 }
154 }
155 }
156}
157
158fn quote_dsl_string(s: &str) -> String {
159 format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
167}
168
169fn quote_arg(s: &str) -> String {
170 let is_safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
171 && !s.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '/' || c == '.')
172 && !crate::Command::is_statement_keyword(s);
173 if is_safe && !s.is_empty() {
174 s.to_string()
175 } else {
176 quote_dsl_string(s)
177 }
178}
179
180fn quote_msg(s: &str) -> String {
181 let safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
182 && !s.starts_with(|c: char| c.is_ascii_digit())
183 && !crate::Command::is_statement_keyword(s);
184 if safe && !s.is_empty() {
185 s.to_string()
186 } else {
187 quote_dsl_string(s)
188 }
189}
190
191fn quote_run(s: &str) -> String {
192 if s.is_empty() || s.chars().any(|c| c == ';' || c == '\n') || s.contains("//") {
193 return quote_dsl_string(s);
194 }
195 s.split(' ')
196 .map(|w| {
197 if w.starts_with(|c: char| c.is_ascii_digit())
198 || w.starts_with(['/', '.', '-', ':', '='])
199 {
200 quote_dsl_string(w)
201 } else {
202 w.to_string()
203 }
204 })
205 .collect::<Vec<_>>()
206 .join(" ")
207}
208
209fn fmt_exec_arg(arg: &Arg) -> String {
215 match arg {
216 Arg::String(text, _) => quote_dsl_string(text),
217 Arg::Expr(_) => arg.render(),
218 Arg::Parts(_) => {
219 let rendered = arg.render();
220 if rendered.contains(';')
221 || rendered.contains('}')
222 || rendered.contains('\n')
223 || rendered.contains('\r')
224 {
225 quote_dsl_string(&rendered)
226 } else {
227 rendered
228 }
229 }
230 }
231}
232
233fn fmt_raw_arg(arg: &Arg) -> String {
237 match arg {
238 Arg::String(s, true) => quote_dsl_string(s),
239 _ => arg.render(),
240 }
241}
242
243fn fmt_io(b: &IoBinding) -> String {
244 let s = match b.stream {
245 IoStream::Stdin => "stdin",
246 IoStream::Stdout => "stdout",
247 IoStream::Stderr => "stderr",
248 };
249 match &b.pipe {
250 Some(PipeTarget::Var(v)) => format!("{}=${}", s, v),
251 None => s.to_string(),
252 }
253}
254
255pub(crate) fn is_known_command(name: &str) -> bool {
262 if name == "ELSE" {
263 return true;
264 }
265 all_metadata().iter().any(|meta| meta.name == name)
266}
267
268pub(crate) fn invalid_syntax_error(name: &str, raw_args: &[Arg]) -> ParseError {
269 let received = raw_args
270 .iter()
271 .map(Arg::render)
272 .collect::<Vec<_>>()
273 .join(" ");
274 let got = if received.is_empty() {
275 "nothing".to_string()
276 } else {
277 format!("`{received}`")
278 };
279 let found = if received.is_empty() {
280 None
281 } else {
282 Some(received.clone())
283 };
284 let expected = all_metadata()
285 .iter()
286 .find(|meta| meta.name == name)
287 .map(|meta| vec![meta.syntax.to_string()])
288 .unwrap_or_default();
289 let ctx = SpanContext::line_only(0);
290 match structural_hint(name, &received) {
291 Some(hint) => ParseError::invalid_syntax(
292 name,
293 format!("invalid syntax for command {name}: {hint}"),
294 found,
295 expected,
296 Some(hint),
297 &ctx,
298 ),
299 None => ParseError::invalid_syntax(
300 name,
301 format!("invalid syntax for command {name}: got {got}."),
302 found,
303 expected,
304 None,
305 &ctx,
306 ),
307 }
308}
309
310fn unknown_command_error(name: &str, raw_args: &[Arg]) -> ParseError {
311 let received = raw_args
312 .iter()
313 .map(Arg::render)
314 .collect::<Vec<_>>()
315 .join(" ");
316 let hint = structural_hint(name, &received).or_else(|| case_hint(name));
317 let ctx = SpanContext::line_only(0);
318 match hint {
319 Some(hint) => ParseError::unknown_command(
320 name,
321 format!("unknown command: {name}\n{hint}"),
322 Some(hint),
323 &ctx,
324 ),
325 None => ParseError::unknown_command(name, format!("unknown command: {name}"), None, &ctx),
326 }
327}
328
329pub(crate) fn classify(name: &str, raw_args: &[Arg]) -> ParseError {
335 if is_known_command(name) {
336 invalid_syntax_error(name, raw_args)
337 } else {
338 unknown_command_error(name, raw_args)
339 }
340}
341
342fn structural_hint(name: &str, received: &str) -> Option<String> {
343 let got = if received.is_empty() {
344 "nothing".to_string()
345 } else {
346 format!("`{received}`")
347 };
348 match name {
349 "WITH_IO" => Some(with_io_hint(&got, received)),
350 "AWAIT" => Some(format!(
351 "AWAIT waits for a background task variable, e.g. `LET $t: HANDLE = ASYNC ECHO hi` then `AWAIT $t`; got {got}."
352 )),
353 "CANCEL" => Some(format!(
354 "CANCEL stops a background task variable, e.g. `CANCEL $t` (from `LET $t: HANDLE = ASYNC ...`); got {got}."
355 )),
356 "ASYNC" => Some(format!(
357 "ASYNC runs a command in the background, e.g. `ASYNC RUN ...`, `ASYNC {{ ... }}`, or `LET $t: HANDLE = ASYNC ...`; got {got}."
358 )),
359 "FOR" => Some(format!(
360 "FOR loops need `FOR $item: TYPE IN <expr> {{ ... }}` (or `FOR $key: STRING, $value: TYPE IN <expr> {{ ... }}`); got {got}."
361 )),
362 "IF" => Some(format!(
363 "IF needs a condition and a block, e.g. `IF true {{ ECHO yes }}`; got {got}."
364 )),
365 "ELSE" => Some(format!(
366 "ELSE must directly follow an `IF ... {{ ... }}` block, e.g. `IF true {{ ECHO yes }} ELSE {{ ECHO no }}`; got {got}."
367 )),
368 "LET" => Some(format!(
369 "LET assigns a variable, e.g. `LET $name: STRING = <expr>`, `LET $t: HANDLE = ASYNC ...`, `LET $out: STRING = <command>` (capture), `LET $out: STRING = AWAIT $t`, or `LET $var: TYPE = {{ ... }}` (inline block); got {got}."
370 )),
371 "SET" => Some(
372 "`SET` is not a keyword; mutate a declared variable with `$var = <expr>`, e.g. `$count = 2`.".to_string(),
373 ),
374 "TIMEOUT" => Some(format!(
375 "TIMEOUT needs a duration and a command or block, e.g. `TIMEOUT 30s RUN ...`; got {got}."
376 )),
377 "REMOTE" => Some(format!(
378 "REMOTE needs a target and a braced block, e.g. `REMOTE prod [$version, env:DEPLOY_ENV] {{ ... }}`; got {got}."
379 )),
380 "FUNC" => Some(format!(
381 "FUNC defines a function, e.g. `FUNC GREET($name: STRING) {{ RETURN $name }}`; got {got}."
382 )),
383 "RETURN" => Some(format!(
384 "RETURN ends the nearest function, ASYNC task, or inline LET block with a value, e.g. `RETURN $x`; got {got}."
385 )),
386 "WHILE" => Some(format!(
387 "WHILE needs a Bool condition and a block, e.g. `WHILE !$done {{ ... }}`; got {got}."
388 )),
389 "BREAK" => Some(
390 "`BREAK` exits the innermost enclosing FOR/WHILE loop; it must appear inside a loop.".to_string(),
391 ),
392 "CONTINUE" => Some(
393 "`CONTINUE` skips to the next iteration of the innermost enclosing FOR/WHILE loop; it must appear inside a loop.".to_string(),
394 ),
395 "INHERIT_ENV" => Some(format!(
396 "INHERIT_ENV takes a key list, e.g. `INHERIT_ENV [HOME, PATH]`; got {got}."
397 )),
398 name if name == KEYWORD_IMPORT => Some(format!(
399 "IMPORT brings module functions into bare-call scope, e.g. `IMPORT [STD]` or `IMPORT [STD, MOCK]`; got {got}."
400 )),
401 name if name == KEYWORD_EXPORT => Some(
402 "`EXPORT` is reserved for future script-module support and cannot be used yet."
403 .to_string(),
404 ),
405 _ => None,
406 }
407}
408
409fn with_io_hint(got: &str, received: &str) -> String {
412 const SYNTAX: &str =
413 "WITH_IO needs `WITH_IO [bindings] <command>` or `WITH_IO [bindings] { <commands> }`";
414 const BINDINGS: &str = "bindings are `stdin`, `stdout`, `stderr`, or `<stream>=$var` with a PIPE-typed variable (e.g. `[stdout=$p]`, `[stdin=$p]`)";
415 if let Some(after_open) = received.strip_prefix('[') {
416 match after_open.split_once(']') {
417 None => {
418 return format!("{SYNTAX}: missing closing `]` in the binding list; got {got}.");
419 }
420 Some((bindings, _)) => {
421 for part in bindings.split(',') {
422 let part = part.trim();
423 if part.is_empty() {
424 continue;
425 }
426 let (stream, binding) = match part.split_once('=') {
427 Some((stream, binding)) => (stream.trim(), Some(binding.trim())),
428 None => (part, None),
429 };
430 if !matches!(stream, "stdin" | "stdout" | "stderr") {
431 return format!(
432 "{SYNTAX}: invalid stream `{stream}`; expected `stdin`, `stdout`, or `stderr`; got {got}."
433 );
434 }
435 let valid = match binding {
436 None => true,
437 Some(value) => value.strip_prefix('$').is_some_and(|var| {
438 !var.trim().is_empty()
439 && var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
440 }),
441 };
442 if !valid {
443 return format!(
444 "{SYNTAX}: invalid binding `{part}`; {BINDINGS}; got {got}."
445 );
446 }
447 }
448 }
449 }
450 }
451 format!("{SYNTAX}; got {got}. {BINDINGS}.")
452}
453
454fn case_hint(name: &str) -> Option<String> {
456 let upper = name.to_ascii_uppercase();
457 if upper != name
458 && all_metadata()
459 .iter()
460 .any(|meta| meta.name == upper.as_str())
461 {
462 return Some(format!("did you mean `{upper}`? commands are uppercase."));
463 }
464 None
465}
466
467macro_rules! declare_commands {
468 (
469 structural [
470 $( $sname:ident $( { $( $sfname:ident : $sftype:ty ),* $(,)? } )? ),* $(,)?
471 ]
472
473 $(
474 $cmd_ident:ident => [
475 name: $name:expr,
476 variant: $vname:ident $( { $( $vfname:ident : $vftype:ty ),* $(,)? } )? $( ( $( $ttuple:ty ),* $(,)? ) )?,
477 syntax: $syntax:expr,
478 summary: $summary:expr,
479 description: $desc:expr,
480 args: $args:expr,
481 flags: $flags:expr,
482 default_output: $out:expr,
483 examples: $examples:expr,
484 lower: $lower:expr,
485 ]
486 ),* $(,)?
487 ) => {
488 #[derive(Debug, Clone, PartialEq)]
489 pub enum StepKind {
490 $( $vname $( { $( $vfname : $vftype ),* } )? $( ( $( $ttuple ),* ) )?, )*
491 $( $sname $( { $( $sfname : $sftype ),* } )?, )*
492 }
493
494 pub fn lower_command(name: &str, raw_args: Vec<Arg>) -> ParseResult<StepKind> {
495 match name {
496 $(
497 s if s == $name => {
498 let meta = CommandMeta {
499 name: $name, syntax: $syntax, summary: $summary,
500 description: $desc, args: $args, flags: $flags,
501 default_output: $out, examples: $examples,
502 };
503 let (flags, positional) = crate::strip_flags(raw_args, &meta)?;
504 crate::command::validate_positionals_against_meta(
505 s,
506 &meta.args,
507 &positional,
508 )?;
509 let lower_fn: fn(Vec<(String, Arg)>, Vec<Arg>) -> ParseResult<StepKind> = $lower;
510 lower_fn(flags, positional)
511 }
512 )*
513 _ => {
514 Err(classify(name, &raw_args))
515 }
516 }
517 }
518
519 pub fn all_metadata() -> Vec<CommandMeta> {
520 let mut out = vec![
521 $( CommandMeta {
522 name: $name, syntax: $syntax, summary: $summary,
523 description: $desc, args: $args, flags: $flags,
524 default_output: $out, examples: $examples,
525 }, )*
526 ];
527 out.extend(all_structural_metadata());
531 out
532 }
533 };
534}
535
536impl StepKind {
537 pub fn walk_exprs(&self, f: &mut impl FnMut(&Expr)) {
544 fn walk_arg(arg: &Arg, f: &mut impl FnMut(&Expr)) {
545 match arg {
546 Arg::Expr(expr) => f(expr),
547 Arg::Parts(parts) => {
548 for part in parts {
549 if let ArgPart::Expr(expr) = part {
550 f(expr);
551 }
552 }
553 }
554 Arg::String(..) => {}
555 }
556 }
557 fn walk_opt(arg: &Option<Arg>, f: &mut impl FnMut(&Expr)) {
558 if let Some(arg) = arg {
559 walk_arg(arg, f);
560 }
561 }
562 fn walk_target(target: &AssertTarget, f: &mut impl FnMut(&Expr)) {
563 if let AssertTarget::Value(arg) = target {
564 walk_arg(arg, f);
565 }
566 }
567 match self {
568 StepKind::Assign { expr, .. } | StepKind::Set { expr, .. } => f(expr),
569 StepKind::Return { expr } => f(expr),
570 StepKind::Call { args, .. } => {
571 for arg in args {
572 f(arg);
573 }
574 }
575 StepKind::For { in_expr, .. } => f(in_expr),
576 StepKind::If { cond, else_ifs, .. } => {
577 f(cond);
578 for (cond, _) in else_ifs {
579 f(cond);
580 }
581 }
582 StepKind::While { cond, .. } => f(cond),
583 StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
584 walk_arg(duration, f);
585 }
586 StepKind::Workdir(arg)
587 | StepKind::Echo(arg)
588 | StepKind::Run(arg)
589 | StepKind::Mkdir(arg)
590 | StepKind::HashSha256 { path: arg }
591 | StepKind::Exit(arg) => walk_arg(arg, f),
592 StepKind::Env { value, .. } => walk_arg(value, f),
593 StepKind::Copy { from, to, .. }
594 | StepKind::Symlink { from, to, .. }
595 | StepKind::Archive {
596 src: from, dst: to, ..
597 }
598 | StepKind::Install { from, to } => {
599 walk_arg(from, f);
600 walk_arg(to, f);
601 }
602 StepKind::Unarchive {
603 src,
604 dst,
605 max_bytes,
606 } => {
607 walk_arg(src, f);
608 walk_arg(dst, f);
609 walk_opt(max_bytes, f);
610 }
611 StepKind::CopyGit { rev, from, to, .. } => {
612 walk_arg(rev, f);
613 walk_arg(from, f);
614 walk_arg(to, f);
615 }
616 StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
617 StepKind::Remove { path, .. } => walk_arg(path, f),
618 StepKind::Prompt {
619 message, default, ..
620 } => {
621 walk_arg(message, f);
622 walk_opt(default, f);
623 }
624 StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
625 walk_arg(path, f);
626 walk_opt(contents, f);
627 }
628 StepKind::Expand { path, overrides } => {
629 walk_opt(path, f);
630 for (_, value) in overrides {
631 walk_arg(value, f);
632 }
633 }
634 StepKind::AssertEq {
635 actual, expected, ..
636 } => {
637 walk_target(actual, f);
638 walk_opt(expected, f);
639 }
640 StepKind::AssertContains { haystack, needle } => {
641 walk_target(haystack, f);
642 walk_arg(needle, f);
643 }
644 StepKind::ListAppend { item, .. } => walk_arg(item, f),
645 StepKind::RunExec { argv } => {
646 for arg in argv {
647 walk_arg(arg, f);
648 }
649 }
650 StepKind::WithIo { .. }
651 | StepKind::WithIoBlock { .. }
652 | StepKind::TypeAlias { .. }
653 | StepKind::Workspace(_)
654 | StepKind::InheritEnv { .. }
655 | StepKind::Isolated { .. }
656 | StepKind::IsolatedInheritEnv { .. }
657 | StepKind::Cwd
658 | StepKind::ReadLine { .. }
659 | StepKind::AssignCapture { .. }
660 | StepKind::AwaitCapture { .. }
661 | StepKind::AsyncBlock { .. }
662 | StepKind::AssignAsync { .. }
663 | StepKind::Await { .. }
664 | StepKind::Cancel { .. }
665 | StepKind::RemoteBlock { .. }
666 | StepKind::FuncDef { .. }
667 | StepKind::Break
668 | StepKind::Continue => {}
669 }
670 }
671
672 pub fn walk_child_kinds(&self, f: &mut impl FnMut(&StepKind)) {
676 fn walk_body(body: &[Step], f: &mut impl FnMut(&StepKind)) {
677 for step in body {
678 f(&step.kind);
679 }
680 }
681 match self {
682 StepKind::WithIo { cmd, .. } => f(cmd),
683 StepKind::AssignCapture { cmd, .. } => f(cmd),
684 StepKind::For { body, .. }
685 | StepKind::While { body, .. }
686 | StepKind::FuncDef { body, .. }
687 | StepKind::Timeout { body, .. }
688 | StepKind::Isolated { body }
689 | StepKind::AssignAsync { body, .. }
690 | StepKind::AsyncBlock { body }
691 | StepKind::RemoteBlock { body, .. } => walk_body(body, f),
692 StepKind::If {
693 then_body,
694 else_ifs,
695 else_body,
696 ..
697 } => {
698 walk_body(then_body, f);
699 for (_, body) in else_ifs {
700 walk_body(body, f);
701 }
702 if let Some(body) = else_body {
703 walk_body(body, f);
704 }
705 }
706 StepKind::InheritEnv { .. }
707 | StepKind::IsolatedInheritEnv { .. }
708 | StepKind::TypeAlias { .. }
709 | StepKind::Workdir(_)
710 | StepKind::Workspace(_)
711 | StepKind::Env { .. }
712 | StepKind::Echo(_)
713 | StepKind::Run(_)
714 | StepKind::RunExec { .. }
715 | StepKind::Copy { .. }
716 | StepKind::CopyGit { .. }
717 | StepKind::Symlink { .. }
718 | StepKind::Archive { .. }
719 | StepKind::Unarchive { .. }
720 | StepKind::Install { .. }
721 | StepKind::Mkdir(_)
722 | StepKind::Ls(_)
723 | StepKind::Cwd
724 | StepKind::Read(_)
725 | StepKind::ReadLine { .. }
726 | StepKind::Prompt { .. }
727 | StepKind::Write { .. }
728 | StepKind::Append { .. }
729 | StepKind::Remove { .. }
730 | StepKind::Expand { .. }
731 | StepKind::AssertEq { .. }
732 | StepKind::AssertContains { .. }
733 | StepKind::HashSha256 { .. }
734 | StepKind::Exit(_)
735 | StepKind::WithIoBlock { .. }
736 | StepKind::Assign { .. }
737 | StepKind::Set { .. }
738 | StepKind::AwaitCapture { .. }
739 | StepKind::Await { .. }
740 | StepKind::Cancel { .. }
741 | StepKind::Sleep { .. }
742 | StepKind::ListAppend { .. }
743 | StepKind::Call { .. }
744 | StepKind::Return { .. }
745 | StepKind::Break
746 | StepKind::Continue => {}
747 }
748 }
749
750 pub fn walk_step_exprs(&self, f: &mut impl FnMut(&Expr)) {
755 self.walk_exprs(&mut |expr| expr.walk(f));
756 self.walk_child_kinds(&mut |kind| kind.walk_step_exprs(f));
757 }
758}
759
760#[derive(Debug, Clone, PartialEq)]
769pub enum AssertTarget {
770 Value(Arg),
771 Stdout,
772 Stderr,
773}
774
775impl AssertTarget {
776 pub fn render(&self) -> String {
777 match self {
778 AssertTarget::Value(arg) => arg.render(),
779 AssertTarget::Stdout => "stdout".to_string(),
780 AssertTarget::Stderr => "stderr".to_string(),
781 }
782 }
783}
784
785fn lower_assert_target(arg: Arg) -> ParseResult<AssertTarget> {
794 match arg {
795 Arg::Expr(_) => Ok(AssertTarget::Value(arg)),
796 Arg::String(text, quoted) if !quoted => match text.as_str() {
797 "stdout" => Ok(AssertTarget::Stdout),
798 "stderr" => Ok(AssertTarget::Stderr),
799 _ => Ok(AssertTarget::Value(lower_assert_operand(Arg::String(
800 text, false,
801 )))),
802 },
803 other => Ok(AssertTarget::Value(lower_assert_operand(other))),
804 }
805}
806
807fn lower_assert_operand(arg: Arg) -> Arg {
816 match arg {
817 Arg::String(text, false) => {
818 let clean = crate::command::strip_digit_separators(&text);
823 if let Ok(i) = clean.parse::<i64>() {
824 Arg::Expr(Expr::Literal(Value::int(i)))
825 } else if clean.contains('.') && clean.parse::<f64>().is_ok() {
826 Arg::Expr(Expr::Literal(Value::float(
827 clean.parse::<f64>().unwrap_or(f64::NAN),
828 )))
829 } else if text == "true" {
830 Arg::Expr(Expr::Literal(Value::bool(true)))
831 } else if text == "false" {
832 Arg::Expr(Expr::Literal(Value::bool(false)))
833 } else {
834 Arg::String(text, false)
835 }
836 }
837 other => other,
838 }
839}
840
841declare_commands! {
842 structural [
843 WithIo { bindings: Vec<IoBinding>, cmd: Box<StepKind> },
844 WithIoBlock { bindings: Vec<IoBinding> },
845 TypeAlias { name: String, target: String },
846 For { key_var: Option<String>, key_type: Option<String>, var: String, var_type: String, in_expr: Expr, body: Vec<Step> },
847 If { cond: Box<Expr>, then_body: Vec<Step>, else_ifs: Vec<(Box<Expr>, Vec<Step>)>, else_body: Option<Vec<Step>> },
848 Assign { var: String, decl_type: String, expr: Expr },
849 Set { var: String, expr: Expr },
850 AssignCapture { var: String, decl_type: String, cmd: Box<StepKind> },
851 AwaitCapture { out_var: String, out_type: String, task_var: String },
852 AsyncBlock { body: Vec<Step> },
853 AssignAsync { var: String, decl_type: String, body: Vec<Step> },
854 Await { var: String },
855 Cancel { var: String },
856 Timeout { duration: Arg, body: Vec<Step> },
857 Isolated { body: Vec<Step> },
858 IsolatedInheritEnv { keys: Vec<String> },
859 RemoteBlock { target: String, vars: Vec<String>, env: Vec<String>, body: Vec<Step> },
860 RunExec { argv: Vec<Arg> },
861 FuncDef { name: String, params: Vec<(String, String)>, body: Vec<Step> },
862 Call { name: String, args: Vec<Expr> },
863 Return { expr: Box<Expr> },
864 While { cond: Box<Expr>, body: Vec<Step> },
865 Break,
866 Continue,
867 ]
868
869 Workdir => [
870 name: "WORKDIR",
871 variant: Workdir(Arg),
872 syntax: "WORKDIR <path>",
873 summary: "Change the working directory.",
874 description: indoc! {r#"
875 Sets the current working directory.
876
877 Relative paths resolve against the current directory; `/` resets to
878 the workspace root. Paths cannot escape the workspace.
879 "#},
880 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Directory to change to", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
881 flags: &[],
882 default_output: None,
883 examples: &[ Example { name: "change working directory", fence_meta: None, code: indoc! {r#"
884 # Later relative paths resolve under the new directory.
885 WORKDIR project/src
886 WRITE generated.txt generated-under-workdir
887
888 LET $body: STRING = READ generated.txt
889 ASSERT_EQ $body "generated-under-workdir"
890 "#} }, Example { name: "workdir in a scoped block", fence_meta: None, code: indoc! {r#"
891 # The block reverts to the starting directory on exit.
892 LET $outside: STRING = CWD
893 MKDIR project
894
895 [bool:true] {
896 WORKDIR project
897 WRITE inner.txt inner
898 }
899
900 LET $back: STRING = CWD
901 ASSERT_EQ $back $outside
902 LET $body: STRING = READ project/inner.txt
903 ASSERT_EQ $body "inner"
904 "#} } ],
905 lower: |_flags, args| {
906 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKDIR", "WORKDIR requires a path".to_string(), &SpanContext::line_only(0)))?;
907 Ok(StepKind::Workdir(path))
908 },
909 ],
910
911 Workspace => [
912 name: "WORKSPACE",
913 variant: Workspace(WorkspaceTarget),
914 syntax: "WORKSPACE (SNAPSHOT|LOCAL|CACHE|SYSTEM) [--local]",
915 summary: "Switch workspace roots.",
916 description: indoc! {r#"
917 Switches the workspace root. The selection reverts at scope
918 exit like `WORKDIR`.
919
920 - `SNAPSHOT`: the materialized build snapshot (the default).
921 One session-shared directory: every selection resolves to
922 it, in any block.
923 - `LOCAL`: the local workspace directory.
924 - `CACHE`: a persistent per-project directory shared across
925 runs, never evicted. It lives under the OS user cache
926 (`OXDOCK_CACHE_DIR` pins an exact directory);
927 `WORKSPACE CACHE --local` keeps it in
928 `<project>/.cache/workspace` instead.
929 - `SYSTEM`: full filesystem access. Scripts using it are not
930 hermetic.
931 "#},
932 args: &[ ArgSpec { name: "target", arg_type: ArgType::OneOf(&["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM"]), description: "Target root", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
933 flags: &[ FlagSpec { name: "local", long: "--local", value_type: FlagValueType::Flag, required: false, description: "Use the project-local cache directory instead of the OS user cache (CACHE only)" } ],
934 default_output: None,
935 examples: &[ Example { name: "switch roots", fence_meta: None, code: indoc! {r#"
936 IMPORT [STD]
937 WORKSPACE LOCAL
938
939 LET $t: STRING = PATH_TYPE(".")
940 ASSERT_EQ $t "dir"
941 "#} }, Example { name: "workspace cache in a scoped block", fence_meta: None, code: indoc! {r#"
942 [bool:true] {
943 WORKSPACE CACHE
944 WRITE cached.txt cached-content
945 }
946
947 COPY --from-workspace CACHE cached.txt restored.txt
948 LET $body: STRING = READ restored.txt
949 ASSERT_EQ $body "cached-content"
950 "#} } ],
951 lower: |flags, args| {
952 let local = flags.iter().any(|(k, _)| k == "local");
953 let target = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKSPACE", "WORKSPACE requires a target".to_string(), &SpanContext::line_only(0)))?;
954 match target.as_str() {
955 "SNAPSHOT" | "LOCAL" | "SYSTEM" if local => Err(ParseError::validation("WORKSPACE", "WORKSPACE --local requires CACHE".to_string(), &SpanContext::line_only(0))),
956 "SNAPSHOT" => Ok(StepKind::Workspace(WorkspaceTarget::Snapshot)),
957 "LOCAL" => Ok(StepKind::Workspace(WorkspaceTarget::Local)),
958 "CACHE" => Ok(StepKind::Workspace(WorkspaceTarget::Cache { local })),
959 "SYSTEM" => Ok(StepKind::Workspace(WorkspaceTarget::System)),
960 other => Err(ParseError::validation("WORKSPACE", format!("unknown workspace target: {other}"), &SpanContext::line_only(0))),
961 }
962 },
963 ],
964
965 Env => [
966 name: "ENV",
967 variant: Env { key: String, value: Arg },
968 syntax: "ENV KEY=value",
969 summary: "Set an environment variable.",
970 description: indoc! {r#"
971 Inserts or updates an env var.
972
973 The value uses the unified string-value rules shared by every command:
974 `"..."` or `'...'` quotes keep exact bytes (spaces, tabs), a lone `$var`
975 evaluates that variable, `{{ ... }}` placeholders interpolate, unquoted
976 words join with single spaces, and the first `=` splits key from value
977 (`KEY=a=b` stores `a=b`).
978
979 A `$var` inside larger text stays literal — write `{{ $var }}` to
980 interpolate there.
981 "#},
982 args: &[ ArgSpec { name: "assignment", arg_type: ArgType::String, description: "KEY=value pair; the value resolves as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
983 flags: &[],
984 default_output: None,
985 examples: &[
986 Example { name: "set env", fence_meta: None, code: indoc! {r#"
987 ENV APP_MODE=production
988 LET $mode: STRING = env:APP_MODE
989 ASSERT_EQ $mode "production"
990 "#} },
991 Example { name: "quoted value with spaces", fence_meta: None, code: indoc! {r#"
992 # Quotes keep the space: SET_FORTH stores `outer scope`.
993 ENV SET_FORTH="outer scope"
994 WRITE out.txt "{{ env:SET_FORTH }}"
995
996 LET $body: STRING = READ out.txt
997 ASSERT_EQ $body "outer scope"
998 "#} },
999 Example { name: "variable value", fence_meta: None, code: indoc! {r#"
1000 # A lone $var evaluates, like ECHO $var.
1001 LET $who: STRING = "Alice"
1002 ENV GREETING=$who
1003 WRITE out.txt "{{ env:GREETING }}"
1004
1005 LET $body: STRING = READ out.txt
1006 ASSERT_EQ $body "Alice"
1007 "#} },
1008 Example { name: "all value forms agree", fence_meta: None, code: indoc! {r#"
1009 # A bare variable, a quoted literal, and a template all
1010 # store plain strings through the same value rules.
1011 LET $x: STRING = "Ada"
1012 ENV A=$x
1013 ENV B="hello world"
1014 ENV C="{{ $x }} concatenated"
1015 WRITE check.txt "{{ env:A }}|{{ env:B }}|{{ env:C }}"
1016
1017 LET $body: STRING = READ check.txt
1018 ASSERT_EQ $body "Ada|hello world|Ada concatenated"
1019 "#} },
1020 Example { name: "scoped env reverts", fence_meta: None, code: indoc! {r#"
1021 # ENV inside a braced block reverts when the block exits
1022 ENV MODE=production
1023
1024 [bool:true] {
1025 ENV MODE=staging
1026 WRITE inner.txt "{{ env:MODE }}"
1027 }
1028
1029 WRITE outer.txt "{{ env:MODE }}"
1030
1031 LET $inner_body: STRING = READ inner.txt
1032 ASSERT_EQ $inner_body "staging"
1033
1034 LET $outer_body: STRING = READ outer.txt
1035 ASSERT_EQ $outer_body "production"
1036 "#} },
1037 Example { name: "shell reads env per platform", fence_meta: None, code: indoc! {r#"
1038 # A shell command reads its own environment, with
1039 # per-platform spelling: quoted "$VAR" passes the parser
1040 # through untouched on Unix ...
1041 ENV PROXY_PORT=23791
1042
1043 [family:unix] LET $o: STRING = RUN echo serving on "$PROXY_PORT"
1044
1045 # ... while cmd expands %VAR% on Windows.
1046 [family:windows] LET $o: STRING = RUN echo serving on %PROXY_PORT%
1047
1048 ASSERT_CONTAINS $o "23791"
1049 "#} },
1050 ],
1051 lower: |_flags, args| lower_env_assignment(args),
1052 ],
1053
1054 InheritEnv => [
1055 name: "INHERIT_ENV",
1056 variant: InheritEnv { keys: Vec<String> },
1057 syntax: "INHERIT_ENV [<key>, ...]",
1058 summary: "Inherit env vars from host.",
1059 description: indoc! {r#"
1060 Declares which host environment variables to inherit into the script.
1061
1062 Must appear before any other commands. Several directives may
1063 appear so platform-specific names ride explicit guards
1064 (`[family:windows] INHERIT_ENV [USERPROFILE]`); each guarded
1065 line runs only when its guard passes.
1066
1067 Sandbox defaults need no declaration: loader bindings,
1068 terminal defaults, the host lookup path, and the user's
1069 profile locations seed automatically. See Environment
1070 Variable Contracts for the exact list, which grows with the
1071 engine.
1072
1073 Secrets and tool config stay opt-in here: a token or a
1074 `CARGO_HOME` override arrives only through this directive.
1075 "#},
1076 args: &[ ArgSpec { name: "keys", arg_type: ArgType::Rest(&ArgType::String), description: "Host variables to inherit", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1077 flags: &[],
1078 default_output: None,
1079 examples: &[ Example { name: "inherit env", fence_meta: None, code: indoc! {r#"
1080 [family:unix] INHERIT_ENV [HOME]
1081 LET $path: STRING = env:PATH
1082 [family:unix] ASSERT_CONTAINS $path ":"
1083 [family:windows] ASSERT_CONTAINS $path ";"
1084 "#} } ],
1085 lower: |_flags, args| {
1086 let keys = args.into_iter().map(|a| a.as_str().to_string()).collect();
1087 Ok(StepKind::InheritEnv { keys })
1088 },
1089 ],
1090
1091 Echo => [
1092 name: "ECHO",
1093 variant: Echo(Arg),
1094 syntax: "ECHO <message>",
1095 summary: "Print to stdout.",
1096 description: "Outputs message to stdout.",
1097 args: &[ ArgSpec { name: "message", arg_type: ArgType::Rest(&ArgType::String), description: "Text", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1098 flags: &[],
1099 default_output: Some(Stream::Stdout),
1100 examples: &[
1101 Example { name: "echo", fence_meta: None, code: indoc! {r#"
1102 ECHO build-complete
1103 ASSERT_CONTAINS stdout "build-complete"
1104 "#} },
1105 Example { name: "variables", fence_meta: None, code: indoc! {r#"
1106 # {{ }} interpolates inside text; a lone $var evaluates on its own.
1107 LET $x: STRING = "World"
1108 ECHO "braced:{{ $x }}"
1109 ECHO $x
1110 ASSERT_EQ stdout "braced:World\nWorld\n"
1111 "#} },
1112 Example { name: "interpolation", fence_meta: None, code: indoc! {r#"
1113 # `{{ env:KEY }}` reads the script environment; a bare name
1114 # resolves a DSL variable instead. Unknown keys expand to
1115 # empty with no host fallback.
1116 ENV USER=OxDock
1117 LET $WHO: STRING = "Ada"
1118 ECHO "Hello {{ env:USER }}! Hi {{ WHO }}!{{ env:OXDOCK_DOC_NO_SUCH_KEY }}"
1119 ASSERT_CONTAINS stdout "Hello OxDock! Hi Ada!"
1120 "#} },
1121 ],
1122 lower: |_flags, args| Ok(StepKind::Echo(join_value(args, "ECHO")?)),
1123 ],
1124
1125 Run => [
1126 name: "RUN",
1127 variant: Run(Arg),
1128 syntax: "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
1129 summary: "Execute shell command or direct executable.",
1130 description: indoc! {r#"
1131 Shell form (`RUN <command...>`) runs the joined command string in the
1132 batch shell (`sh -c` / `cmd /C`). Never the operator's login
1133 shell: login shells re-pollute scrubbed children from system
1134 profiles and break script portability, so step execution is
1135 pinned to POSIX `sh` (interactive `oxdock --shell` still uses
1136 `$SHELL`).
1137
1138 Exec form (`RUN ["exe", "arg", ...]`) spawns the executable directly
1139 with no shell, so there is no shell expansion, globbing, redirection,
1140 or pipes; use it for portable commands.
1141
1142 Guards and wrappers (`ASYNC`, `TIMEOUT`, `WITH_IO`, `LET`) apply to
1143 both forms.
1144 "#},
1145 args: &[ ArgSpec { name: "command", arg_type: ArgType::Rest(&ArgType::String), description: "Command", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1146 flags: &[],
1147 default_output: None,
1148 examples: &[ Example { name: "run", fence_meta: None, code: indoc! {r#"
1149 # Spawned children resolve through the seeded host PATH:
1150 # closed child env is the default, not ambient inherit.
1151 RUN echo hello
1152
1153 # Captured runs prove the output, not just the exit status.
1154 LET $o: STRING = RUN echo hello
1155 ASSERT_CONTAINS $o "hello"
1156 "#} }, Example { name: "run exec form", fence_meta: None, code: indoc! {r#"
1157 # No shell: `>` stays a literal argument, so no file is created.
1158 # Toolchain spawns bridge the host home explicitly: rustup
1159 # shims resolve toolchains through the host home.
1160 IMPORT [STD]
1161 [family:unix] INHERIT_ENV [HOME]
1162 [family:windows] INHERIT_ENV [USERPROFILE]
1163 RUN ["cargo", "--version", ">", "x.txt"]
1164 ASSERT_CONTAINS stdout "cargo"
1165
1166 LET $t: STRING = PATH_TYPE("x.txt")
1167 ASSERT_EQ $t "absent"
1168 "#} } ],
1169 lower: |_flags, args| match args.as_slice() {
1170 [Arg::Expr(Expr::List(elems))] if elems.is_empty() => {
1171 Err(ParseError::validation("RUN", "RUN requires at least one argument".to_string(), &SpanContext::line_only(0)))
1172 }
1173 [Arg::Expr(Expr::List(elems))] => Ok(StepKind::RunExec {
1174 argv: elems.iter().cloned().map(Arg::Expr).collect(),
1175 }),
1176 _ => Ok(StepKind::Run(join_value(args, "RUN")?)),
1177 },
1178 ],
1179
1180 Copy => [
1181 name: "COPY",
1182 variant: Copy { from_workspace: Option<WorkspaceTarget>, from_host: bool, to_host: bool, from: Arg, to: Arg },
1183 syntax: "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] [--from-host | --to-host] <from> <to>",
1184 summary: "Copy file into workspace.",
1185 description: "Copies from host (the source is never moved or modified). Docker destination semantics: a file copied onto a directory (an existing one, or a trailing-slash spell like `out/`) is duplicated inside it under its own basename; a directory source duplicates its contents into the destination; any other destination path is created holding the copied bytes.",
1186 args: &[
1187 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1188 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1189 ],
1190 flags: &[ FlagSpec { name: "from_workspace", long: "--from-workspace", value_type: FlagValueType::String, required: false, description: "Copy from the given workspace root instead of the build context" }, FlagSpec { name: "from_host", long: "--from-host", value_type: FlagValueType::Flag, required: false, description: "Fetch from the host workspace into the guest (REMOTE bodies only)" }, FlagSpec { name: "to_host", long: "--to-host", value_type: FlagValueType::Flag, required: false, description: "Push from the guest workspace back to the host (REMOTE bodies only)" } ],
1191 default_output: None,
1192 examples: &[ Example { name: "copy", fence_meta: Some("roots:unified"), code: indoc! {r#"
1193 # Copy to a new name, then read back.
1194 WRITE src.txt content
1195 COPY src.txt dst.txt
1196
1197 LET $body: STRING = READ dst.txt
1198 ASSERT_EQ $body "content"
1199 "#} }, Example { name: "copy from workspace", fence_meta: None, code: indoc! {r#"
1200 # Same name, different contents per root: only LOCAL has ws-content.
1201 WRITE shared.txt from-snapshot
1202 WORKSPACE LOCAL
1203 WRITE shared.txt ws-content
1204
1205 WORKSPACE SNAPSHOT
1206 COPY --from-workspace LOCAL shared.txt ws-copy.txt
1207
1208 LET $body: STRING = READ ws-copy.txt
1209 ASSERT_EQ $body "ws-content"
1210 "#} } ],
1211 lower: |flags, args| {
1212 let from_workspace = flags
1213 .iter()
1214 .find(|(k, _)| k == "from_workspace")
1215 .map(|(_, v)| match v.as_str() {
1216 "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1217 "LOCAL" => Ok(WorkspaceTarget::Local),
1218 "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1219 "SYSTEM" => Ok(WorkspaceTarget::System),
1220 other => Err(ParseError::validation("COPY", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1221 })
1222 .transpose()?;
1223 let mut it = args.into_iter();
1224 let from = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a source".to_string(), &SpanContext::line_only(0)))?;
1225 let to = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a destination".to_string(), &SpanContext::line_only(0)))?;
1226 let from_host = flags.iter().any(|(k, _)| k == "from_host");
1227 let to_host = flags.iter().any(|(k, _)| k == "to_host");
1228 if from_host && to_host {
1229 return Err(ParseError::validation("COPY", "COPY --from-host and --to-host are mutually exclusive".to_string(), &SpanContext::line_only(0)));
1230 }
1231 Ok(StepKind::Copy { from_workspace, from_host, to_host, from, to })
1232 },
1233 ],
1234
1235 CopyGit => [
1236 name: "COPY_GIT",
1237 variant: CopyGit { rev: Arg, from: Arg, to: Arg, include_dirty: bool },
1238 syntax: "COPY_GIT [--include-dirty] <rev> <src> <dst>",
1239 summary: "Copy from git revision.",
1240 description: "Checkout and copy.",
1241 args: &[
1242 ArgSpec { name: "rev", arg_type: ArgType::String, description: "Rev", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1243 ArgSpec { name: "src", arg_type: ArgType::Path, description: "Src", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1244 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Dst", io: IoDirection::Write, index: 2, required: true, fallback_stream: None },
1245 ],
1246 flags: &[ FlagSpec { name: "dirty", long: "--include-dirty", value_type: FlagValueType::Flag, required: false, description: "Include dirty" } ],
1247 default_output: None,
1248 examples: &[ Example { name: "git copy missing source errors", fence_meta: Some("expect_error:\"COPY source missing\""), code: indoc! {r#"COPY_GIT HEAD src.txt dst.txt"#} } ],
1249 lower: |flags, args| {
1250 let include_dirty = flags.iter().any(|(k, _)| k == "dirty");
1251 let mut it = args.into_iter();
1252 let rev = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a revision".to_string(), &SpanContext::line_only(0)))?;
1253 let from = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a source".to_string(), &SpanContext::line_only(0)))?;
1254 let to = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a destination".to_string(), &SpanContext::line_only(0)))?;
1255 Ok(StepKind::CopyGit { rev, from, to, include_dirty })
1256 },
1257 ],
1258
1259 Symlink => [
1260 name: "SYMLINK",
1261 variant: Symlink { from_workspace: Option<WorkspaceTarget>, from: Arg, to: Arg },
1262 syntax: "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
1263 summary: "Create symlink.",
1264 description: "Creates symlink. A directory destination (existing, or a trailing-slash spell) receives the link under the source basename.",
1265 args: &[
1266 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Target", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1267 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Link", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1268 ],
1269 flags: &[ FlagSpec { name: "from_workspace", long: "--from-workspace", value_type: FlagValueType::String, required: false, description: "Symlink from the given workspace root instead of the build context" } ],
1270 default_output: None,
1271 examples: &[ Example { name: "symlink", fence_meta: Some("roots:unified"), code: indoc! {r#"
1272 # A symlink reads like its target.
1273 WRITE original.txt content
1274 SYMLINK original.txt link.txt
1275
1276 LET $body: STRING = READ link.txt
1277 ASSERT_EQ $body "content"
1278 "#} }, Example { name: "symlink from workspace", fence_meta: None, code: indoc! {r#"
1279 # Same name, different contents per root: only LOCAL has ws-content.
1280 WRITE shared.txt from-snapshot
1281 WORKSPACE LOCAL
1282 WRITE shared.txt ws-content
1283
1284 WORKSPACE SNAPSHOT
1285 SYMLINK --from-workspace LOCAL shared.txt ws-link.txt
1286
1287 LET $body: STRING = READ ws-link.txt
1288 ASSERT_EQ $body "ws-content"
1289 "#} } ],
1290 lower: |flags, args| {
1291 let from_workspace = flags
1292 .iter()
1293 .find(|(k, _)| k == "from_workspace")
1294 .map(|(_, v)| match v.as_str() {
1295 "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1296 "LOCAL" => Ok(WorkspaceTarget::Local),
1297 "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1298 "SYSTEM" => Ok(WorkspaceTarget::System),
1299 other => Err(ParseError::validation("SYMLINK", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1300 })
1301 .transpose()?;
1302 let mut it = args.into_iter();
1303 let from = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a source".to_string(), &SpanContext::line_only(0)))?;
1304 let to = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a target".to_string(), &SpanContext::line_only(0)))?;
1305 Ok(StepKind::Symlink { from_workspace, from, to })
1306 },
1307 ],
1308
1309 Mkdir => [
1310 name: "MKDIR",
1311 variant: Mkdir(Arg),
1312 syntax: "MKDIR <path>",
1313 summary: "Create directory.",
1314 description: "Creates dir with parents.",
1315 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir path", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1316 flags: &[],
1317 default_output: None,
1318 examples: &[ Example { name: "mkdir", fence_meta: None, code: indoc! {r#"
1319 IMPORT [STD]
1320 MKDIR deeply/nested/tree
1321
1322 LET $t: STRING = PATH_TYPE("deeply/nested/tree")
1323 ASSERT_EQ $t "dir"
1324 "#} } ],
1325 lower: |_flags, args| Ok(StepKind::Mkdir(args.into_iter().next().ok_or_else(|| ParseError::validation("MKDIR", "MKDIR requires a path".to_string(), &SpanContext::line_only(0)))?)),
1326 ],
1327
1328 Install => [
1329 name: "INSTALL",
1330 variant: Install { from: Arg, to: Arg },
1331 syntax: "INSTALL <source> <dest>",
1332 summary: "Atomically install a verified binary as executable.",
1333 description: "Stages the source as a temp file in the dest dir, sets executable mode, then renames into place.",
1334 args: &[
1335 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source file", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1336 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest file", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1337 ],
1338 flags: &[],
1339 default_output: None,
1340 examples: &[ Example { name: "install", fence_meta: Some("roots:unified"), code: indoc! {r#"
1341 # Place a verified binary with executable mode.
1342 IMPORT [STD]
1343 WRITE src.bin payload
1344 INSTALL src.bin dst-bin/tool
1345
1346 LET $t: STRING = PATH_TYPE("dst-bin/tool")
1347 ASSERT_EQ $t "file"
1348 "#} } ],
1349 lower: |_flags, args| {
1350 let mut it = args.into_iter();
1351 let from = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a source".to_string(), &SpanContext::line_only(0)))?;
1352 let to = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a destination".to_string(), &SpanContext::line_only(0)))?;
1353 Ok(StepKind::Install { from, to })
1354 },
1355 ],
1356
1357 Archive => [
1358 name: "ARCHIVE",
1359 variant: Archive { src: Arg, dst: Arg, raw: bool },
1360 syntax: "ARCHIVE [--raw] <src> <dst>",
1361 summary: "Pack a file or directory into a tarball.",
1362 description: indoc! {r#"
1363 Packs a file or directory into a tarball, gzip-compressed by
1364 default (`--raw` writes an uncompressed tar instead).
1365
1366 A lone file packs as a single top-level entry under its
1367 basename; a directory recurses, preserving empty dirs. Source
1368 modes ride in the headers on Unix, so system `tar` restores
1369 them elsewhere. Symlink sources refuse: archives cross trust
1370 boundaries, so links never resolve into member bytes. Hashing
1371 stays with `HASH_SHA256`, which reads the finished archive
1372 like any other file.
1373 "#},
1374 args: &[
1375 ArgSpec { name: "src", arg_type: ArgType::Path, description: "File or directory to pack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1376 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Archive file to write", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1377 ],
1378 flags: &[ FlagSpec { name: "raw", long: "--raw", value_type: FlagValueType::Flag, required: false, description: "Write an uncompressed tar instead of gzip" } ],
1379 default_output: None,
1380 examples: &[ Example { name: "archive directory", fence_meta: None, code: indoc! {r#"
1381 # Stage a small tree to pack.
1382 WRITE bundle/app.txt bundled-payload
1383 WRITE bundle/nested/deep.txt deep-payload
1384
1385 # ARCHIVE packs it gzip-compressed by default.
1386 ARCHIVE bundle bundle.tar.gz
1387
1388 # UNARCHIVE restores the tree under the destination.
1389 UNARCHIVE bundle.tar.gz restored
1390
1391 # The payloads arrive byte-identical.
1392 LET $body: STRING = READ restored/app.txt
1393 ASSERT_EQ $body "bundled-payload"
1394
1395 LET $deep: STRING = READ restored/nested/deep.txt
1396 ASSERT_EQ $deep "deep-payload"
1397 "#} }, Example { name: "archive raw", fence_meta: None, code: indoc! {r#"
1398 # A lone file packs as a single top-level entry.
1399 WRITE tool.bin tool-payload
1400
1401 # Raw archives skip gzip and stay readable by any tar.
1402 ARCHIVE --raw tool.bin tool.tar
1403 UNARCHIVE tool.tar tool-out
1404
1405 # The entry lands under its basename.
1406 LET $body: STRING = READ tool-out/tool.bin
1407 ASSERT_EQ $body "tool-payload"
1408 "#} } ],
1409 lower: |flags, args| {
1410 let raw = flags.iter().any(|(k, _)| k == "raw");
1411 let mut it = args.into_iter();
1412 let src = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a source".to_string(), &SpanContext::line_only(0)))?;
1413 let dst = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1414 Ok(StepKind::Archive { src, dst, raw })
1415 },
1416 ],
1417
1418 Unarchive => [
1419 name: "UNARCHIVE",
1420 variant: Unarchive { src: Arg, dst: Arg, max_bytes: Option<Arg> },
1421 syntax: "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
1422 summary: "Unpack a tarball into a directory.",
1423 description: indoc! {r#"
1424 Unpacks a tarball under the destination directory, creating
1425 it first. Gzip and raw (`ARCHIVE --raw`) tarballs
1426 self-identify by magic bytes, so no flag is needed.
1427
1428 Member bytes meter against a 1 GiB default expansion cap
1429 across the whole archive: a decompression bomb trips it
1430 instead of filling the disk, and `--max-bytes` moves the
1431 ceiling either way (plain integer bytes). The tripped member
1432 stays truncated on disk while the step fails loudly.
1433
1434 Symlink and special members refuse naming the entry, and
1435 absolute or escaping paths fail closed before any byte
1436 lands: the member sanitizer plus the destination join check
1437 form two independent walls. Unix modes recorded in the
1438 headers restore on unpack; other platforms land default
1439 modes (confer executability with `INSTALL` there).
1440 "#},
1441 args: &[
1442 ArgSpec { name: "src", arg_type: ArgType::Path, description: "Archive file to unpack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1443 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Directory to unpack under", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1444 ],
1445 flags: &[ FlagSpec { name: "max_bytes", long: "--max-bytes", value_type: FlagValueType::String, required: false, description: "Cap total unpacked member bytes: bare digits are bytes (`1_000_000` grouping allowed), suffixes B/KB/MB/GB/TB (decimal) and KIB/MIB/GIB/TIB (binary), any case, one optional space before the unit (defaults to 1 GiB)" } ],
1446 default_output: None,
1447 examples: &[ Example { name: "unarchive", fence_meta: None, code: indoc! {r#"
1448 # Pack a note, then restore it under a fresh destination.
1449 WRITE pack/note.txt packed-note
1450 ARCHIVE pack pack.tar.gz
1451 UNARCHIVE pack.tar.gz unpacked
1452
1453 LET $body: STRING = READ unpacked/note.txt
1454 ASSERT_EQ $body "packed-note"
1455 "#} }, Example { name: "unarchive with a lower cap", fence_meta: None, code: indoc! {r#"
1456 # Small payloads clear even a tight ceiling.
1457 WRITE pack/note.txt packed-note
1458 ARCHIVE pack pack.tar.gz
1459 UNARCHIVE pack.tar.gz capped --max-bytes 100KB
1460
1461 LET $body: STRING = READ capped/note.txt
1462 ASSERT_EQ $body "packed-note"
1463 "#} } ],
1464 lower: |flags, args| {
1465 let mut it = args.into_iter();
1466 let src = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires an archive".to_string(), &SpanContext::line_only(0)))?;
1467 let dst = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1468 let max_bytes = flags
1469 .into_iter()
1470 .find_map(|(k, v)| (k == "max_bytes").then_some(v));
1471 if let Some(Arg::String(text, _)) = max_bytes.as_ref()
1475 && !text.contains("{{")
1476 && let Err(e) = crate::command::parse_byte_count(text)
1477 {
1478 return Err(ParseError::validation(
1479 "UNARCHIVE",
1480 format!("UNARCHIVE --max-bytes {e:#}"),
1481 &SpanContext::line_only(0),
1482 ));
1483 }
1484 Ok(StepKind::Unarchive { src, dst, max_bytes })
1485 },
1486 ],
1487
1488 Ls => [
1489 name: "LS",
1490 variant: Ls(Option<Arg>),
1491 syntax: "LS [<path>]",
1492 summary: "List directory.",
1493 description: "Lists entries.",
1494 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1495 flags: &[],
1496 default_output: Some(Stream::Stdout),
1497 examples: &[ Example { name: "ls", fence_meta: None, code: indoc! {r#"
1498 MKDIR inventory
1499 WRITE inventory/a.txt a
1500 LS inventory
1501 ASSERT_CONTAINS stdout "a.txt"
1502 "#} } ],
1503 lower: |_flags, args| Ok(StepKind::Ls(args.into_iter().next())),
1504 ],
1505
1506 Cwd => [
1507 name: "CWD",
1508 variant: Cwd,
1509 syntax: "CWD",
1510 summary: "Print working directory.",
1511 description: "Outputs cwd.",
1512 args: &[],
1513 flags: &[],
1514 default_output: Some(Stream::Stdout),
1515 examples: &[ Example { name: "cwd", fence_meta: None, code: indoc! {r#"
1516 CWD
1517
1518 # CWD tracks WORKDIR: the listing names the new directory.
1519 MKDIR sub
1520 WORKDIR sub
1521 LET $c: STRING = CWD
1522 ASSERT_CONTAINS $c "sub"
1523 "#} } ],
1524 lower: |_flags, _args| Ok(StepKind::Cwd),
1525 ],
1526
1527 Read => [
1528 name: "READ",
1529 variant: Read(Option<Arg>),
1530 syntax: "READ [<path>]",
1531 summary: "Read file to stdout.",
1532 description: "Outputs file contents.",
1533 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1534 flags: &[],
1535 default_output: Some(Stream::Stdout),
1536 examples: &[ Example { name: "read", fence_meta: None, code: indoc! {r#"
1537 WRITE note.txt "hello"
1538 READ note.txt
1539
1540 LET $body: STRING = READ note.txt
1541 ASSERT_EQ $body "hello"
1542 "#} } ],
1543 lower: |_flags, args| Ok(StepKind::Read(args.into_iter().next())),
1544 ],
1545
1546 ReadLine => [
1547 name: "READ_LINE",
1548 variant: ReadLine { var: String },
1549 syntax: "READ_LINE $var",
1550 summary: "Read one line from stdin into a variable.",
1551 description: indoc! {r#"
1552 Reads bytes until newline without waiting for EOF, leaving the pipe open.
1553
1554 Trailing newline is stripped (shell-read parity). On premature EOF
1555 assigns accumulated bytes and returns.
1556 "#},
1557 args: &[ ArgSpec { name: "var", arg_type: ArgType::String, description: "Target variable (`$name`); the line binds as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1558 flags: &[],
1559 default_output: None,
1560 examples: &[ Example { name: "read line", fence_meta: None, code: indoc! {r#"
1561 # The trailing newline is stripped: the variable holds exactly `first`.
1562 LET $lines: PIPE
1563 WITH_IO [stdout=$lines] ECHO "first"
1564 WITH_IO [stdin=$lines] READ_LINE $reply
1565 ASSERT_EQ $reply "first"
1566 "#} } ],
1567 lower: |_flags, args| {
1568 let arg = args.into_iter().next().ok_or_else(|| ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))?;
1569 let var = match arg {
1570 Arg::Expr(Expr::Var(name)) => name,
1571 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1574 other => return Err(ParseError::validation("READ_LINE", format!("READ_LINE requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1575 };
1576 if var.is_empty() {
1577 return Err(ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))
1578 }
1579 Ok(StepKind::ReadLine { var })
1580 },
1581 ],
1582
1583 Prompt => [
1584 name: "PROMPT",
1585 variant: Prompt { var: String, message: Arg, default: Option<Arg> },
1586 syntax: "PROMPT $var <message> [<default>]",
1587 summary: "Prompt on the terminal into a variable.",
1588 description: indoc! {r#"
1589 Prints `{message} [{default}]: ` (or `{message}: ` with no
1590 default) to stderr and reads one line from the terminal.
1591
1592 Empty input yields the default when one is given, else an
1593 empty string. EOF aborts loudly. Non-TTY stdin never reads:
1594 a default binds with a stderr note, while no default bails.
1595 "#},
1596 args: &[
1597 ArgSpec { name: "var", arg_type: ArgType::String, description: "Target variable (`$name`); the answer binds as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1598 ArgSpec { name: "message", arg_type: ArgType::String, description: "Prompt message", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1599 ArgSpec { name: "default", arg_type: ArgType::String, description: "Default on empty input", io: IoDirection::Read, index: 2, required: false, fallback_stream: None },
1600 ],
1601 flags: &[],
1602 default_output: None,
1603 examples: &[ Example { name: "prompt needs a terminal", fence_meta: Some("expect_error:\"non-TTY\""), code: indoc! {r#"
1604 # Headless runs have no terminal: without a default the
1605 # prompt fails instead of hanging or reading piped stdin.
1606 PROMPT $dir "Install destination?"
1607 "#} } ],
1608 lower: |_flags, args| {
1609 let mut it = args.into_iter();
1610 let var_arg = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))?;
1611 let var = match var_arg {
1612 Arg::Expr(Expr::Var(name)) => name,
1613 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1614 other => return Err(ParseError::validation("PROMPT", format!("PROMPT requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1615 };
1616 if var.is_empty() {
1617 return Err(ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))
1618 }
1619 let message = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a message".to_string(), &SpanContext::line_only(0)))?;
1620 let default = it.next();
1621 Ok(StepKind::Prompt { var, message, default })
1622 },
1623 ],
1624
1625 Write => [
1626 name: "WRITE",
1627 variant: Write { path: Arg, contents: Option<Arg> },
1628 syntax: "WRITE <path> [<contents>]",
1629 summary: "Write to file.",
1630 description: "Writes contents.",
1631 args: &[
1632 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1633 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1634 ],
1635 flags: &[],
1636 default_output: None,
1637 examples: &[ Example { name: "write", fence_meta: None, code: indoc! {r#"
1638 WRITE output.txt hello-world
1639 LET $body: STRING = READ output.txt
1640 ASSERT_EQ $body "hello-world"
1641 "#} } ],
1642 lower: |_flags, args| {
1643 let mut it = args.into_iter();
1644 let path = it.next().ok_or_else(|| ParseError::validation("WRITE", "WRITE requires a path".to_string(), &SpanContext::line_only(0)))?;
1645 let remaining: Vec<Arg> = it.collect();
1646 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "WRITE")?) };
1647 Ok(StepKind::Write { path, contents })
1648 },
1649 ],
1650
1651 Append => [
1652 name: "APPEND",
1653 variant: Append { path: Arg, contents: Option<Arg> },
1654 syntax: "APPEND <path> [<contents>]",
1655 summary: "Append to file.",
1656 description: "Appends contents.",
1657 args: &[
1658 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1659 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1660 ],
1661 flags: &[],
1662 default_output: None,
1663 examples: &[ Example { name: "append", fence_meta: None, code: indoc! {r#"
1664 WRITE log.txt line1
1665 APPEND log.txt line2
1666
1667 # APPEND concatenates with no separator.
1668 LET $all: STRING = READ log.txt
1669 ASSERT_EQ $all "line1line2"
1670 "#} } ],
1671 lower: |_flags, args| {
1672 let mut it = args.into_iter();
1673 let path = it.next().ok_or_else(|| ParseError::validation("APPEND", "APPEND requires a path".to_string(), &SpanContext::line_only(0)))?;
1674 let remaining: Vec<Arg> = it.collect();
1675 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "APPEND")?) };
1676 Ok(StepKind::Append { path, contents })
1677 },
1678 ],
1679
1680 Remove => [
1681 name: "REMOVE",
1682 variant: Remove { path: Arg, recursive: bool },
1683 syntax: "REMOVE [--recursive] <path>",
1684 summary: "Remove a file, symlink, or directory.",
1685 description: "Removes a file, symlink (the link itself), or empty dir. With --recursive removes a directory tree.",
1686 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Path to remove", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1687 flags: &[ FlagSpec { name: "recursive", long: "--recursive", value_type: FlagValueType::Flag, required: false, description: "Remove a directory tree" } ],
1688 default_output: None,
1689 examples: &[ Example { name: "remove", fence_meta: None, code: indoc! {r#"
1690 # WRITE then REMOVE leaves nothing behind.
1691 IMPORT [STD]
1692 WRITE scratch.txt content
1693
1694 # Assert original file is written
1695 LET $o: STRING = PATH_TYPE("scratch.txt")
1696 ASSERT_EQ $o "file"
1697
1698 REMOVE scratch.txt
1699
1700 # Assert file has been removed
1701 LET $t: STRING = PATH_TYPE("scratch.txt")
1702 ASSERT_EQ $t "absent"
1703 "#} } ],
1704 lower: |flags, args| {
1705 let recursive = flags.iter().any(|(k, _)| k == "recursive");
1706 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("REMOVE", "REMOVE requires a path".to_string(), &SpanContext::line_only(0)))?;
1707 Ok(StepKind::Remove { path, recursive })
1708 },
1709 ],
1710
1711 Expand => [
1712 name: "EXPAND",
1713 variant: Expand { path: Option<Arg>, overrides: Vec<(String, Arg)> },
1714 syntax: "EXPAND [<path>] [<KEY=val> ...]",
1715 summary: "Expand a template file (or stdin) to stdout.",
1716 description: indoc! {r#"
1717 A template is any text file — or piped stdin when no path is given —
1718 containing `{{ ... }}` placeholders. EXPAND replaces each placeholder
1719 and prints the result to stdout.
1720
1721 Placeholders: `{{ NAME }}` reads a `KEY=val` override passed on this
1722 command; `{{ env:NAME }}` reads an override, falling back to the
1723 environment; `{{ $var }}` reads a script variable (dotted paths allowed).
1724 A missing key is an error, never a silent empty.
1725
1726 Calls: `{{ MODULE::FUNC(args) }}` invokes a pure registry function
1727 with `$var.path` references and `STRING`, `INT`, `FLOAT`, and `BOOL`
1728 literals as arguments. Only pure functions resolve here: stateful,
1729 script-defined, and pipe-backed entries fail naming themselves,
1730 since placeholder evaluation carries no step context. The same
1731 calls resolve in ordinary strings, so both paths agree.
1732
1733 Substitution runs in a single pass. `EXPAND` is not recursive and does not
1734 expand nested placeholders: a value that itself contains `{{ ... }}` is
1735 inserted verbatim and never expanded again.
1736
1737 A bare `$var` argument is a template path; `KEY=val` arguments are
1738 overrides whose values follow the unified string-value rules (same as
1739 `ENV`: quotes keep exact bytes, a lone `$var` evaluates,
1740 `{{ ... }}` interpolates).
1741
1742 NOTE: `WRITE` interpolates `{{ ... }}` while writing, so escape it
1743 (`\{{ ... }}`) when writing a template file for a later `EXPAND`.
1744
1745 With no path, the template arrives on stdin through a pipe. When piping
1746 from a shell, single-quote the template (`echo '{{ $x }}'`): double
1747 quotes let the shell swallow `$x`, so oxdock receives an empty `{{ }}`
1748 placeholder and errors.
1749 "#},
1750 args: &[
1751 ArgSpec { name: "path", arg_type: ArgType::Path, description: "Template file to expand; omit to expand stdin", io: IoDirection::Read, index: 0, required: false, fallback_stream: None },
1752 ArgSpec { name: "overrides", arg_type: ArgType::Rest(&ArgType::String), description: "Template overrides shadowing that key (unified string values)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
1753 ],
1754 flags: &[],
1755 default_output: Some(Stream::Stdout),
1756 examples: &[
1757 Example { name: "expand", fence_meta: None, code: indoc! {r#"
1758 # Placeholders read overrides first, then the environment.
1759 ENV NAME="Alice"
1760 WRITE template.md "Hello {{ env:NAME }}!"
1761 EXPAND template.md
1762
1763 ASSERT_CONTAINS stdout "Hello Alice!"
1764 "#} },
1765 Example { name: "override with spaces", fence_meta: None, code: indoc! {r#"
1766 # WRITE would interpolate {{ }} right away, so escape it.
1767 # The file must literally contain {{ env:NAME }} for EXPAND.
1768 WRITE template.md "Hello \{{ env:NAME }}!"
1769 EXPAND template.md NAME="Alice Smith"
1770
1771 ASSERT_CONTAINS stdout "Hello Alice Smith!"
1772 "#} },
1773 Example { name: "variable override", fence_meta: None, code: indoc! {r#"
1774 # Same escaping: keep the placeholder literal until EXPAND.
1775 # A lone $who evaluates, like ECHO $who.
1776 LET $who: STRING = "Bob"
1777 WRITE template.md "Hi \{{ env:WHO }}!"
1778 EXPAND template.md WHO=$who
1779
1780 ASSERT_CONTAINS stdout "Hi Bob!"
1781 "#} },
1782 Example { name: "override forms agree", fence_meta: None, code: indoc! {r#"
1783 # A bare variable and a template-with-tail expand identically.
1784 LET $x: STRING = "Ada"
1785 WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
1786 EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"
1787
1788 ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"
1789 "#} },
1790 Example { name: "expand stdin", fence_meta: None, code: indoc! {r#"
1791 # No path: the template arrives on stdin through a pipe.
1792 LET $tpl: PIPE
1793 WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
1794 WITH_IO [stdin=$tpl] EXPAND NAME=Alice
1795
1796 ASSERT_CONTAINS stdout "Hello Alice!"
1797 "#} },
1798 Example { name: "override does not leak", fence_meta: None, code: indoc! {r#"
1799 # KEY=val overrides shadow env for that EXPAND only.
1800 # They never update the environment itself.
1801 ENV NAME="Alice"
1802 WRITE template.md "Hi \{{ env:NAME }}!"
1803
1804 EXPAND template.md NAME="Bob"
1805 ASSERT_CONTAINS stdout "Hi Bob!"
1806
1807 EXPAND template.md
1808 ASSERT_CONTAINS stdout "Hi Alice!"
1809 "#} },
1810 Example { name: "function call", fence_meta: None, code: indoc! {r#"
1811 # Pure registry functions run inside placeholders.
1812 # WRITE would interpolate {{ }} right away, so escape it.
1813 IMPORT [STD]
1814 WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"
1815
1816 EXPAND template.md
1817 ASSERT_CONTAINS stdout "Count: 2!"
1818 "#} },
1819 ],
1820 lower: |_flags, args| {
1821 let mut path = None;
1822 let mut overrides = Vec::new();
1823 for arg in args {
1824 let text = arg.as_str();
1825 if let Some((key, value)) = split_assignment(text).map_err(|e| ParseError::validation("EXPAND", e.to_string(), &SpanContext::line_only(0)))? {
1826 overrides.push((key, value));
1827 } else if path.is_none() { path = Some(arg); }
1828 else { return Err(ParseError::validation("EXPAND", "EXPAND accepts at most one path".to_string(), &SpanContext::line_only(0))) }
1829 }
1830 Ok(StepKind::Expand { path, overrides })
1831 },
1832 ],
1833
1834 AssertEq => [
1835 name: "ASSERT_EQ",
1836 variant: AssertEq { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
1837 syntax: "ASSERT_EQ <actual> <expected> | ASSERT_EQ --hash <sha256> <actual>",
1838 summary: "Assert strict equality.",
1839 description: indoc! {r#"
1840 Compares two evaluated values with typed equality (no coercion:
1841 `INT(42)` never equals `STRING("42")`), aborting the pipeline
1842 with a step-numbered error showing expected vs actual otherwise.
1843
1844 Both sides are values: `$var`, literals, templates, and calls
1845 evaluate in memory and never touch disk. Read files explicitly
1846 first (`LET $text: STRING = READ "out.txt"`, then
1847 `ASSERT_EQ $text ...`).
1848 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1849 holding a `PIPE` observes its backend bytes. `--hash` compares
1850 the SHA-256 of a string, pipe, or captured-stdout actual
1851 instead of the raw bytes (`stderr` is unsupported).
1852 "#},
1853 args: &[
1854 ArgSpec { name: "actual", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1855 ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Expected (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
1856 ],
1857 flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
1858 default_output: None,
1859 examples: &[ Example { name: "assert eq", fence_meta: None, code: indoc! {r#"
1860 LET $status: INT = 200
1861 ASSERT_EQ $status 200
1862 "#} },
1863 Example { name: "assert eq file", fence_meta: None, code: indoc! {r#"
1864 WRITE payload.bin stable-content
1865 LET $body: STRING = READ payload.bin
1866 ASSERT_EQ $body "stable-content"
1867 "#} },
1868 Example { name: "assert eq hash", fence_meta: None, code: indoc! {r#"
1869 # --hash compares the SHA-256 digest instead of raw bytes.
1870 WRITE payload.bin stable-content
1871 LET $body: STRING = READ payload.bin
1872 ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body
1873 "#} } ],
1874 lower: |flags, args| {
1875 let hash = flags.iter().find(|(k, _)| k == "hash").map(|(_, v)| v.as_str().to_string());
1876 let mut it = args.into_iter();
1877 let actual = lower_assert_target(it.next().ok_or_else(|| ParseError::validation("ASSERT_EQ", "ASSERT_EQ requires a value".to_string(), &SpanContext::line_only(0)))?)?;
1878 let remaining: Vec<Arg> = it
1879 .map(lower_assert_operand)
1880 .collect::<Vec<Arg>>();
1881 let expected = if remaining.is_empty() {
1884 if hash.is_some() {
1885 None
1886 } else {
1887 return Err(ParseError::validation("ASSERT_EQ", "ASSERT_EQ requires an expected value".to_string(), &SpanContext::line_only(0)))
1888 }
1889 } else {
1890 Some(join_value(remaining, "ASSERT_EQ")?)
1891 };
1892 Ok(StepKind::AssertEq { hash, actual, expected })
1893 },
1894 ],
1895
1896 AssertContains => [
1897 name: "ASSERT_CONTAINS",
1898 variant: AssertContains { haystack: AssertTarget, needle: Arg },
1899 syntax: "ASSERT_CONTAINS <haystack> <needle>",
1900 summary: "Assert containment.",
1901 description: indoc! {r#"
1902 Checks containment and aborts the pipeline with a step-numbered
1903 error otherwise: substring for strings, element match for lists,
1904 key presence for maps, substring over stream and pipe buffers.
1905
1906 Like `ASSERT_EQ`, both sides are values read without implicit
1907 I/O; read files explicitly first
1908 (`LET $text: STRING = READ "cfg.txt"`).
1909 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1910 holding a `PIPE` observes its backend bytes.
1911 "#},
1912 args: &[
1913 ArgSpec { name: "haystack", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1914 ArgSpec { name: "needle", arg_type: ArgType::Rest(&ArgType::Any), description: "Substring, element, or key", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1915 ],
1916 flags: &[],
1917 default_output: None,
1918 examples: &[ Example { name: "assert contains", fence_meta: None, code: indoc! {r#"
1919 ECHO build-complete
1920 ASSERT_CONTAINS stdout "build-complete"
1921 "#} } ],
1922 lower: |flags, args| {
1923 let _ = flags;
1924 let mut it = args.into_iter();
1925 let haystack = lower_assert_target(it.next().ok_or_else(|| ParseError::validation("ASSERT_CONTAINS", "ASSERT_CONTAINS requires a value".to_string(), &SpanContext::line_only(0)))?)?;
1926 let remaining: Vec<Arg> = it
1927 .map(lower_assert_operand)
1928 .collect::<Vec<Arg>>();
1929 if remaining.is_empty() {
1930 return Err(ParseError::validation("ASSERT_CONTAINS", "ASSERT_CONTAINS requires a needle".to_string(), &SpanContext::line_only(0)))
1931 }
1932 let needle = join_value(remaining, "ASSERT_CONTAINS")?;
1933 Ok(StepKind::AssertContains { haystack, needle })
1934 },
1935 ],
1936
1937 HashSha256 => [
1938 name: "HASH_SHA256",
1939 variant: HashSha256 { path: Arg },
1940 syntax: "HASH_SHA256 <path>",
1941 summary: "Print SHA-256.",
1942 description: "Computes digest.",
1943 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: true, fallback_stream: None } ],
1944 flags: &[],
1945 default_output: Some(Stream::Stdout),
1946 examples: &[ Example { name: "hash", fence_meta: None, code: indoc! {r#"
1947 WRITE payload.txt hello
1948 HASH_SHA256 payload.txt
1949
1950 LET $digest: STRING = HASH_SHA256 payload.txt
1951 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\n"
1952 "#} } ],
1953 lower: |_flags, args| Ok(StepKind::HashSha256 { path: args.into_iter().next().ok_or_else(|| ParseError::validation("HASH_SHA256", "HASH_SHA256 requires a path".to_string(), &SpanContext::line_only(0)))? }),
1954 ],
1955
1956 Exit => [
1957 name: "EXIT",
1958 variant: Exit(Arg),
1959 syntax: "EXIT <code>",
1960 summary: "Exit pipeline.",
1961 description: indoc! {r#"
1962 Stops the pipeline immediately with an `EXIT requested with code <code>`
1963 error; steps after it never run, at any nesting depth.
1964
1965 Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state,
1966 anonymous background tasks are killed synchronously, and files written
1967 before the EXIT persist.
1968
1969 The code reaches the OS: the CLI exits with `<code>` clamped to
1970 0..=255, and a guest EXIT relays through `REMOTE` the same way.
1971 "#},
1972 args: &[ ArgSpec { name: "code", arg_type: ArgType::Int, description: "Code", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1973 flags: &[],
1974 default_output: None,
1975 examples: &[ Example { name: "exit", fence_meta: Some("expect_error:\"EXIT requested with code 0\""), code: indoc! {r#"EXIT 0"#} } ],
1976 lower: |_flags, args| {
1977 let code = args.into_iter().next().ok_or_else(|| ParseError::validation("EXIT", "EXIT requires a code".to_string(), &SpanContext::line_only(0)))?;
1980 Ok(StepKind::Exit(code))
1981 },
1982 ],
1983
1984 Sleep => [
1985 name: "SLEEP",
1986 variant: Sleep { duration: Arg },
1987 syntax: "SLEEP <duration>",
1988 summary: "Pause execution for a duration.",
1989 description: indoc! {r#"
1990 Parks the step for the duration (e.g. 500ms, 10s, 2m).
1991
1992 Cooperative: checks for cancellation so an enclosing TIMEOUT or task
1993 teardown interrupts the sleep. Cross-platform alternative to shell sleep
1994 for testing time boundaries.
1995 "#},
1996 args: &[ ArgSpec { name: "duration", arg_type: ArgType::Duration, description: "How long to sleep", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1997 flags: &[],
1998 default_output: None,
1999 examples: &[
2000 Example { name: "sleep", fence_meta: None, code: indoc! {r#"SLEEP 100ms"#} },
2001 Example {
2002 name: "sleep variable duration",
2003 fence_meta: None,
2004 code: indoc! {r#"
2005 # Durations resolve at runtime, so variables work too:
2006 # quoted or bare, both bind the same string.
2007 LET $pause: STRING = "100ms"
2008 SLEEP $pause
2009
2010 LET $bare: STRING = 100ms
2011 SLEEP $bare
2012 "#},
2013 },
2014 ],
2015 lower: |_flags, args| {
2016 let mut it = args.into_iter();
2017 let raw = it
2018 .next()
2019 .ok_or_else(|| ParseError::validation("SLEEP", "SLEEP requires a duration (e.g. SLEEP 500ms)".to_string(), &SpanContext::line_only(0)))?;
2020 if it.next().is_some() {
2021 return Err(ParseError::validation("SLEEP", "SLEEP takes exactly one duration argument".to_string(), &SpanContext::line_only(0)))
2022 }
2023 Ok(StepKind::Sleep { duration: raw })
2026 },
2027 ],
2028
2029 ListAppend => [
2030 name: "LIST_APPEND",
2031 variant: ListAppend { list: String, item: Arg },
2032 syntax: "LIST_APPEND $list <item>",
2033 summary: "Append an item to a LIST variable in place.",
2034 description: indoc! {r#"
2035 Appends the item to the LIST variable in place.
2036
2037 When the binding holds the only reference the push runs in
2038 amortized constant time. Aliased buffers detach first, so
2039 other holders keep their contents.
2040 "#},
2041 args: &[
2042 ArgSpec { name: "list", arg_type: ArgType::List, description: "Target LIST variable (`$name`)", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2043 ArgSpec { name: "item", arg_type: ArgType::Any, description: "Item to append (any value)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
2044 ],
2045 flags: &[],
2046 default_output: None,
2047 examples: &[ Example { name: "list append", fence_meta: None, code: indoc! {r#"
2048 # Appends accumulate in order.
2049 LET $items: LIST<STRING> = []
2050 LIST_APPEND $items "first"
2051 LIST_APPEND $items "second"
2052
2053 LET $want: LIST<STRING> = ["first", "second"]
2054 ASSERT_EQ $items $want
2055 "#} } ],
2056 lower: |_flags, args| {
2057 let mut it = args.into_iter();
2058 let raw_list = it
2059 .next()
2060 .ok_or_else(|| ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))?;
2061 let list = match raw_list {
2062 Arg::Expr(Expr::Var(name)) => name,
2063 Arg::String(s, _) => s.trim_start_matches('$').to_string(),
2064 other => return Err(ParseError::validation("LIST_APPEND", format!("LIST_APPEND requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2065 };
2066 if list.is_empty() {
2067 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))
2068 }
2069 let item = it
2070 .next()
2071 .ok_or_else(|| ParseError::validation("LIST_APPEND", "LIST_APPEND requires an item to append (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))?;
2072 if it.next().is_some() {
2073 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>".to_string(), &SpanContext::line_only(0)))
2074 }
2075 Ok(StepKind::ListAppend { list, item })
2076 },
2077 ],
2078}
2079
2080pub fn all_structural_metadata() -> Vec<CommandMeta> {
2088 vec![
2089 CommandMeta {
2090 name: "WITH_IO",
2091 syntax: "WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> }",
2092 summary: "Reroute standard streams.",
2093 description: indoc! {r#"
2094 Reroutes the standard streams of the next command or, in block form,
2095 of every enclosed command.
2096
2097 Bindings map streams (`stdin`, `stdout`, `stderr`) to a PIPE-typed
2098 variable (`stdout=$p`, `stdin=$p`), resolved from the variable
2099 when the step runs. Both stdout and stderr pipes capture output
2100 the same way. Declare the handle first with `LET $p: PIPE`.
2101
2102 Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a
2103 producer can finish before the consumer starts.
2104
2105 If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or
2106 not, the pipe is a zero copy OS kernel pipe instead: pair it with a
2107 consumer that runs while the producer is alive, since output past the
2108 64 KiB kernel buffer stalls until drained. That promotion never crosses
2109 a function boundary: pipes created, bound, or passed by variable inside FUNC
2110 bodies are always script pipes, even when the surrounding task would
2111 otherwise promote.
2112
2113 A second producer or consumer on a live handle is an explicit
2114 error. A handle bound as output can later feed another
2115 command's `stdin`, connecting commands without touching the
2116 terminal. Binding `stdout` and `stderr` to the same live
2117 handle fails deterministically. Merge streams in shell
2118 via `2>&1` instead.
2119
2120 Nested blocks stack defaults; inline bindings override inherited ones for
2121 their command only; closing a block restores previous wiring.
2122 "#},
2123 args: &[],
2124 flags: &[],
2125 default_output: None,
2126 examples: &[
2127 Example {
2128 name: "with_io block",
2129 fence_meta: None,
2130 code: indoc! {r#"
2131 LET $log: PIPE
2132 WITH_IO [stdout=$log] {
2133 ECHO first
2134 ECHO second
2135 }
2136 WITH_IO [stdin=$log] WRITE captured.txt
2137
2138 # The piped bytes landed in the file.
2139 LET $body: STRING = READ captured.txt
2140 ASSERT_CONTAINS $body "first"
2141 ASSERT_CONTAINS $body "second"
2142 "#},
2143 },
2144 Example {
2145 name: "variable pipe binding",
2146 fence_meta: None,
2147 code: indoc! {r#"
2148 # Declare the pipe first: `LET $p: PIPE` mints a fresh
2149 # backend without touching a stream. A plain string here
2150 # would be a TypeMismatch.
2151 LET $p: PIPE
2152 WITH_IO [stdout=$p] ECHO hello
2153 WITH_IO [stdin=$p] READ_LINE $line
2154 ASSERT_EQ $line "hello"
2155 "#},
2156 },
2157 ],
2158 },
2159 CommandMeta {
2160 name: "FOR",
2161 syntax: "FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }",
2162 summary: "Iterate over a list or map.",
2163 description: indoc! {r#"
2164 The loop variable receives each element (lists) or value (maps); with
2165 two variables, the first receives the key.
2166
2167 Loop variables are declared with explicit types and scoped per iteration;
2168 they do not leak outward. The body may be a braced block
2169 or a single-line `{ ... }` command.
2170
2171 `GLOB("...")` patterns must be quoted (`*` is not a bare word, so
2172 `GLOB(*)` is a parse error); GLOB returns a root-relative sorted list,
2173 empty when nothing matches, and rejects `..` escapes.
2174 "#},
2175 args: &[],
2176 flags: &[],
2177 default_output: None,
2178 examples: &[
2179 Example {
2180 name: "for loop",
2181 fence_meta: None,
2182 code: indoc! {r#"
2183 # Each element binds in turn; the loop body sees every one.
2184 LET $items: LIST<STRING> = ["a", "b"]
2185 FOR $item: STRING IN $items {
2186 ECHO $item
2187 }
2188 ASSERT_CONTAINS stdout "a"
2189 ASSERT_CONTAINS stdout "b"
2190
2191 # Key and value bind together for maps.
2192 LET $map: MAP<x: INT> = {"x": 1}
2193 FOR $k: STRING, $v: INT IN $map {
2194 ECHO "{{ $k }}={{ $v }}"
2195 }
2196 ASSERT_CONTAINS stdout "x=1"
2197 "#},
2198 },
2199 Example {
2200 name: "expand every match",
2201 fence_meta: None,
2202 code: indoc! {r#"
2203 # Single-line body; $x is a template path, WHO an override.
2204 IMPORT [STD]
2205 WRITE a.txt "hi \{{ env:WHO }}!"
2206 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
2207
2208 ASSERT_CONTAINS stdout "hi World!"
2209 "#},
2210 },
2211 ],
2212 },
2213 CommandMeta {
2214 name: "IF",
2215 syntax: "IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]",
2216 summary: "Conditional execution.",
2217 description: indoc! {r#"
2218 The condition is evaluated as a boolean expression.
2219
2220 Prefix `!` negates (`IF !false`); `&&` binds tighter than
2221 `||`, and both short-circuit, so `IF true || $missing`
2222 never evaluates the right side. Only Bool values are
2223 accepted as conditions.
2224 "#},
2225 args: &[],
2226 flags: &[],
2227 default_output: None,
2228 examples: &[
2229 Example {
2230 name: "if else",
2231 fence_meta: None,
2232 code: indoc! {r#"
2233 IMPORT [STD]
2234
2235 # True branch runs; the false branch is skipped.
2236 IF true {
2237 WRITE yes.txt taken
2238 } ELSE {
2239 WRITE yes.txt skipped
2240 }
2241
2242 # ELSE IF selects the first true branch.
2243 IF false {
2244 WRITE skipped.txt no
2245 } ELSE IF true {
2246 WRITE fallback.txt taken
2247 }
2248
2249 # !false evaluates to true, so this branch runs.
2250 IF !false {
2251 WRITE negated.txt taken
2252 }
2253
2254 LET $yes_body: STRING = READ yes.txt
2255 LET $fallback_body: STRING = READ fallback.txt
2256 LET $negated_body: STRING = READ negated.txt
2257 ASSERT_EQ $yes_body "taken"
2258 ASSERT_EQ $fallback_body "taken"
2259 ASSERT_EQ $negated_body "taken"
2260 LET $t: STRING = PATH_TYPE("skipped.txt")
2261 ASSERT_EQ $t "absent"
2262 "#},
2263 },
2264 Example {
2265 name: "logical condition composition",
2266 fence_meta: None,
2267 code: indoc! {r#"
2268 IMPORT [STD]
2269 LET $role: STRING = "admin"
2270 LET $level: INT = 3
2271
2272 # || is true when either side holds; && needs both.
2273 IF $role == "owner" || $level >= 5 {
2274 WRITE unexpected.txt no
2275 } ELSE {
2276 WRITE fallback.txt or-false
2277 }
2278
2279 LET $fb: STRING = READ fallback.txt
2280 ASSERT_EQ $fb "or-false"
2281 LET $t1: STRING = PATH_TYPE("unexpected.txt")
2282 ASSERT_EQ $t1 "absent"
2283
2284 IF $role == "admin" || $level >= 5 {
2285 WRITE chosen.txt or-true
2286 }
2287
2288 LET $ch: STRING = READ chosen.txt
2289 ASSERT_EQ $ch "or-true"
2290
2291 IF $role == "admin" && $level >= 5 {
2292 WRITE unexpected-too.txt no
2293 } ELSE {
2294 WRITE and.txt and-false
2295 }
2296
2297 LET $an: STRING = READ and.txt
2298 ASSERT_EQ $an "and-false"
2299 LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
2300 ASSERT_EQ $t2 "absent"
2301 "#},
2302 },
2303 ],
2304 },
2305 CommandMeta {
2306 name: "LET",
2307 syntax: "LET $var: TYPE = <expr> | LET $p: PIPE | LET $var: TYPE = ASYNC { <commands> } | LET $var: TYPE = <command> | LET $var: TYPE = AWAIT $task | LET $var: TYPE = { <commands> }",
2308 summary: "Bind script-local variables.",
2309 description: indoc! {r#"
2310 Declares a script-local variable with an explicit type (STRING, INT,
2311 FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
2312 in the same scope frame is a redeclaration error; mutate with
2313 `$var = <expr>`.
2314
2315 Variables are usable in templates (`{{ $var }}`), guards, and
2316 expressions. With `ASYNC`, spawns a background task and stores its
2317 handle (see ASYNC). The `$` sigil on the name is mandatory.
2318
2319 No hoisting: a variable exists only after its LET runs, in
2320 execution order. Reading `$var` before its LET (or after the
2321 block that declared it exits) fails with
2322 `undefined variable $var`. Scopes are a stack of frames and
2323 resolution walks innermost outward, so nothing pre-declares
2324 names. Function bodies read outer variables through the same
2325 walk, but their own LETs never leak out (see FUNC).
2326
2327 The right-hand side is always an expression — literals, lists, maps,
2328 arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
2329 parentheses), comparisons (`< <= > >=` binding tighter than
2330 `== !=`), logical `&&` (tighter) and `||` with short-circuit,
2331 `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
2332 `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
2333 `{{ ... }}` template; interpolation happens in string values,
2334 not here.
2335 The one exception is pipes: `LET $p: PIPE` with no `=`
2336 and no initializer mints a fresh anonymous backend,
2337 lazily materialized at first binding, so two declarations
2338 never share a channel.
2339
2340 Numbers are numeric literals: `42` binds `INT`, `3.14` binds
2341 `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
2342 so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
2343 Division by zero, overflow, and non-finite results are errors.
2344 Both numeric sides compare numerically (`1 == 1.0` is true);
2345 otherwise `==`/`!=` compare rendered strings and ordering on
2346 non-numerics is a Type Error. Constant subtrees fold at parse
2347 time and dynamic arithmetic compiles to flat RPN with
2348 identical semantics.
2349
2350 Float equality is exact with no epsilon. Floats store decimals
2351 in binary, so a value is exact only when its reduced fraction
2352 has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
2353 (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
2354 repeat forever in binary (like 1/3 in decimal) and truncate,
2355 so `0.1 + 0.2 == 0.3` is false (the sum is
2356 `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
2357 .125, .625, .875 are exact; .1, .2, .3 and similar are
2358 approximations. Bound approximations instead of comparing
2359 them: `IF $sum > 0.299999 && $sum < 0.300001`.
2360
2361 Comparisons do not chain: `a < b < c` is a parse error, not
2362 `(a < b) < c`. Chaining would compare a `BOOL` against a
2363 number (a runtime Type Error in C-style parsing) or evaluate
2364 the middle term twice (Python-style chaining), so the grammar
2365 accepts exactly one comparison operator per level. Write the
2366 conjunction explicitly: `$a < $b && $b < $c`. The same holds
2367 for equality (`$a == $b == $c` is rejected).
2368
2369 Captured command output is a string, so convert before math:
2370 `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
2371 whitespace; `FLOAT` accepts int strings and rejects
2372 non-finite).
2373
2374 Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
2375 as quoted.
2376
2377 When the right-hand side is a synchronous command
2378 (`LET $out: STRING = ECHO hi`), the command runs to completion and its
2379 exact stdout bytes are captured into the variable as a string (no newline
2380 stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
2381 an error). Combining capture with an explicit
2382 `WITH_IO [stdout=$var]` is a parse error.
2383
2384 Coming from Bash, the capture line looks familiar but behaves
2385 strictly:
2386
2387 | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
2388 | --- | --- | --- |
2389 | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
2390 | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
2391 | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
2392 | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |
2393
2394 `LET $out: TYPE = AWAIT $var` binds the background task's
2395 explicit `RETURN` value instead (tasks stream their stdout
2396 live, so there is no output left to capture); a task that
2397 succeeded without `RETURN` yields `INT` 0, like a process
2398 exit status.
2399
2400 An inline block (`LET $var: TYPE = { <commands> }`) runs its
2401 steps in a fresh scope and binds the nearest `RETURN` value,
2402 like a zero-arg function body: fallthrough without `RETURN`
2403 binds `""`, and `BREAK`/`CONTINUE` escaping the block are
2404 errors. The block reads outer variables but its own LETs
2405 never leak out. A `{k: v}` shape still parses as a map
2406 literal; anything else in braces is a block.
2407
2408 The split is deliberate: synchronous commands capture
2409 stdout because they run inline to completion on the same
2410 thread; background tasks never capture stdout because
2411 concurrent output has no well-defined value. Task results
2412 travel only through `RETURN` (or `INT` 0 for void tasks).
2413
2414 `LET $e: STRING = env:FOO` reads the script environment into a plain
2415 string.
2416 "#},
2417 args: &[],
2418 flags: &[],
2419 default_output: None,
2420 examples: &[
2421 Example {
2422 name: "let",
2423 fence_meta: None,
2424 code: indoc! {r#"
2425 LET $name: STRING = "world"
2426 ECHO "hello, {{ $name }}"
2427 ASSERT_CONTAINS stdout "hello, world"
2428
2429 LET $items: LIST<STRING> = ["a", "b"]
2430 ASSERT_CONTAINS $items "a"
2431 ASSERT_CONTAINS $items "b"
2432
2433 LET $count: INT = 42
2434 ASSERT_EQ $count 42
2435 "#},
2436 },
2437 Example {
2438 name: "no hoisting",
2439 fence_meta: Some("expect_error:\"undefined variable\""),
2440 code: indoc! {r#"
2441 # Reading before the LET runs is an error, not an empty value.
2442 ECHO $too_early
2443 LET $too_early: STRING = "too late"
2444 "#},
2445 },
2446 Example {
2447 name: "glob binding",
2448 fence_meta: None,
2449 code: indoc! {r#"
2450 # The RHS is an expression: GLOB(...) runs and binds a list.
2451 IMPORT [STD]
2452 WRITE a.txt "x"
2453 LET $files: LIST<STRING> = GLOB("*.txt")
2454 FOR $f: STRING IN $files { ECHO $f }
2455
2456 ASSERT_CONTAINS stdout "a.txt"
2457 "#},
2458 },
2459 Example {
2460 name: "scoped variable reverts",
2461 fence_meta: None,
2462 code: indoc! {r#"
2463 # LET inside a braced block reverts when the block exits.
2464 LET $a: STRING = "outer"
2465
2466 [bool:true] {
2467 LET $a: STRING = "inner"
2468 WRITE inner.txt "{{ $a }}"
2469 }
2470
2471 WRITE outer.txt "{{ $a }}"
2472
2473 LET $in_body: STRING = READ inner.txt
2474 ASSERT_EQ $in_body "inner"
2475
2476 LET $out_body: STRING = READ outer.txt
2477 ASSERT_EQ $out_body "outer"
2478 "#},
2479 },
2480 Example {
2481 name: "capture command output",
2482 fence_meta: None,
2483 code: indoc! {r#"
2484 # Capture keeps the trailing newline.
2485 LET $out: STRING = ECHO hi
2486 ASSERT_EQ $out "hi\n"
2487 "#},
2488 },
2489 Example {
2490 name: "inline block",
2491 fence_meta: None,
2492 code: indoc! {r#"
2493 LET $who: STRING = "ada"
2494
2495 # An inline block binds its RETURN value like a function body.
2496 LET $res: STRING = {
2497 LET $loud: STRING = "{{ $who }}!"
2498 RETURN $loud
2499 }
2500 ASSERT_EQ $res "ada!"
2501
2502 # Any declared type works: the block value checks like any RHS.
2503 LET $n: INT = {
2504 RETURN 40 + 2
2505 }
2506 ASSERT_EQ $n 42
2507 "#},
2508 },
2509 Example {
2510 name: "arithmetic over captured output",
2511 fence_meta: None,
2512 code: indoc! {r#"
2513 # Captured output converts explicitly: INT() then arithmetic.
2514 IMPORT [STD]
2515 LET $size_str: STRING = ECHO 41
2516 LET $total: INT = INT($size_str) + 1
2517 ASSERT_EQ $total 42
2518
2519 # FLOAT() promotes instead of truncating.
2520 LET $ratio: FLOAT = 1 + 2.5
2521 ASSERT_EQ $ratio 3.5
2522
2523 # Int x Int stays INT: integer division truncates.
2524 LET $half: INT = 7 / 2
2525 ASSERT_EQ $half 3
2526 "#},
2527 },
2528 Example {
2529 name: "float equality is exact",
2530 fence_meta: None,
2531 code: indoc! {r#"
2532 # Binary fractions compare cleanly; decimal fractions may not:
2533 # 0.1 + 0.2 is 0.30000000000000004, so == is false.
2534 IMPORT [STD]
2535 LET $exact: BOOL = 0.5 + 0.25 == 0.75
2536 LET $decimal: BOOL = 0.1 + 0.2 == 0.3
2537 IF $exact {
2538 WRITE exact.txt yes
2539 }
2540 IF $decimal {
2541 WRITE unexpected.txt no
2542 }
2543
2544 LET $ok: STRING = READ exact.txt
2545 ASSERT_EQ $ok "yes"
2546
2547 LET $t: STRING = PATH_TYPE("unexpected.txt")
2548 ASSERT_EQ $t "absent"
2549 "#},
2550 },
2551 Example {
2552 name: "bound inexact decimals",
2553 fence_meta: None,
2554 code: indoc! {r#"
2555 # Never test inexact decimals for equality; bound them.
2556 LET $sum: FLOAT = 0.1 + 0.2
2557 IF $sum > 0.299999 && $sum < 0.300001 {
2558 WRITE bounded.txt yes
2559 }
2560
2561 LET $ok: STRING = READ bounded.txt
2562 ASSERT_EQ $ok "yes"
2563 "#},
2564 },
2565 Example {
2566 name: "inspect a variable",
2567 fence_meta: None,
2568 code: indoc! {r#"
2569 # INSPECT($var) snapshots a variable into a MAP: declared
2570 # type plus live details (pipe backend stats here), so
2571 # scripts can branch on engine state.
2572 IMPORT [STD]
2573 LET $p: PIPE
2574 WITH_IO [stdout=$p] ECHO hello
2575 LET $info: MAP<ANY> = INSPECT($p)
2576 IF $info.is_os_pipe {
2577 WRITE unexpected.txt "should be a script pipe"
2578 }
2579
2580 ASSERT_EQ $info.type "PIPE"
2581 LET $t: STRING = PATH_TYPE("unexpected.txt")
2582 ASSERT_EQ $t "absent"
2583 "#},
2584 },
2585 ],
2586 },
2587 CommandMeta {
2588 name: "MUTATION",
2589 syntax: "$var = <expr>",
2590 summary: "Mutate a declared variable.",
2591 description: indoc! {r#"
2592 Reassigns an existing variable, converting the new value to
2593 the type declared at LET time. The explicit annotation is
2594 what authorizes string-to-number conversion here (`$n = "42"`
2595 binds 42 for an INT); a non-numeric string is an error.
2596 Expressions never convert: `"100" + 1` is a Type Error, use
2597 `INT()` / `FLOAT()` to cross that boundary explicitly.
2598
2599 The leading `$` distinguishes mutation from `KEY=value` command
2600 assignments. Assigning an undeclared variable or a mismatched type is
2601 an error.
2602
2603 Mutation writes through to the scope where the variable was
2604 declared, so it survives block exit: `LET $x` outside a block
2605 followed by `$x = ...` inside still reads back the new value
2606 afterwards, for every type. This is the counterpart to LET
2607 shadowing, where `LET $x` *inside* the block declares a
2608 separate inner variable that reverts on exit.
2609
2610 Reassignment rebinds the variable to a new value: values
2611 captured earlier keep the old word (see the rebinding
2612 example below).
2613 "#},
2614 args: &[],
2615 flags: &[],
2616 default_output: None,
2617 examples: &[
2618 Example {
2619 name: "mutate",
2620 fence_meta: None,
2621 code: indoc! {r#"
2622 # Mutation writes through: the binding holds the new value.
2623 LET $count: INT = 1
2624 $count = 2
2625 ASSERT_EQ $count 2
2626 "#},
2627 },
2628 Example {
2629 name: "rebind keeps earlier captures",
2630 fence_meta: None,
2631 code: indoc! {r#"
2632 # Reassignment rebinds: a map built from `$s` still
2633 # reads the original string after `$s` moves on.
2634 LET $s: STRING = "test"
2635 LET $m: MAP<ANY> = {a: $s}
2636 $s = "changed"
2637 ASSERT_EQ $m.a "test"
2638
2639 # Appending to one list binding never touches its clones.
2640 LET $a: LIST<STRING> = ["1"]
2641 LET $b: LIST<STRING> = $a
2642 LIST_APPEND $a "2"
2643 LET $want: LIST<STRING> = ["1"]
2644 ASSERT_EQ $b $want
2645 "#},
2646 },
2647 Example {
2648 name: "convert before math",
2649 fence_meta: None,
2650 code: indoc! {r#"
2651 # Captured output is a string: `"100" + 1` is a Type Error.
2652 # Convert explicitly, then mutate with arithmetic.
2653 IMPORT [STD]
2654 LET $raw: STRING = ECHO 100
2655 LET $n: INT = INT($raw)
2656 $n = $n + 1
2657
2658 # The declared slot stays strict: strings parse only
2659 # through the explicit converter, never on assignment.
2660 $n = INT("42")
2661 ASSERT_EQ $n 42
2662
2663 # Same crossing for decimals via FLOAT().
2664 LET $frac_str: STRING = ECHO 2.5
2665 LET $f: FLOAT = FLOAT($frac_str) + 0.25
2666 ASSERT_EQ $f 2.75
2667 "#},
2668 },
2669 ],
2670 },
2671 CommandMeta {
2672 name: "ASYNC",
2673 syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE = ASYNC { <commands> }",
2674 summary: "Run steps in a background thread.",
2675 description: indoc! {r#"
2676 Runs a command or block of commands in a background thread with
2677 subshell isolation.
2678
2679 Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
2680 task handle for `AWAIT`. Task output streams live to the parent
2681 stdout; a task publishes a value with an explicit `RETURN`,
2682 which `LET $out: TYPE = AWAIT $task` binds.
2683
2684 `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
2685 then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
2686 the main thread before the worker spawns. Placing `WITH_IO` directly
2687 inside `ASYNC` is rejected at parse time.
2688 "#},
2689 args: &[],
2690 flags: &[],
2691 default_output: None,
2692 examples: &[
2693 Example {
2694 name: "async",
2695 fence_meta: None,
2696 code: indoc! {r#"
2697 # Inline and block forms both run in the background; AWAIT joins them.
2698 ASYNC ECHO "warming-up"
2699 LET $a: HANDLE = ASYNC ECHO "first"
2700 LET $b: HANDLE = ASYNC {
2701 ECHO "second"
2702 }
2703 AWAIT $a
2704 AWAIT $b
2705 ASSERT_CONTAINS stdout "first"
2706 ASSERT_CONTAINS stdout "second"
2707 "#},
2708 },
2709 Example {
2710 name: "async task handle",
2711 fence_meta: None,
2712 code: indoc! {r#"
2713 LET $task: HANDLE = ASYNC {
2714 ECHO "built"
2715 }
2716 AWAIT $task
2717 ASSERT_CONTAINS stdout "built"
2718 "#},
2719 },
2720 ],
2721 },
2722 CommandMeta {
2723 name: "AWAIT",
2724 syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
2725 summary: "Join a background task.",
2726 description: indoc! {r#"
2727 Blocks until the named task completes. Propagates errors if the task failed.
2728
2729 Task output streams live during the run; joining binds nothing by
2730 itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
2731 `RETURN` value instead, or `INT` 0 when the task succeeded
2732 without one (add `RETURN <expr>` to the task body to yield
2733 a value).
2734 "#},
2735 args: &[],
2736 flags: &[],
2737 default_output: None,
2738 examples: &[
2739 Example {
2740 name: "await",
2741 fence_meta: None,
2742 code: indoc! {r#"
2743 LET $task: HANDLE = ASYNC ECHO "done"
2744 AWAIT $task
2745 ASSERT_CONTAINS stdout "done"
2746 "#},
2747 },
2748 Example {
2749 name: "await capture",
2750 fence_meta: None,
2751 code: indoc! {r#"
2752 LET $task: HANDLE = ASYNC {
2753 ECHO "logged"
2754 RETURN "returned"
2755 }
2756
2757 # AWAIT binds the RETURN value, not the streamed output.
2758 LET $out: STRING = AWAIT $task
2759 ASSERT_EQ $out "returned"
2760 "#},
2761 },
2762 ],
2763 },
2764 CommandMeta {
2765 name: "CANCEL",
2766 syntax: "CANCEL $var",
2767 summary: "Synchronously cancel a background task.",
2768 description: indoc! {r#"
2769 Kills the named background task spawned via LET $var: HANDLE = ASYNC ....
2770
2771 Blocking: returns only after the task thread has been joined and its OS
2772 process reaped, so no residual filesystem or stream mutation follows. A
2773 later AWAIT $var reports cancellation. Only named tasks can be cancelled.
2774 "#},
2775 args: &[],
2776 flags: &[],
2777 default_output: None,
2778 examples: &[
2779 Example {
2780 name: "cancel",
2781 fence_meta: None,
2782 code: indoc! {r#"
2783 LET $task: HANDLE = ASYNC SLEEP 30s
2784 CANCEL $task
2785 "#},
2786 },
2787 Example {
2788 name: "await after cancel reports cancellation",
2789 fence_meta: Some("expect_error:\"was cancelled\""),
2790 code: indoc! {r#"
2791 # A cancelled task stays cancelled: joining it reports.
2792 LET $task: HANDLE = ASYNC SLEEP 30s
2793 CANCEL $task
2794 AWAIT $task
2795 "#},
2796 },
2797 ],
2798 },
2799 CommandMeta {
2800 name: "TIMEOUT",
2801 syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
2802 summary: "Enforce an execution deadline.",
2803 description: indoc! {r#"
2804 Aborts the wrapped step or block with a deadline error if it exceeds the
2805 duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
2806
2807 A blocking foreground process is killed.
2808
2809 ASYNC composes in either nesting order with order-dependent deadline
2810 semantics: `LET $task: HANDLE = ASYNC TIMEOUT 30s RUN "build"` enforces
2811 the deadline inside the background thread (a later `AWAIT $task`
2812 surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
2813 preempts a hung task from the awaiting side.
2814 "#},
2815 args: &[],
2816 flags: &[],
2817 default_output: None,
2818 examples: &[
2819 Example {
2820 name: "timeout",
2821 fence_meta: None,
2822 code: indoc! {r#"
2823 TIMEOUT 30s WRITE heartbeat.txt alive
2824 LET $beat: STRING = READ heartbeat.txt
2825 ASSERT_EQ $beat "alive"
2826 "#},
2827 },
2828 Example {
2829 name: "timeout block",
2830 fence_meta: None,
2831 code: indoc! {r#"
2832 TIMEOUT 30s {
2833 WRITE a.txt one
2834 WRITE b.txt two
2835 }
2836 LET $a: STRING = READ a.txt
2837 LET $b: STRING = READ b.txt
2838 ASSERT_EQ $a "one"
2839 ASSERT_EQ $b "two"
2840 "#},
2841 },
2842 Example {
2843 name: "deadline aborts the step",
2844 fence_meta: Some("expect_error:\"TIMEOUT after\""),
2845 code: indoc! {r#"
2846 # 50ms expires long before the sleep does: the step dies
2847 # with a deadline error instead of running out the clock.
2848 TIMEOUT 50ms SLEEP 30s
2849 "#},
2850 },
2851 Example {
2852 name: "timeout variable duration",
2853 fence_meta: None,
2854 code: indoc! {r#"
2855 # Durations resolve at runtime, so variables work too.
2856 LET $budget: DURATION = "30s"
2857 TIMEOUT $budget WRITE heartbeat.txt alive
2858
2859 LET $beat: STRING = READ heartbeat.txt
2860 ASSERT_EQ $beat "alive"
2861 "#},
2862 },
2863 Example {
2864 name: "timeout await",
2865 fence_meta: None,
2866 code: indoc! {r#"
2867 # AWAIT form bounds a task join instead of a step.
2868 LET $quick: HANDLE = ASYNC {
2869 ECHO hi
2870 }
2871 TIMEOUT 30s AWAIT $quick
2872 "#},
2873 },
2874 ],
2875 },
2876 CommandMeta {
2877 name: "ISOLATED",
2878 syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
2879 summary: "Run steps with the seeded script environment.",
2880 description: indoc! {r#"
2881 Resets the script environment for the block to the session
2882 seed: spawned children see the sandbox defaults plus names
2883 the block re-adds through its leading `INHERIT_ENV`.
2884
2885 The allowlist resolves against the outer scope, never the
2886 host. Absent names stay absent silently, matching top-level
2887 `INHERIT_ENV`.
2888
2889 Script variables, pipes, and files flow through untouched;
2890 only `env:` is reset. Files share the session workspace:
2891 blocks selecting the same `WORKSPACE` target resolve to the
2892 same directory with no per-block overlay, so one block's
2893 writes are visible to another.
2894
2895 Blocks nest (each level re-seeds from the same seed, so
2896 nesting only narrows through the allowlists) and compose
2897 with `ASYNC` and `FUNC`. Scope exit restores the prior
2898 environment.
2899 "#},
2900 args: &[],
2901 flags: &[],
2902 default_output: None,
2903 examples: &[
2904 Example {
2905 name: "isolated scope",
2906 fence_meta: None,
2907 code: indoc! {r#"
2908 # The block sees a clean env; plain steps still run and
2909 # outer bindings survive untouched.
2910 ENV MODE=outer
2911 ISOLATED {
2912 ENV MODE=inner
2913 WRITE inner.txt "{{ env:MODE }}"
2914 }
2915 LET $back: STRING = "{{ env:MODE }}"
2916 ASSERT_EQ $back "outer"
2917 LET $body: STRING = READ inner.txt
2918 ASSERT_EQ $body "inner"
2919 "#},
2920 },
2921 Example {
2922 name: "reseeded child env",
2923 fence_meta: None,
2924 code: indoc! {r#"
2925 # The block resets to the session seed: plain steps and
2926 # spawns run with zero prelude, while outer customs
2927 # stay out.
2928 ENV OUTER_CUSTOM=outer-val
2929 WRITE top-path.txt "{{ env:PATH }}"
2930 ISOLATED {
2931 WRITE inner-path.txt "{{ env:PATH }}"
2932 WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
2933 RUN "echo seed-ok"
2934 }
2935 LET $top: STRING = READ top-path.txt
2936 LET $inner: STRING = READ inner-path.txt
2937 ASSERT_EQ $inner $top
2938 LET $custom: STRING = READ inner-custom.txt
2939 ASSERT_EQ $custom ""
2940 ASSERT_CONTAINS stdout "seed-ok"
2941 "#},
2942 },
2943 Example {
2944 name: "absent names stay absent",
2945 fence_meta: None,
2946 code: indoc! {r#"
2947 # Listing a name the outer scope lacks is not an error:
2948 # the block simply runs without it.
2949 ISOLATED {
2950 INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
2951 ECHO still-runs
2952 }
2953 ASSERT_CONTAINS stdout "still-runs"
2954 "#},
2955 },
2956 Example {
2957 name: "nesting narrows",
2958 fence_meta: None,
2959 code: indoc! {r#"
2960 # Each level snapshots the already-scrubbed parent, so
2961 # an inner block cannot recover what the outer dropped.
2962 ENV KEEP=yes
2963 ISOLATED {
2964 INHERIT_ENV [KEEP]
2965 ISOLATED {
2966 ENV KEEP=inner
2967 WRITE deep.txt "{{ env:KEEP }}"
2968 }
2969 LET $mid: STRING = "{{ env:KEEP }}"
2970 ASSERT_EQ $mid "yes"
2971 }
2972 LET $deep: STRING = READ deep.txt
2973 ASSERT_EQ $deep "inner"
2974 "#},
2975 },
2976 ],
2977 },
2978 CommandMeta {
2979 name: "REMOTE",
2980 syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
2981 summary: "Run a sealed block on a remote target.",
2982 description: indoc! {r#"
2983 Runs the braced block on the named remote target, which the
2984 host binds at startup (`--remote`). The block is sealed:
2985 only header-listed `$var` and `env:NAME` entries cross, the
2986 guest starts empty, and results return through declared
2987 transfers or `WITH_IO` pipes.
2988
2989 The target is a static literal, never a variable. Unknown
2990 targets fail before execution starts.
2991
2992 Bodies check twice: the host static pass validates the
2993 body before anything ships, and the guest re-validates on
2994 arrival through the same entry point, so a body type error
2995 fails locally, never mid-run on the remote.
2996
2997 A failing guest fails the host step: EXIT in the body
2998 exits the guest, and the host relays the code to its own
2999 process exit status (see EXIT).
3000 "#},
3001 args: &[],
3002 flags: &[],
3003 default_output: None,
3004 examples: &[
3005 Example {
3006 name: "sealed header values cross, outer scope does not",
3007 fence_meta: Some("mock_remote:prod"),
3008 code: indoc! {r#"
3009 # Only header-listed names arrive: `$version` is visible
3010 # on the guest, `$secret` was never sent.
3011 LET $version: STRING = "1.2.3"
3012 LET $secret: STRING = "host-only"
3013 REMOTE prod [$version] {
3014 WRITE version.txt "{{ $version }}"
3015 COPY --to-host ./version.txt back.txt
3016 }
3017
3018 # The pushed file proves the guest saw the injected value.
3019 LET $back: STRING = READ back.txt
3020 ASSERT_EQ $back "1.2.3"
3021 "#},
3022 },
3023 Example {
3024 name: "background tasks stream through shared pipes",
3025 fence_meta: Some("mock_remote:prod"),
3026 code: indoc! {r#"
3027 # Two background REMOTEs share one capture pipe while a
3028 # WITH_IO block holds the write end open.
3029 IMPORT [STD]
3030 LET $cap: PIPE
3031 WITH_IO [stdout=$cap] {
3032 LET $a: HANDLE = ASYNC REMOTE prod {
3033 ECHO "from-a"
3034 }
3035 LET $b: HANDLE = ASYNC REMOTE prod {
3036 ECHO "from-b"
3037 }
3038 AWAIT $a
3039 AWAIT $b
3040 }
3041
3042 # EOF ends the drain: no sentinel line, no baked-in count.
3043 LET $n: INT = 0
3044 WHILE !EOF($cap) {
3045 WITH_IO [stdin=$cap] READ_LINE $line
3046 $n = $n + 1
3047 }
3048 ASSERT_EQ $n 2
3049 "#},
3050 },
3051 Example {
3052 name: "declared files cross both directions",
3053 fence_meta: Some("mock_remote:prod roots:unified"),
3054 code: indoc! {r#"
3055 # Fetches ride in, pushes ride back. Anything undeclared
3056 # never leaves its side.
3057 WRITE send.txt "payload"
3058 REMOTE prod {
3059 COPY --from-host ./send.txt got.txt
3060 LET $v: STRING = READ got.txt
3061 ASSERT_EQ $v "payload"
3062 WRITE back.txt "returned"
3063 COPY --to-host ./back.txt back.txt
3064 }
3065
3066 # The push landed on the host; guest staging is gone.
3067 LET $b: STRING = READ back.txt
3068 ASSERT_EQ $b "returned"
3069 "#},
3070 },
3071 Example {
3072 name: "guest workspace selection stays on the guest",
3073 fence_meta: Some("mock_remote:prod"),
3074 code: indoc! {r#"
3075 # WORKSPACE switches inside the block resolve against the
3076 # guest staging dir, which serves as both the SNAPSHOT
3077 # root and the LOCAL build context. The host selection
3078 # restores when the block exits.
3079 REMOTE prod {
3080 WORKSPACE SNAPSHOT
3081 WRITE out.txt "from-snapshot"
3082 COPY --to-host ./out.txt snap.txt
3083 }
3084
3085 LET $s: STRING = READ snap.txt
3086 ASSERT_EQ $s "from-snapshot"
3087 "#},
3088 },
3089 Example {
3090 name: "guest cache persists across execs",
3091 fence_meta: Some("mock_remote:prod"),
3092 code: indoc! {r#"
3093 # WORKSPACE CACHE addresses guest-local persistent
3094 # storage: the second block reads what the first wrote,
3095 # while the guest staging starts empty every time.
3096 REMOTE prod {
3097 WORKSPACE CACHE
3098 WRITE marker.txt "run-marker"
3099 }
3100 REMOTE prod {
3101 WORKSPACE CACHE
3102 LET $m: STRING = READ marker.txt
3103 ASSERT_EQ $m "run-marker"
3104 }
3105 "#},
3106 },
3107 Example {
3108 name: "pushes outside staging fail closed",
3109 fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
3110 code: indoc! {r#"
3111 # WORKSPACE SYSTEM exposes the whole guest machine, but
3112 # transfers stay staging scoped: a push source outside
3113 # staging fails loudly instead of crossing.
3114 REMOTE prod {
3115 WORKSPACE SYSTEM
3116 COPY --to-host /no/such/file.txt got.txt
3117 }
3118 "#},
3119 },
3120 Example {
3121 name: "guest exit fails the step, host survives",
3122 fence_meta: Some(
3123 "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
3124 ),
3125 code: indoc! {r#"
3126 # EXIT in the body exits the guest with code 3. The
3127 # host is unaffected: it keeps executing after the
3128 # guest is already dead, and the failure surfaces as
3129 # a host step error carrying the same code. The CLI
3130 # then exits with it, so the guest code reaches the OS.
3131 LET $t: HANDLE = ASYNC REMOTE prod {
3132 EXIT 3
3133 }
3134 WRITE host-alive.txt "still here"
3135 AWAIT $t
3136 "#},
3137 },
3138 Example {
3139 name: "remote block without a runner",
3140 fence_meta: Some("expect_error:\"has no registered session\""),
3141 code: indoc! {r#"
3142 # Without a bound session, the block bails instead of
3143 # executing anywhere unexpected.
3144 REMOTE prod {
3145 ECHO "do something on remote"
3146 }
3147 "#},
3148 },
3149 ],
3150 },
3151 CommandMeta {
3152 name: "FUNC",
3153 syntax: "FUNC NAME([$param: TYPE, ...]) { <commands> }",
3154 summary: "Define a user function.",
3155 description: indoc! {r#"
3156 Defines a user function with UPPERCASE name and explicitly typed
3157 parameters.
3158
3159 Params bind by position, converting each argument to its
3160 declared parameter type before the body runs.
3161 Bodies run in a fresh variable scope; LETs inside do not leak. A nested
3162 FUNC definition is scoped to its block and reverts on exit. Names share
3163 one namespace with native and host-registered functions, which a FUNC
3164 may never shadow.
3165
3166 Functions resolve like variables: a name is visible from its
3167 definition line, so recursion works but mutual recursion does
3168 not (the second name does not exist while the first body
3169 lowers). Calls name their module (`STD::GLOB(...)`) unless
3170 imported; see IMPORT.
3171
3172 Invoke any function with one syntax: `NAME(...)` as a statement
3173 (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
3174 the RETURN value (fallthrough without RETURN captures as "").
3175 "#},
3176 args: &[],
3177 flags: &[],
3178 default_output: None,
3179 examples: &[
3180 Example {
3181 name: "func def call",
3182 fence_meta: None,
3183 code: indoc! {r#"
3184 FUNC GREET($name: STRING) {
3185 RETURN $name
3186 }
3187
3188 LET $res: STRING = GREET("ada")
3189 ASSERT_EQ $res "ada"
3190
3191 # Statement form: parens stay, the value drops.
3192 GREET("bex")
3193 "#},
3194 },
3195 Example {
3196 name: "call with pipes",
3197 fence_meta: None,
3198 code: indoc! {r#"
3199 # A pipe handle travels into a function as a typed argument
3200 # and is usable as a binding target in both directions.
3201 # `LET $p: PIPE` mints the handle; `$p` passes it on.
3202 FUNC DRAIN($q: PIPE) {
3203 WITH_IO [stdin=$q] READ_LINE $line
3204 RETURN $line
3205 }
3206
3207 LET $p: PIPE
3208 WITH_IO [stdout=$p] ECHO "payload"
3209
3210 LET $got: STRING = DRAIN($p)
3211 ASSERT_EQ $got "payload"
3212 "#},
3213 },
3214 ],
3215 },
3216 CommandMeta {
3217 name: "RETURN",
3218 syntax: "RETURN [<expr>]",
3219 summary: "Return a value from a function, task, or inline block.",
3220 description: indoc! {r#"
3221 Ends the nearest enclosing boundary with a value: a function
3222 call, an `ASYNC` task (bound by `LET $o = AWAIT $t`), or an
3223 inline `LET` block. Bare `RETURN` with no expression yields
3224 `""`.
3225
3226 Falling off the end without RETURN yields "". RETURN with no
3227 enclosing boundary (including at top level) is an error; use
3228 EXIT or ECHO there.
3229 "#},
3230 args: &[],
3231 flags: &[],
3232 default_output: None,
3233 examples: &[Example {
3234 name: "return",
3235 fence_meta: None,
3236 code: indoc! {r#"
3237 FUNC PICK($flag: BOOL) {
3238 IF $flag {
3239 RETURN "yes"
3240 }
3241 RETURN "no"
3242 }
3243
3244 LET $res: STRING = PICK(true)
3245 ASSERT_EQ $res "yes"
3246
3247 # Fallthrough without RETURN yields its own value.
3248 LET $no: STRING = PICK(false)
3249 ASSERT_EQ $no "no"
3250 "#},
3251 }],
3252 },
3253 CommandMeta {
3254 name: "WHILE",
3255 syntax: "WHILE <bool-expr> { <commands> }",
3256 summary: "Loop while a condition holds.",
3257 description: indoc! {r#"
3258 Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
3259 non-Bool is a type error).
3260
3261 Each iteration runs in a fresh scope; mutate outer state with $var = ...
3262 so the next check observes it. BREAK exits the loop; CONTINUE skips to
3263 the next check.
3264 "#},
3265 args: &[],
3266 flags: &[],
3267 default_output: None,
3268 examples: &[Example {
3269 name: "while loop",
3270 fence_meta: None,
3271 code: indoc! {r#"
3272 # The condition re-evaluates every iteration: three passes, then stop.
3273 LET $n: INT = 0
3274 WHILE $n < 3 {
3275 WRITE tick.txt "{{ $n }}"
3276 $n = $n + 1
3277 }
3278
3279 ASSERT_EQ $n 3
3280 LET $tick: STRING = READ tick.txt
3281 ASSERT_EQ $tick "2"
3282 "#},
3283 }],
3284 },
3285 CommandMeta {
3286 name: "BREAK",
3287 syntax: "BREAK",
3288 summary: "Exit the innermost loop.",
3289 description: indoc! {r#"
3290 Exits the innermost enclosing FOR or WHILE loop.
3291
3292 BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
3293 "#},
3294 args: &[],
3295 flags: &[],
3296 default_output: None,
3297 examples: &[Example {
3298 name: "break",
3299 fence_meta: None,
3300 code: indoc! {r#"
3301 # BREAK leaves after the first pass: only "a" is written.
3302 FOR $x: STRING IN ["a", "b"] {
3303 WRITE picked.txt "{{ $x }}"
3304 BREAK
3305 }
3306
3307 LET $body: STRING = READ picked.txt
3308 ASSERT_EQ $body "a"
3309 "#},
3310 }],
3311 },
3312 CommandMeta {
3313 name: "CONTINUE",
3314 syntax: "CONTINUE",
3315 summary: "Skip to the next loop iteration.",
3316 description: indoc! {r#"
3317 Skips the rest of the innermost enclosing FOR or WHILE body and starts
3318 the next iteration.
3319
3320 CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
3321 "#},
3322 args: &[],
3323 flags: &[],
3324 default_output: None,
3325 examples: &[Example {
3326 name: "continue",
3327 fence_meta: None,
3328 code: indoc! {r#"
3329 # CONTINUE skips the write on "a": only "b" lands.
3330 FOR $x: STRING IN ["a", "b"] {
3331 IF $x == "a" {
3332 CONTINUE
3333 }
3334 WRITE picked.txt "{{ $x }}"
3335 }
3336
3337 LET $body: STRING = READ picked.txt
3338 ASSERT_EQ $body "b"
3339 "#},
3340 }],
3341 },
3342 CommandMeta {
3343 name: KEYWORD_IMPORT,
3344 syntax: "IMPORT [<module>, ...] | IMPORT <module>",
3345 summary: "Bring module functions into bare-call scope.",
3346 description: indoc! {r#"
3347 Every function call names its module (`STD::GLOB(...)`,
3348 `MOCK::READ_CSV(...)`) unless the module is imported:
3349 `IMPORT [STD]` lets the rest of the scope call `GLOB(...)`
3350 bare. Calls resolve at parse time against `SCRIPT`
3351 definitions first, then imported modules; unknown modules,
3352 unknown functions, and unimported bare calls are parse
3353 errors, never runtime surprises.
3354
3355 IMPORT is a lowering directive, not a step: it applies from
3356 its line to the enclosing block exit, then reverts, exactly
3357 like `LET` scoping but with no runtime footprint. Guards do
3358 not apply to it. Two imported modules exporting one name is
3359 an ambiguity error: qualify the call instead.
3360
3361 `EXPORT` is reserved for future script-module support and
3362 cannot be used yet.
3363 "#},
3364 args: &[],
3365 flags: &[],
3366 default_output: None,
3367 examples: &[Example {
3368 name: "import",
3369 fence_meta: None,
3370 code: indoc! {r#"
3371 # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
3372 WRITE a.txt "hi \{{ env:WHO }}!"
3373 IMPORT [STD]
3374 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
3375 ASSERT_CONTAINS stdout "hi World!"
3376 "#},
3377 }],
3378 },
3379 ]
3380}
3381
3382impl fmt::Display for StepKind {
3385 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3386 match self {
3387 StepKind::InheritEnv { keys } => write!(f, "INHERIT_ENV [{}]", keys.join(", ")),
3388 StepKind::Workdir(a) => write!(f, "WORKDIR {}", fmt_value(a, quote_arg)),
3389 StepKind::Workspace(t) => write!(f, "WORKSPACE {}", t),
3390 StepKind::Env { key, value } => {
3391 write!(f, "ENV {}={}", key, fmt_value(value, quote_arg))
3392 }
3393 StepKind::Run(c) => write!(f, "RUN {}", fmt_value(c, quote_run)),
3394 StepKind::RunExec { argv } => {
3395 let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
3396 write!(f, "RUN [{}]", parts.join(", "))
3397 }
3398 StepKind::Echo(m) => write!(f, "ECHO {}", fmt_value(m, quote_msg)),
3399 StepKind::Copy {
3400 from_workspace,
3401 from_host,
3402 to_host,
3403 from,
3404 to,
3405 } => {
3406 let mut head = String::from("COPY");
3407 if let Some(target) = from_workspace {
3408 head.push_str(&format!(" --from-workspace {target}"));
3409 }
3410 if *from_host {
3411 head.push_str(" --from-host");
3412 }
3413 if *to_host {
3414 head.push_str(" --to-host");
3415 }
3416 write!(
3417 f,
3418 "{head} {} {}",
3419 fmt_value(from, quote_arg),
3420 fmt_value(to, quote_arg)
3421 )
3422 }
3423 StepKind::Symlink {
3424 from_workspace,
3425 from,
3426 to,
3427 } => {
3428 if let Some(target) = from_workspace {
3429 write!(
3430 f,
3431 "SYMLINK --from-workspace {} {} {}",
3432 target,
3433 fmt_value(from, quote_arg),
3434 fmt_value(to, quote_arg)
3435 )
3436 } else {
3437 write!(
3438 f,
3439 "SYMLINK {} {}",
3440 fmt_value(from, quote_arg),
3441 fmt_value(to, quote_arg)
3442 )
3443 }
3444 }
3445 StepKind::Mkdir(a) => write!(f, "MKDIR {}", fmt_value(a, quote_arg)),
3446 StepKind::Install { from, to } => write!(
3447 f,
3448 "INSTALL {} {}",
3449 fmt_value(from, quote_arg),
3450 fmt_value(to, quote_arg)
3451 ),
3452 StepKind::Archive { src, dst, raw } => {
3453 if *raw {
3454 write!(
3455 f,
3456 "ARCHIVE --raw {} {}",
3457 fmt_value(src, quote_arg),
3458 fmt_value(dst, quote_arg)
3459 )
3460 } else {
3461 write!(
3462 f,
3463 "ARCHIVE {} {}",
3464 fmt_value(src, quote_arg),
3465 fmt_value(dst, quote_arg)
3466 )
3467 }
3468 }
3469 StepKind::Unarchive {
3470 src,
3471 dst,
3472 max_bytes,
3473 } => {
3474 write!(f, "UNARCHIVE")?;
3475 if let Some(n) = max_bytes {
3476 write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
3477 }
3478 write!(
3479 f,
3480 " {} {}",
3481 fmt_value(src, quote_arg),
3482 fmt_value(dst, quote_arg)
3483 )
3484 }
3485 StepKind::Ls(a) => {
3486 write!(f, "LS")?;
3487 if let Some(x) = a {
3488 write!(f, " {}", fmt_value(x, quote_arg))?;
3489 }
3490 Ok(())
3491 }
3492 StepKind::Cwd => write!(f, "CWD"),
3493 StepKind::Read(a) => {
3494 write!(f, "READ")?;
3495 if let Some(x) = a {
3496 write!(f, " {}", fmt_value(x, quote_arg))?;
3497 }
3498 Ok(())
3499 }
3500 StepKind::ReadLine { var } => write!(f, "READ_LINE ${}", var),
3501 StepKind::Prompt {
3502 var,
3503 message,
3504 default,
3505 } => {
3506 write!(f, "PROMPT ${} {}", var, fmt_value(message, quote_arg))?;
3507 if let Some(d) = default {
3508 write!(f, " {}", fmt_value(d, quote_arg))?;
3509 }
3510 Ok(())
3511 }
3512 StepKind::Write { path, contents } => {
3513 write!(f, "WRITE {}", fmt_value(path, quote_arg))?;
3514 if let Some(b) = contents {
3515 write!(f, " {}", fmt_value(b, quote_msg))?;
3516 }
3517 Ok(())
3518 }
3519 StepKind::Append { path, contents } => {
3520 write!(f, "APPEND {}", fmt_value(path, quote_arg))?;
3521 if let Some(b) = contents {
3522 write!(f, " {}", fmt_value(b, quote_msg))?;
3523 }
3524 Ok(())
3525 }
3526 StepKind::Remove { path, recursive } => {
3527 if *recursive {
3528 write!(f, "REMOVE --recursive {}", fmt_value(path, quote_arg))
3529 } else {
3530 write!(f, "REMOVE {}", fmt_value(path, quote_arg))
3531 }
3532 }
3533 StepKind::Expand { path, overrides } => {
3534 write!(f, "EXPAND")?;
3535 if let Some(p) = path {
3536 write!(f, " {}", fmt_value(p, quote_arg))?;
3537 }
3538 for (k, v) in overrides {
3539 write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
3540 }
3541 Ok(())
3542 }
3543 StepKind::AssertEq {
3544 hash,
3545 actual,
3546 expected,
3547 } => {
3548 if let Some(d) = hash {
3549 write!(f, "ASSERT_EQ --hash {d} {}", fmt_assert_target(actual))?;
3550 } else {
3551 write!(
3552 f,
3553 "ASSERT_EQ {} {}",
3554 fmt_assert_target(actual),
3555 fmt_value(
3556 expected
3557 .as_ref()
3558 .expect("Display of ASSERT_EQ without --hash needs expected"),
3559 quote_msg
3560 )
3561 )?;
3562 }
3563 Ok(())
3564 }
3565 StepKind::AssertContains { haystack, needle } => write!(
3566 f,
3567 "ASSERT_CONTAINS {} {}",
3568 fmt_assert_target(haystack),
3569 fmt_value(needle, quote_msg)
3570 ),
3571 StepKind::WithIo { bindings, cmd } => {
3572 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3573 write!(f, "WITH_IO [{}] {}", p.join(", "), cmd)
3574 }
3575 StepKind::WithIoBlock { bindings } => {
3576 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3577 write!(f, "WITH_IO [{}] {{...}}", p.join(", "))
3578 }
3579 StepKind::CopyGit {
3580 rev,
3581 from,
3582 to,
3583 include_dirty,
3584 } => {
3585 if *include_dirty {
3586 write!(
3587 f,
3588 "COPY_GIT --include-dirty {} {} {}",
3589 fmt_value(rev, quote_arg),
3590 fmt_value(from, quote_arg),
3591 fmt_value(to, quote_arg)
3592 )
3593 } else {
3594 write!(
3595 f,
3596 "COPY_GIT {} {} {}",
3597 fmt_value(rev, quote_arg),
3598 fmt_value(from, quote_arg),
3599 fmt_value(to, quote_arg)
3600 )
3601 }
3602 }
3603 StepKind::HashSha256 { path } => {
3604 write!(f, "HASH_SHA256 {}", fmt_value(path, quote_arg))
3605 }
3606 StepKind::Exit(code) => write!(f, "EXIT {}", fmt_raw_arg(code)),
3607 StepKind::Sleep { duration } => write!(f, "SLEEP {}", fmt_raw_arg(duration)),
3608 StepKind::ListAppend { list, item } => {
3609 write!(f, "LIST_APPEND ${} {}", list, fmt_raw_arg(item))
3610 }
3611 StepKind::For {
3612 key_var,
3613 key_type,
3614 var,
3615 var_type,
3616 in_expr,
3617 body,
3618 } => {
3619 match key_var {
3620 Some(k) => {
3621 let kt = key_type.as_deref().unwrap_or("STRING");
3622 write!(
3623 f,
3624 "FOR ${}: {}, ${}: {} IN {} {{",
3625 k, kt, var, var_type, in_expr
3626 )?
3627 }
3628 None => write!(f, "FOR ${}: {} IN {} {{", var, var_type, in_expr)?,
3629 }
3630 for s in body {
3631 write!(f, "\n {}", s)?;
3632 }
3633 write!(f, "\n}}")
3634 }
3635 StepKind::If {
3636 cond,
3637 then_body,
3638 else_ifs,
3639 else_body,
3640 } => {
3641 write!(f, "IF {} {{", cond)?;
3642 for s in then_body {
3643 write!(f, "\n {}", s)?;
3644 }
3645 write!(f, " }}")?;
3646 for (c, b) in else_ifs {
3647 write!(f, " ELSE IF {} {{", c)?;
3648 for s in b {
3649 write!(f, "\n {}", s)?;
3650 }
3651 write!(f, " }}")?;
3652 }
3653 if let Some(b) = else_body {
3654 write!(f, " ELSE {{")?;
3655 for s in b {
3656 write!(f, "\n {}", s)?;
3657 }
3658 write!(f, " }}")?;
3659 }
3660 Ok(())
3661 }
3662 StepKind::Assign {
3663 var,
3664 decl_type,
3665 expr,
3666 } => {
3667 if matches!(expr, Expr::FreshPipe) {
3669 write!(f, "LET ${}: {}", var, decl_type)
3670 } else {
3671 write!(f, "LET ${}: {} = {}", var, decl_type, expr)
3672 }
3673 }
3674 StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
3675 StepKind::AssignCapture {
3676 var,
3677 decl_type,
3678 cmd,
3679 } => {
3680 write!(f, "LET ${}: {} = {}", var, decl_type, cmd)
3681 }
3682 StepKind::AsyncBlock { body } => {
3683 write!(f, "ASYNC {{")?;
3684 for s in body {
3685 write!(f, "\n {}", s)?;
3686 }
3687 write!(f, "\n}}")
3688 }
3689 StepKind::AssignAsync {
3690 var,
3691 decl_type,
3692 body,
3693 } => {
3694 write!(f, "LET ${}: {} = ASYNC {{", var, decl_type)?;
3695 for s in body {
3696 write!(f, "\n {}", s)?;
3697 }
3698 write!(f, "\n}}")
3699 }
3700 StepKind::Await { var } => write!(f, "AWAIT ${}", var),
3701 StepKind::AwaitCapture {
3702 out_var,
3703 out_type,
3704 task_var,
3705 } => {
3706 write!(f, "LET ${}: {} = AWAIT ${}", out_var, out_type, task_var)
3707 }
3708 StepKind::Cancel { var } => write!(f, "CANCEL ${}", var),
3709 StepKind::Timeout { duration, body } => {
3710 let budget = fmt_raw_arg(duration);
3711 if body.len() == 1 {
3712 write!(f, "TIMEOUT {} {}", budget, body[0].kind)
3713 } else {
3714 write!(f, "TIMEOUT {} {{", budget)?;
3715 for s in body {
3716 write!(f, "\n {}", s)?;
3717 }
3718 write!(f, "\n}}")
3719 }
3720 }
3721 StepKind::Isolated { body } => {
3722 if body.len() == 1 {
3723 write!(f, "ISOLATED {}", body[0].kind)
3724 } else {
3725 write!(f, "ISOLATED {{")?;
3726 for s in body {
3727 write!(f, "\n {}", s)?;
3728 }
3729 write!(f, "\n}}")
3730 }
3731 }
3732 StepKind::IsolatedInheritEnv { keys } => {
3733 write!(f, "INHERIT_ENV [{}]", keys.join(", "))
3737 }
3738 StepKind::RemoteBlock {
3739 target,
3740 vars,
3741 env,
3742 body,
3743 } => {
3744 let mut entries: Vec<String> = vars.iter().map(|v| format!("${v}")).collect();
3745 entries.extend(env.iter().map(|e| format!("env:{e}")));
3746 if entries.is_empty() {
3747 write!(f, "REMOTE {target} {{")?;
3748 } else {
3749 write!(f, "REMOTE {target} [{}] {{", entries.join(", "))?;
3750 }
3751 for s in body {
3752 write!(f, "\n {}", s)?;
3753 }
3754 write!(f, "\n}}")
3755 }
3756 StepKind::FuncDef { name, params, body } => {
3757 let ps: Vec<String> = params
3758 .iter()
3759 .map(|(p, t)| format!("${}: {}", p, t))
3760 .collect();
3761 write!(f, "FUNC {}({}) {{", name, ps.join(", "))?;
3762 for s in body {
3763 write!(f, "\n {}", s)?;
3764 }
3765 write!(f, "\n}}")
3766 }
3767 StepKind::Call { name, args } => {
3768 let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
3769 write!(f, "{}({})", name, ps.join(", "))
3770 }
3771 StepKind::Return { expr } => write!(f, "RETURN {}", expr),
3772 StepKind::TypeAlias { name, target } => write!(f, "TYPE {} = {}", name, target),
3773 StepKind::While { cond, body } => {
3774 write!(f, "WHILE {} {{", cond)?;
3775 for s in body {
3776 write!(f, "\n {}", s)?;
3777 }
3778 write!(f, "\n}}")
3779 }
3780 StepKind::Break => write!(f, "BREAK"),
3781 StepKind::Continue => write!(f, "CONTINUE"),
3782 }
3783 }
3784}
3785
3786#[cfg(test)]
3787mod tests {
3788 use super::*;
3789 use crate::command::{
3790 format_byte_count, format_duration, parse_byte_count, parse_duration,
3791 strip_digit_separators,
3792 };
3793 use crate::parser::parse_script;
3794
3795 fn parse_err(script: &str) -> String {
3796 parse_script(script, lower_command)
3797 .expect_err("script must fail to parse")
3798 .to_string()
3799 }
3800
3801 #[test]
3802 fn malformed_with_io_binding_names_the_bad_binding() {
3803 let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
3804 assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
3805 assert!(!err.contains("unknown command"), "{err}");
3806 assert!(err.contains("stdout=discard"), "{err}");
3807 assert!(err.contains("[stdout=$p]"), "{err}");
3808 }
3809
3810 #[test]
3811 fn connect_is_unknown_command() {
3812 let err = parse_err("CONNECT 127.0.0.1:8080\n");
3815 assert!(err.contains("unknown command"), "{err}");
3816 assert!(err.contains("CONNECT"), "{err}");
3817 }
3818
3819 #[test]
3820 fn listen_is_unknown_command() {
3821 let err = parse_err("LISTEN 127.0.0.1:8080\n");
3824 assert!(err.contains("unknown command"), "{err}");
3825 assert!(err.contains("LISTEN"), "{err}");
3826 }
3827
3828 #[test]
3829 fn await_without_task_variable_points_at_syntax() {
3830 let err = parse_err("AWAIT ECHO \"test\"\n");
3831 assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
3832 assert!(!err.contains("unknown command"), "{err}");
3833 assert!(err.contains("AWAIT $t"), "{err}");
3834 assert!(err.contains("ECHO"), "{err}");
3835 }
3836
3837 #[test]
3838 fn bare_let_without_type_points_at_typed_syntax() {
3839 let err = parse_err("LET $x = 1\n");
3840 assert!(err.contains("invalid syntax for command LET"), "{err}");
3841 assert!(err.contains("LET $name: STRING = <expr>"), "{err}");
3842 }
3843
3844 #[test]
3845 fn workspace_accepts_all_four_targets_uppercase_only() {
3846 for (spelling, target) in [
3849 ("SNAPSHOT", WorkspaceTarget::Snapshot),
3850 ("LOCAL", WorkspaceTarget::Local),
3851 ("CACHE", WorkspaceTarget::Cache { local: false }),
3852 ("SYSTEM", WorkspaceTarget::System),
3853 ] {
3854 let steps =
3855 parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
3856 assert_eq!(steps.len(), 1);
3857 assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
3858 assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
3859 }
3860 for spelling in ["snapshot", "local", "cache", "system"] {
3861 let err = parse_err(&format!("WORKSPACE {spelling}\n"));
3862 assert!(
3863 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
3864 "{spelling}: {err}"
3865 );
3866 }
3867 let err = parse_err("WORKSPACE REMOTE\n");
3868 assert!(
3869 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
3870 "{err}"
3871 );
3872
3873 let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
3876 assert_eq!(
3877 steps[0].kind,
3878 StepKind::Workspace(WorkspaceTarget::Cache { local: true })
3879 );
3880 assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
3881 for bad in [
3882 "WORKSPACE SNAPSHOT --local\n",
3883 "WORKSPACE LOCAL --local\n",
3884 "WORKSPACE SYSTEM --local\n",
3885 ] {
3886 let err = parse_err(bad);
3887 assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
3888 }
3889 }
3890
3891 #[test]
3892 fn archive_unarchive_parse_and_round_trip() {
3893 let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
3894 match &steps[0].kind {
3895 StepKind::Archive { src, dst, raw } => {
3896 assert_eq!(src.as_str(), "bundle");
3897 assert_eq!(dst.as_str(), "bundle.tar.gz");
3898 assert!(!raw);
3899 }
3900 other => panic!("expected Archive, got {other:?}"),
3901 }
3902 assert_eq!(
3903 steps[0].kind.to_string(),
3904 "ARCHIVE bundle \"bundle.tar.gz\""
3905 );
3906
3907 let steps =
3908 parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
3909 assert!(
3910 matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
3911 "unexpected lowering: {:?}",
3912 steps[0].kind
3913 );
3914 assert_eq!(
3915 steps[0].kind.to_string(),
3916 "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
3917 );
3918
3919 let steps =
3920 parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
3921 match &steps[0].kind {
3922 StepKind::Unarchive {
3923 src,
3924 dst,
3925 max_bytes,
3926 } => {
3927 assert_eq!(src.as_str(), "pack.tar.gz");
3928 assert_eq!(dst.as_str(), "unpacked");
3929 assert_eq!(max_bytes, &None);
3930 }
3931 other => panic!("expected Unarchive, got {other:?}"),
3932 }
3933 assert_eq!(
3934 steps[0].kind.to_string(),
3935 "UNARCHIVE \"pack.tar.gz\" unpacked"
3936 );
3937
3938 let steps = parse_script(
3939 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
3940 lower_command,
3941 )
3942 .expect("parses");
3943 match &steps[0].kind {
3944 StepKind::Unarchive {
3945 src,
3946 dst,
3947 max_bytes,
3948 } => {
3949 assert_eq!(src.as_str(), "pack.tar.gz");
3950 assert_eq!(dst.as_str(), "unpacked");
3951 assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
3952 }
3953 other => panic!("expected Unarchive, got {other:?}"),
3954 }
3955 assert_eq!(
3956 steps[0].kind.to_string(),
3957 "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
3958 );
3959
3960 for script in [
3961 "ARCHIVE bundle bundle.tar.gz\n",
3962 "ARCHIVE --raw tool.bin tool.tar\n",
3963 "UNARCHIVE pack.tar.gz unpacked\n",
3964 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
3965 ] {
3966 let first = parse_script(script, lower_command).expect("parses");
3967 let rendered = first[0].kind.to_string() + "\n";
3968 let second = parse_script(&rendered, lower_command).expect("reparses");
3969 assert_eq!(
3972 second[0].kind.to_string(),
3973 first[0].kind.to_string(),
3974 "Display must fixpoint for {script:?}"
3975 );
3976 }
3977
3978 for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
3979 let err = parse_err(bad);
3980 assert!(
3981 err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
3982 "{bad}: {err}"
3983 );
3984 }
3985 }
3986
3987 #[test]
3988 fn copy_from_workspace_selects_source_root() {
3989 for (spelling, target) in [
3990 ("SNAPSHOT", WorkspaceTarget::Snapshot),
3991 ("LOCAL", WorkspaceTarget::Local),
3992 ("CACHE", WorkspaceTarget::Cache { local: false }),
3993 ("SYSTEM", WorkspaceTarget::System),
3994 ] {
3995 let steps = parse_script(
3996 &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
3997 lower_command,
3998 )
3999 .expect("parses");
4000 assert!(
4001 matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
4002 "unexpected lowering for {spelling}: {:?}",
4003 steps[0].kind
4004 );
4005 }
4006 for script in [
4009 "COPY --from-workspace=CACHE a.txt b.txt\n",
4010 "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
4011 ] {
4012 let steps = parse_script(script, lower_command).expect("parses");
4013 assert!(
4014 matches!(
4015 &steps[0].kind,
4016 StepKind::Copy {
4017 from_workspace: Some(WorkspaceTarget::Cache { local: false }),
4018 ..
4019 }
4020 ),
4021 "unexpected lowering for {script:?}: {:?}",
4022 steps[0].kind
4023 );
4024 }
4025 let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
4027 assert!(
4028 matches!(
4029 &steps[0].kind,
4030 StepKind::Copy {
4031 from_workspace: None,
4032 ..
4033 }
4034 ),
4035 "unexpected lowering: {:?}",
4036 steps[0].kind
4037 );
4038 for bad in ["REMOTE", "local"] {
4040 let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
4041 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4042 }
4043 }
4044
4045 #[test]
4046 fn symlink_from_workspace_selects_source_root() {
4047 for (spelling, target) in [
4048 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4049 ("LOCAL", WorkspaceTarget::Local),
4050 ("CACHE", WorkspaceTarget::Cache { local: false }),
4051 ("SYSTEM", WorkspaceTarget::System),
4052 ] {
4053 let steps = parse_script(
4054 &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
4055 lower_command,
4056 )
4057 .expect("parses");
4058 assert!(
4059 matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
4060 "unexpected lowering for {spelling}: {:?}",
4061 steps[0].kind
4062 );
4063 let roundtrip = steps[0].kind.to_string();
4064 assert!(
4065 roundtrip.contains("--from-workspace"),
4066 "display should round-trip the flag: {roundtrip}"
4067 );
4068 }
4069 let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
4070 assert!(
4071 matches!(
4072 &steps[0].kind,
4073 StepKind::Symlink {
4074 from_workspace: None,
4075 ..
4076 }
4077 ),
4078 "unexpected lowering: {:?}",
4079 steps[0].kind
4080 );
4081 for bad in ["REMOTE", "local"] {
4082 let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
4083 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4084 }
4085 let steps = parse_script(
4087 "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
4088 lower_command,
4089 )
4090 .expect("parses");
4091 assert!(
4092 matches!(
4093 &steps[0].kind,
4094 StepKind::Symlink {
4095 from_workspace: Some(WorkspaceTarget::Local),
4096 ..
4097 }
4098 ),
4099 "unexpected lowering: {:?}",
4100 steps[0].kind
4101 );
4102 }
4103
4104 #[test]
4105 fn dash_dash_equals_tokens_bypass_assignment() {
4106 let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
4109 let StepKind::Env { key, value } = &steps[0].kind else {
4110 panic!("expected Env, got {:?}", steps[0].kind);
4111 };
4112 assert_eq!(key, "--foo");
4113 assert_eq!(value.as_str(), "bar");
4114
4115 let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
4116 let StepKind::Run(cmd) = &steps[0].kind else {
4117 panic!("expected Run, got {:?}", steps[0].kind);
4118 };
4119 assert!(
4120 cmd.as_str().contains("--foo=bar"),
4121 "unexpected RUN lowering: {cmd:?}"
4122 );
4123
4124 let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
4125 let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
4126 .expect("parses");
4127 let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
4128 panic!("expected AssertEq, got {:?}", steps[0].kind);
4129 };
4130 assert_eq!(hash.as_deref(), Some(digest));
4131
4132 let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
4134 let StepKind::Expand { path, overrides } = &steps[0].kind else {
4135 panic!("expected Expand, got {:?}", steps[0].kind);
4136 };
4137 assert!(path.is_none());
4138 assert_eq!(overrides.len(), 1);
4139 assert_eq!(overrides[0].0.as_str(), "--k");
4140 }
4141
4142 #[test]
4143 fn space_before_paren_is_not_a_call() {
4144 let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
4147 assert_eq!(steps.len(), 1);
4148 assert!(
4149 !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
4150 "space before paren must not route to a call: {:?}",
4151 steps[0].kind
4152 );
4153 }
4154
4155 #[test]
4156 fn unknown_type_tag_parses_as_custom() {
4157 let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
4161 let StepKind::Assign { decl_type, .. } = &steps[0].kind else {
4162 panic!("expected Assign, got {:?}", steps[0].kind);
4163 };
4164 assert_eq!(decl_type, "FOO");
4165 }
4166
4167 #[test]
4168 fn bare_for_without_types_is_rejected() {
4169 let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
4170 assert!(err.contains("FOR requires explicit types"), "{err}");
4171 }
4172
4173 #[test]
4174 fn mutate_statement_parses_without_keyword() {
4175 let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
4176 assert!(matches!(steps[0].kind, StepKind::Set { .. }));
4177 }
4178
4179 #[test]
4180 fn set_keyword_is_rejected_with_mutation_hint() {
4181 let err = parse_err("SET $y = 2\n");
4182 assert!(err.contains("not a keyword"), "{err}");
4183 assert!(err.contains("$var = <expr>"), "{err}");
4184 }
4185
4186 #[test]
4187 fn structural_fallthrough_commits_per_keyword() {
4188 for (script, cmd) in [
4189 ("CANCEL foo\n", "CANCEL"),
4190 ("TIMEOUT foo\n", "TIMEOUT"),
4191 ("FOR foo\n", "FOR"),
4192 ("IF foo\n", "IF"),
4193 ("LET foo\n", "LET"),
4194 ("ASYNC\n", "ASYNC"),
4198 ("ELSE foo\n", "ELSE"),
4199 ] {
4200 let err = parse_err(script);
4201 assert!(
4202 err.contains(&format!("invalid syntax for command {cmd}")),
4203 "{cmd}: {err}"
4204 );
4205 assert!(!err.contains("unknown command"), "{cmd}: {err}");
4206 }
4207 }
4208
4209 #[test]
4210 fn leaf_arity_errors_carry_invalid_syntax_prefix() {
4211 let err = parse_err("SLEEP 1s 2s\n");
4212 assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
4213 assert!(!err.contains("unknown command"), "{err}");
4214 }
4215
4216 #[test]
4217 fn list_append_lowers_variable_and_item() {
4218 let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
4219 let StepKind::ListAppend { list, item } = &steps[0].kind else {
4220 panic!("expected ListAppend, got {:?}", steps[0].kind);
4221 };
4222 assert_eq!(list, "items");
4223 assert!(matches!(item, Arg::String(s, _) if s == "hi"));
4224 assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
4225 }
4226
4227 #[test]
4228 fn list_append_rejects_wrong_arity() {
4229 for script in [
4230 "LIST_APPEND\n",
4231 "LIST_APPEND $items\n",
4232 "LIST_APPEND $items \"a\" \"b\"\n",
4233 ] {
4234 let err = parse_err(script);
4235 assert!(
4236 err.contains("invalid syntax for command LIST_APPEND"),
4237 "{script}: {err}"
4238 );
4239 assert!(!err.contains("unknown command"), "{script}: {err}");
4240 }
4241 }
4242
4243 #[test]
4244 fn list_append_rejects_non_variable_target() {
4245 let err = parse_err("LIST_APPEND items \"a\"\n");
4246 assert!(
4247 err.contains("invalid syntax for command LIST_APPEND"),
4248 "{err}"
4249 );
4250 assert!(!err.contains("unknown command"), "{err}");
4251 }
4252
4253 #[test]
4254 fn read_line_rejects_bare_word_target() {
4255 let err = parse_err("READ_LINE reply\n");
4259 assert!(err.contains("READ_LINE requires a $variable"), "{err}");
4260 assert!(!err.contains("unknown command"), "{err}");
4261 }
4262
4263 #[test]
4264 fn genuinely_unknown_command_keeps_bare_message() {
4265 let err = parse_err("FROBNICATE hi\n");
4266 assert!(err.contains("unknown command: FROBNICATE"), "{err}");
4267 assert!(!err.contains("did you mean"), "{err}");
4268 }
4269
4270 #[test]
4271 fn lowercase_command_suggests_uppercase() {
4272 let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
4276 .expect_err("must fail")
4277 .to_string();
4278 assert!(err.contains("unknown command: echo"), "{err}");
4279 assert!(err.contains("did you mean `ECHO`"), "{err}");
4280 }
4281
4282 #[test]
4283 fn func_def_requires_typed_uppercase_name() {
4284 let steps = parse_script(
4285 "FUNC GREET($name: STRING) {\n RETURN $name\n}\n",
4286 lower_command,
4287 )
4288 .expect("func def parses");
4289 let StepKind::FuncDef { name, params, body } = &steps[0].kind else {
4290 panic!("expected FuncDef, got {:?}", steps[0].kind);
4291 };
4292 assert_eq!(name, "GREET");
4293 assert_eq!(
4294 params,
4295 &vec![("name".to_string(), "STRING".to_string())],
4296 "{params:?}"
4297 );
4298 assert!(matches!(body[0].kind, StepKind::Return { .. }));
4299 }
4300
4301 #[test]
4302 fn lowercase_func_name_is_rejected() {
4303 let err = parse_err("FUNC greet($x: STRING) {\n RETURN $x\n}\n");
4304 assert!(err.contains("FUNC"), "{err}");
4305 }
4306
4307 #[test]
4308 fn call_and_while_lower_correctly() {
4309 let steps = parse_script(
4310 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nGREET(\"ada\")\n",
4311 lower_command,
4312 )
4313 .expect("call parses");
4314 assert!(
4315 matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
4316 "{:?}",
4317 steps[1].kind
4318 );
4319 let steps = parse_script(
4320 "FUNC GREET($a: STRING, $b: STRING) {\n RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
4321 lower_command,
4322 )
4323 .expect("spaced call parses");
4324 assert!(
4325 matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
4326 "{:?}",
4327 steps[1].kind
4328 );
4329 let steps = parse_script(
4330 indoc! {r#"
4331 WHILE !$done {
4332 BREAK
4333 }
4334 "#},
4335 lower_command,
4336 )
4337 .expect("while parses");
4338 let StepKind::While { body, .. } = &steps[0].kind else {
4339 panic!("expected While, got {:?}", steps[0].kind);
4340 };
4341 assert!(matches!(body[0].kind, StepKind::Break));
4342 }
4343
4344 #[test]
4345 fn let_capture_call_and_async_call_lower() {
4346 let steps = parse_script(
4349 indoc! {r#"
4350 FUNC GREET($name: STRING) {
4351 RETURN $name
4352 }
4353 LET $r: STRING = GREET("ada")
4354 "#},
4355 lower_command,
4356 )
4357 .expect("capture call parses");
4358 let StepKind::Assign { var, expr, .. } = &steps[1].kind else {
4359 panic!("expected Assign, got {:?}", steps[1].kind);
4360 };
4361 assert_eq!(var, "r");
4362 assert!(
4363 matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
4364 "{expr:?}"
4365 );
4366 let steps = parse_script(
4367 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nLET $t: HANDLE = ASYNC GREET(\"a\")\n",
4368 lower_command,
4369 )
4370 .expect("async call parses");
4371 assert!(
4372 matches!(&steps[1].kind, StepKind::AssignAsync { .. }),
4373 "{:?}",
4374 steps[1].kind
4375 );
4376 }
4377
4378 #[test]
4379 fn multiline_call_args_span_lines() {
4380 let steps = parse_script(
4384 "FUNC SERVE($b: STRING, $u: STRING, $p: STRING, $o: MAP) {\n RETURN $b\n}\nLET $m: MAP = SERVE(\n \"127.0.0.1:2241\",\n \"test\",\n \"test123\", {\n key_path: \"test_key\"\n }\n)\n",
4385 lower_command,
4386 )
4387 .expect("multiline call parses");
4388 let StepKind::Assign { expr, .. } = &steps[1].kind else {
4389 panic!("expected Assign, got {:?}", steps[1].kind);
4390 };
4391 let Expr::Call { name, args } = expr else {
4392 panic!("expected Call expr, got {expr:?}");
4393 };
4394 assert_eq!(name, "SCRIPT::SERVE");
4395 assert_eq!(args.len(), 4);
4396 assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
4397 let rendered = steps[1].to_string();
4399 assert!(!rendered.contains('\n'), "{rendered}");
4400 let script = "FUNC SERVE($b: STRING, $u: STRING, $p: STRING, $o: MAP) {\n RETURN $b\n}\nLET $m: MAP = SERVE(\n \"127.0.0.1:2241\",\n \"test\",\n \"test123\", {\n key_path: \"test_key\"\n }\n)\n";
4401 let again = parse_script(script, lower_command).expect("reparse ok");
4402 assert_eq!(again, steps);
4403 }
4404
4405 #[test]
4406 fn multiline_bare_call_and_list_span_lines() {
4407 let steps = parse_script(
4408 indoc! {r#"
4409 FUNC GREET($a: STRING) {
4410 RETURN $a
4411 }
4412 GREET(
4413 "ada"
4414 )
4415 "#},
4416 lower_command,
4417 )
4418 .expect("multiline bare call parses");
4419 let StepKind::Call { name, args } = &steps[1].kind else {
4420 panic!("expected Call, got {:?}", steps[1].kind);
4421 };
4422 assert_eq!(name, "SCRIPT::GREET");
4423 assert_eq!(args.len(), 1);
4424 let steps = parse_script(
4425 indoc! {r#"
4426 LET $l: LIST = [
4427 "a",
4428 "b"
4429 ]
4430 "#},
4431 lower_command,
4432 )
4433 .expect("multiline list parses");
4434 let StepKind::Assign { expr, .. } = &steps[0].kind else {
4435 panic!("expected Assign, got {:?}", steps[0].kind);
4436 };
4437 assert!(
4438 matches!(expr, Expr::List(items) if items.len() == 2),
4439 "{expr:?}"
4440 );
4441 }
4442
4443 #[test]
4444 fn parse_duration_units() {
4445 use std::time::Duration;
4446 assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4447 assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
4448 assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
4449 assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4450 assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
4451 assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
4453 assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
4454 }
4455
4456 #[test]
4457 fn parse_duration_rejects_garbage() {
4458 assert!(parse_duration("").is_err());
4459 assert!(parse_duration("banana").is_err());
4460 assert!(parse_duration("10x").is_err());
4461 assert!(parse_duration("0s").is_err());
4462 assert!(parse_duration("0").is_err());
4463 assert!(parse_duration("-5s").is_err());
4464 assert!(parse_duration("30 s s").is_err());
4466 assert!(parse_duration("3 0s").is_err());
4467 }
4468
4469 #[test]
4470 fn parse_byte_count_units() {
4471 assert_eq!(parse_byte_count("500").unwrap(), 500);
4472 assert_eq!(parse_byte_count("500B").unwrap(), 500);
4473 assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
4474 assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
4475 assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
4476 assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
4477 assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
4478 assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
4479 assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
4480 assert_eq!(
4481 parse_byte_count("1TIB").unwrap(),
4482 1_024 * 1_024 * 1_024 * 1_024
4483 );
4484 assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
4486 assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
4487 assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
4488 assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
4489 assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
4491 assert_eq!(
4492 parse_byte_count("1_000_000_000_000").unwrap(),
4493 1_000_000_000_000
4494 );
4495 assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
4496 assert_eq!(
4497 parse_byte_count("1_0GiB").unwrap(),
4498 10 * 1_024 * 1_024 * 1_024
4499 );
4500 assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
4502 assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
4503 assert_eq!(parse_byte_count(" 2MB ").unwrap(), 2_000_000);
4504 assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
4506 assert!(parse_byte_count("-1 GB").is_err());
4507 }
4508
4509 #[test]
4510 fn parse_byte_count_rejects_garbage() {
4511 for bad in [
4512 "",
4513 "banana",
4514 "10x",
4515 "1G",
4516 "1K",
4517 "1.5GB",
4518 "-5",
4519 "-5GB",
4520 "0",
4521 "0GB",
4522 "_100",
4523 "100_",
4524 "1__000",
4525 "_",
4526 "1_GB",
4527 "1 G B",
4529 "1 2",
4530 "1 0",
4531 "1000000000000000000000000",
4533 "1000000000TB",
4534 ] {
4535 assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
4536 }
4537 }
4538
4539 #[test]
4540 fn format_byte_count_round_trips() {
4541 for text in [
4542 "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
4543 ] {
4544 let parsed = parse_byte_count(text).unwrap();
4545 let rendered = format_byte_count(parsed);
4546 assert_eq!(
4547 parse_byte_count(&rendered).unwrap(),
4548 parsed,
4549 "round-trip failed for {text}"
4550 );
4551 }
4552 assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
4553 assert_eq!(format_byte_count(1_000_000_000), "1GB");
4554 }
4555
4556 #[test]
4557 fn strip_digit_separators_passes_signs_through() {
4558 assert_eq!(strip_digit_separators("-1_000"), "-1000");
4562 assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
4563 assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
4564 assert_eq!(strip_digit_separators("1_000"), "1000");
4565 for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
4566 assert_eq!(strip_digit_separators(untouched), untouched);
4567 }
4568 assert!(parse_byte_count("-1_000").is_err());
4571 assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
4572 }
4573
4574 #[test]
4575 fn format_byte_count_is_lossless() {
4576 for n in [
4581 1,
4582 500,
4583 999,
4584 1_000,
4585 1_024,
4586 1_500,
4587 1_000_000,
4588 1_048_576,
4589 1_000_000_000,
4590 1_073_741_824,
4591 1_000_000_000_000,
4592 1_099_511_627_776,
4593 u64::MAX,
4594 ] {
4595 assert_eq!(
4596 parse_byte_count(&format_byte_count(n)).unwrap(),
4597 n,
4598 "lossless round-trip failed for {n}"
4599 );
4600 }
4601 }
4602
4603 #[test]
4604 fn format_duration_round_trips() {
4605 for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
4606 let parsed = parse_duration(text).unwrap();
4607 let rendered = format_duration(&parsed);
4608 assert_eq!(
4609 parse_duration(&rendered).unwrap(),
4610 parsed,
4611 "round-trip failed for {text}"
4612 );
4613 }
4614 assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
4615 assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
4616 }
4617
4618 #[test]
4619 fn structural_metadata_covers_all_structural_kinds() {
4620 use crate::ast::Value;
4621
4622 fn metadata_name(kind: &StepKind) -> Option<&'static str> {
4626 match kind {
4627 StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some("WITH_IO"),
4628 StepKind::For { .. } => Some("FOR"),
4629 StepKind::If { .. } => Some("IF"),
4630 StepKind::Assign { .. } => Some("LET"),
4631 StepKind::Set { .. } => Some("MUTATION"),
4632 StepKind::AssignCapture { .. } => Some("LET"),
4633 StepKind::AwaitCapture { .. } => Some("AWAIT"),
4634 StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => Some("ASYNC"),
4635 StepKind::Await { .. } => Some("AWAIT"),
4636 StepKind::Cancel { .. } => Some("CANCEL"),
4637 StepKind::Timeout { .. } => Some("TIMEOUT"),
4638 StepKind::Isolated { .. } => Some("ISOLATED"),
4639 StepKind::IsolatedInheritEnv { .. } => Some("ISOLATED"),
4640 StepKind::RemoteBlock { .. } => Some("REMOTE"),
4641 StepKind::FuncDef { .. } => Some("FUNC"),
4642 StepKind::Call { .. } => None,
4645 StepKind::Return { .. } => Some("RETURN"),
4646 StepKind::While { .. } => Some("WHILE"),
4647 StepKind::Break => Some("BREAK"),
4648 StepKind::Continue => Some("CONTINUE"),
4649 StepKind::TypeAlias { .. } => Some("LET"),
4653 StepKind::RunExec { .. } => None,
4654 StepKind::Workdir(_)
4655 | StepKind::Workspace(_)
4656 | StepKind::Env { .. }
4657 | StepKind::InheritEnv { .. }
4658 | StepKind::Run(_)
4659 | StepKind::Echo(_)
4660 | StepKind::Copy { .. }
4661 | StepKind::Symlink { .. }
4662 | StepKind::Mkdir(_)
4663 | StepKind::Archive { .. }
4664 | StepKind::Unarchive { .. }
4665 | StepKind::Install { .. }
4666 | StepKind::Ls(_)
4667 | StepKind::Cwd
4668 | StepKind::Read(_)
4669 | StepKind::ReadLine { .. }
4670 | StepKind::Prompt { .. }
4671 | StepKind::Write { .. }
4672 | StepKind::Append { .. }
4673 | StepKind::Remove { .. }
4674 | StepKind::Expand { .. }
4675 | StepKind::AssertEq { .. }
4676 | StepKind::AssertContains { .. }
4677 | StepKind::CopyGit { .. }
4678 | StepKind::HashSha256 { .. }
4679 | StepKind::Exit(_)
4680 | StepKind::Sleep { .. }
4681 | StepKind::ListAppend { .. } => None,
4682 }
4683 }
4684
4685 let dummies: Vec<StepKind> = vec![
4688 StepKind::WithIo {
4689 bindings: Vec::new(),
4690 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
4691 "x".to_string(),
4692 false,
4693 ))),
4694 },
4695 StepKind::For {
4696 key_var: None,
4697 key_type: None,
4698 var: "i".to_string(),
4699 var_type: "STRING".to_string(),
4700 in_expr: Expr::Literal(Value::bool(true)),
4701 body: Vec::new(),
4702 },
4703 StepKind::If {
4704 cond: Box::new(Expr::Literal(Value::bool(true))),
4705 then_body: Vec::new(),
4706 else_ifs: Vec::new(),
4707 else_body: None,
4708 },
4709 StepKind::Assign {
4710 var: "v".to_string(),
4711 decl_type: "BOOL".to_string(),
4712 expr: Expr::Literal(Value::bool(true)),
4713 },
4714 StepKind::Set {
4715 var: "v".to_string(),
4716 expr: Expr::Literal(Value::bool(true)),
4717 },
4718 StepKind::AssignCapture {
4719 var: "v".to_string(),
4720 decl_type: "STRING".to_string(),
4721 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
4722 "x".to_string(),
4723 false,
4724 ))),
4725 },
4726 StepKind::AwaitCapture {
4727 out_var: "o".to_string(),
4728 out_type: "STRING".to_string(),
4729 task_var: "t".to_string(),
4730 },
4731 StepKind::AsyncBlock { body: Vec::new() },
4732 StepKind::AssignAsync {
4733 var: "t".to_string(),
4734 decl_type: "HANDLE".to_string(),
4735 body: Vec::new(),
4736 },
4737 StepKind::Await {
4738 var: "t".to_string(),
4739 },
4740 StepKind::Cancel {
4741 var: "t".to_string(),
4742 },
4743 StepKind::Timeout {
4744 duration: Arg::String("1s".to_string(), false),
4745 body: Vec::new(),
4746 },
4747 StepKind::Isolated { body: Vec::new() },
4748 StepKind::IsolatedInheritEnv { keys: Vec::new() },
4749 StepKind::RemoteBlock {
4750 target: "prod".to_string(),
4751 vars: Vec::new(),
4752 env: Vec::new(),
4753 body: Vec::new(),
4754 },
4755 StepKind::FuncDef {
4756 name: "F".to_string(),
4757 params: Vec::new(),
4758 body: Vec::new(),
4759 },
4760 StepKind::Call {
4761 name: "F".to_string(),
4762 args: Vec::new(),
4763 },
4764 StepKind::Return {
4765 expr: Box::new(Expr::Literal(Value::bool(true))),
4766 },
4767 StepKind::While {
4768 cond: Box::new(Expr::Literal(Value::bool(true))),
4769 body: Vec::new(),
4770 },
4771 StepKind::Break,
4772 StepKind::Continue,
4773 StepKind::TypeAlias {
4774 name: "PERSON".to_string(),
4775 target: "MAP<name: STRING>".to_string(),
4776 },
4777 ];
4778 let registry = all_structural_metadata();
4779 for kind in &dummies {
4780 let Some(name) = metadata_name(kind) else {
4782 continue;
4783 };
4784 assert!(
4785 registry.iter().any(|meta| meta.name == name),
4786 "no structural metadata entry for {}",
4787 name
4788 );
4789 }
4790 }
4791}