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 # A redirected stdin can never answer: without a default the
1605 # prompt fails instead of hanging or reading piped stdin.
1606 LET $p: PIPE
1607 WITH_IO [stdin=$p] PROMPT $dir "Install destination?"
1608 "#} } ],
1609 lower: |_flags, args| {
1610 let mut it = args.into_iter();
1611 let var_arg = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))?;
1612 let var = match var_arg {
1613 Arg::Expr(Expr::Var(name)) => name,
1614 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1615 other => return Err(ParseError::validation("PROMPT", format!("PROMPT requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1616 };
1617 if var.is_empty() {
1618 return Err(ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))
1619 }
1620 let message = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a message".to_string(), &SpanContext::line_only(0)))?;
1621 let default = it.next();
1622 Ok(StepKind::Prompt { var, message, default })
1623 },
1624 ],
1625
1626 Write => [
1627 name: "WRITE",
1628 variant: Write { path: Arg, contents: Option<Arg> },
1629 syntax: "WRITE <path> [<contents>]",
1630 summary: "Write to file.",
1631 description: "Writes contents.",
1632 args: &[
1633 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1634 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1635 ],
1636 flags: &[],
1637 default_output: None,
1638 examples: &[ Example { name: "write", fence_meta: None, code: indoc! {r#"
1639 WRITE output.txt hello-world
1640 LET $body: STRING = READ output.txt
1641 ASSERT_EQ $body "hello-world"
1642 "#} } ],
1643 lower: |_flags, args| {
1644 let mut it = args.into_iter();
1645 let path = it.next().ok_or_else(|| ParseError::validation("WRITE", "WRITE requires a path".to_string(), &SpanContext::line_only(0)))?;
1646 let remaining: Vec<Arg> = it.collect();
1647 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "WRITE")?) };
1648 Ok(StepKind::Write { path, contents })
1649 },
1650 ],
1651
1652 Append => [
1653 name: "APPEND",
1654 variant: Append { path: Arg, contents: Option<Arg> },
1655 syntax: "APPEND <path> [<contents>]",
1656 summary: "Append to file.",
1657 description: "Appends contents.",
1658 args: &[
1659 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1660 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1661 ],
1662 flags: &[],
1663 default_output: None,
1664 examples: &[ Example { name: "append", fence_meta: None, code: indoc! {r#"
1665 WRITE log.txt line1
1666 APPEND log.txt line2
1667
1668 # APPEND concatenates with no separator.
1669 LET $all: STRING = READ log.txt
1670 ASSERT_EQ $all "line1line2"
1671 "#} } ],
1672 lower: |_flags, args| {
1673 let mut it = args.into_iter();
1674 let path = it.next().ok_or_else(|| ParseError::validation("APPEND", "APPEND requires a path".to_string(), &SpanContext::line_only(0)))?;
1675 let remaining: Vec<Arg> = it.collect();
1676 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "APPEND")?) };
1677 Ok(StepKind::Append { path, contents })
1678 },
1679 ],
1680
1681 Remove => [
1682 name: "REMOVE",
1683 variant: Remove { path: Arg, recursive: bool },
1684 syntax: "REMOVE [--recursive] <path>",
1685 summary: "Remove a file, symlink, or directory.",
1686 description: "Removes a file, symlink (the link itself), or empty dir. With --recursive removes a directory tree.",
1687 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Path to remove", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1688 flags: &[ FlagSpec { name: "recursive", long: "--recursive", value_type: FlagValueType::Flag, required: false, description: "Remove a directory tree" } ],
1689 default_output: None,
1690 examples: &[ Example { name: "remove", fence_meta: None, code: indoc! {r#"
1691 # WRITE then REMOVE leaves nothing behind.
1692 IMPORT [STD]
1693 WRITE scratch.txt content
1694
1695 # Assert original file is written
1696 LET $o: STRING = PATH_TYPE("scratch.txt")
1697 ASSERT_EQ $o "file"
1698
1699 REMOVE scratch.txt
1700
1701 # Assert file has been removed
1702 LET $t: STRING = PATH_TYPE("scratch.txt")
1703 ASSERT_EQ $t "absent"
1704 "#} } ],
1705 lower: |flags, args| {
1706 let recursive = flags.iter().any(|(k, _)| k == "recursive");
1707 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("REMOVE", "REMOVE requires a path".to_string(), &SpanContext::line_only(0)))?;
1708 Ok(StepKind::Remove { path, recursive })
1709 },
1710 ],
1711
1712 Expand => [
1713 name: "EXPAND",
1714 variant: Expand { path: Option<Arg>, overrides: Vec<(String, Arg)> },
1715 syntax: "EXPAND [<path>] [<KEY=val> ...]",
1716 summary: "Expand a template file (or stdin) to stdout.",
1717 description: indoc! {r#"
1718 A template is any text file — or piped stdin when no path is given —
1719 containing `{{ ... }}` placeholders. EXPAND replaces each placeholder
1720 and prints the result to stdout.
1721
1722 Placeholders: `{{ NAME }}` reads a `KEY=val` override passed on this
1723 command; `{{ env:NAME }}` reads an override, falling back to the
1724 environment; `{{ $var }}` reads a script variable (dotted paths allowed).
1725 A missing key is an error, never a silent empty.
1726
1727 Calls: `{{ MODULE::FUNC(args) }}` invokes a pure registry function
1728 with `$var.path` references and `STRING`, `INT`, `FLOAT`, and `BOOL`
1729 literals as arguments. Only pure functions resolve here: stateful,
1730 script-defined, and pipe-backed entries fail naming themselves,
1731 since placeholder evaluation carries no step context. The same
1732 calls resolve in ordinary strings, so both paths agree.
1733
1734 Substitution runs in a single pass. `EXPAND` is not recursive and does not
1735 expand nested placeholders: a value that itself contains `{{ ... }}` is
1736 inserted verbatim and never expanded again.
1737
1738 A bare `$var` argument is a template path; `KEY=val` arguments are
1739 overrides whose values follow the unified string-value rules (same as
1740 `ENV`: quotes keep exact bytes, a lone `$var` evaluates,
1741 `{{ ... }}` interpolates).
1742
1743 NOTE: `WRITE` interpolates `{{ ... }}` while writing, so escape it
1744 (`\{{ ... }}`) when writing a template file for a later `EXPAND`.
1745
1746 With no path, the template arrives on stdin through a pipe. When piping
1747 from a shell, single-quote the template (`echo '{{ $x }}'`): double
1748 quotes let the shell swallow `$x`, so oxdock receives an empty `{{ }}`
1749 placeholder and errors.
1750 "#},
1751 args: &[
1752 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 },
1753 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 },
1754 ],
1755 flags: &[],
1756 default_output: Some(Stream::Stdout),
1757 examples: &[
1758 Example { name: "expand", fence_meta: None, code: indoc! {r#"
1759 # Placeholders read overrides first, then the environment.
1760 ENV NAME="Alice"
1761 WRITE template.md "Hello {{ env:NAME }}!"
1762 EXPAND template.md
1763
1764 ASSERT_CONTAINS stdout "Hello Alice!"
1765 "#} },
1766 Example { name: "override with spaces", fence_meta: None, code: indoc! {r#"
1767 # WRITE would interpolate {{ }} right away, so escape it.
1768 # The file must literally contain {{ env:NAME }} for EXPAND.
1769 WRITE template.md "Hello \{{ env:NAME }}!"
1770 EXPAND template.md NAME="Alice Smith"
1771
1772 ASSERT_CONTAINS stdout "Hello Alice Smith!"
1773 "#} },
1774 Example { name: "variable override", fence_meta: None, code: indoc! {r#"
1775 # Same escaping: keep the placeholder literal until EXPAND.
1776 # A lone $who evaluates, like ECHO $who.
1777 LET $who: STRING = "Bob"
1778 WRITE template.md "Hi \{{ env:WHO }}!"
1779 EXPAND template.md WHO=$who
1780
1781 ASSERT_CONTAINS stdout "Hi Bob!"
1782 "#} },
1783 Example { name: "override forms agree", fence_meta: None, code: indoc! {r#"
1784 # A bare variable and a template-with-tail expand identically.
1785 LET $x: STRING = "Ada"
1786 WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
1787 EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"
1788
1789 ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"
1790 "#} },
1791 Example { name: "expand stdin", fence_meta: None, code: indoc! {r#"
1792 # No path: the template arrives on stdin through a pipe.
1793 LET $tpl: PIPE
1794 WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
1795 WITH_IO [stdin=$tpl] EXPAND NAME=Alice
1796
1797 ASSERT_CONTAINS stdout "Hello Alice!"
1798 "#} },
1799 Example { name: "override does not leak", fence_meta: None, code: indoc! {r#"
1800 # KEY=val overrides shadow env for that EXPAND only.
1801 # They never update the environment itself.
1802 ENV NAME="Alice"
1803 WRITE template.md "Hi \{{ env:NAME }}!"
1804
1805 EXPAND template.md NAME="Bob"
1806 ASSERT_CONTAINS stdout "Hi Bob!"
1807
1808 EXPAND template.md
1809 ASSERT_CONTAINS stdout "Hi Alice!"
1810 "#} },
1811 Example { name: "function call", fence_meta: None, code: indoc! {r#"
1812 # Pure registry functions run inside placeholders.
1813 # WRITE would interpolate {{ }} right away, so escape it.
1814 IMPORT [STD]
1815 WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"
1816
1817 EXPAND template.md
1818 ASSERT_CONTAINS stdout "Count: 2!"
1819 "#} },
1820 ],
1821 lower: |_flags, args| {
1822 let mut path = None;
1823 let mut overrides = Vec::new();
1824 for arg in args {
1825 let text = arg.as_str();
1826 if let Some((key, value)) = split_assignment(text).map_err(|e| ParseError::validation("EXPAND", e.to_string(), &SpanContext::line_only(0)))? {
1827 overrides.push((key, value));
1828 } else if path.is_none() { path = Some(arg); }
1829 else { return Err(ParseError::validation("EXPAND", "EXPAND accepts at most one path".to_string(), &SpanContext::line_only(0))) }
1830 }
1831 Ok(StepKind::Expand { path, overrides })
1832 },
1833 ],
1834
1835 AssertEq => [
1836 name: "ASSERT_EQ",
1837 variant: AssertEq { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
1838 syntax: "ASSERT_EQ <actual> <expected> | ASSERT_EQ --hash <sha256> <actual>",
1839 summary: "Assert strict equality.",
1840 description: indoc! {r#"
1841 Compares two evaluated values with typed equality (no coercion:
1842 `INT(42)` never equals `STRING("42")`), aborting the pipeline
1843 with a step-numbered error showing expected vs actual otherwise.
1844
1845 Both sides are values: `$var`, literals, templates, and calls
1846 evaluate in memory and never touch disk. Read files explicitly
1847 first (`LET $text: STRING = READ "out.txt"`, then
1848 `ASSERT_EQ $text ...`).
1849 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1850 holding a `PIPE` observes its backend bytes. `--hash` compares
1851 the SHA-256 of a string, pipe, or captured-stdout actual
1852 instead of the raw bytes (`stderr` is unsupported).
1853 "#},
1854 args: &[
1855 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 },
1856 ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Expected (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
1857 ],
1858 flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
1859 default_output: None,
1860 examples: &[ Example { name: "assert eq", fence_meta: None, code: indoc! {r#"
1861 LET $status: INT = 200
1862 ASSERT_EQ $status 200
1863 "#} },
1864 Example { name: "assert eq file", fence_meta: None, code: indoc! {r#"
1865 WRITE payload.bin stable-content
1866 LET $body: STRING = READ payload.bin
1867 ASSERT_EQ $body "stable-content"
1868 "#} },
1869 Example { name: "assert eq hash", fence_meta: None, code: indoc! {r#"
1870 # --hash compares the SHA-256 digest instead of raw bytes.
1871 WRITE payload.bin stable-content
1872 LET $body: STRING = READ payload.bin
1873 ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body
1874 "#} } ],
1875 lower: |flags, args| {
1876 let hash = flags.iter().find(|(k, _)| k == "hash").map(|(_, v)| v.as_str().to_string());
1877 let mut it = args.into_iter();
1878 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)))?)?;
1879 let remaining: Vec<Arg> = it
1880 .map(lower_assert_operand)
1881 .collect::<Vec<Arg>>();
1882 let expected = if remaining.is_empty() {
1885 if hash.is_some() {
1886 None
1887 } else {
1888 return Err(ParseError::validation("ASSERT_EQ", "ASSERT_EQ requires an expected value".to_string(), &SpanContext::line_only(0)))
1889 }
1890 } else {
1891 Some(join_value(remaining, "ASSERT_EQ")?)
1892 };
1893 Ok(StepKind::AssertEq { hash, actual, expected })
1894 },
1895 ],
1896
1897 AssertContains => [
1898 name: "ASSERT_CONTAINS",
1899 variant: AssertContains { haystack: AssertTarget, needle: Arg },
1900 syntax: "ASSERT_CONTAINS <haystack> <needle>",
1901 summary: "Assert containment.",
1902 description: indoc! {r#"
1903 Checks containment and aborts the pipeline with a step-numbered
1904 error otherwise: substring for strings, element match for lists,
1905 key presence for maps, substring over stream and pipe buffers.
1906
1907 Like `ASSERT_EQ`, both sides are values read without implicit
1908 I/O; read files explicitly first
1909 (`LET $text: STRING = READ "cfg.txt"`).
1910 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1911 holding a `PIPE` observes its backend bytes.
1912 "#},
1913 args: &[
1914 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 },
1915 ArgSpec { name: "needle", arg_type: ArgType::Rest(&ArgType::Any), description: "Substring, element, or key", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1916 ],
1917 flags: &[],
1918 default_output: None,
1919 examples: &[ Example { name: "assert contains", fence_meta: None, code: indoc! {r#"
1920 ECHO build-complete
1921 ASSERT_CONTAINS stdout "build-complete"
1922 "#} } ],
1923 lower: |flags, args| {
1924 let _ = flags;
1925 let mut it = args.into_iter();
1926 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)))?)?;
1927 let remaining: Vec<Arg> = it
1928 .map(lower_assert_operand)
1929 .collect::<Vec<Arg>>();
1930 if remaining.is_empty() {
1931 return Err(ParseError::validation("ASSERT_CONTAINS", "ASSERT_CONTAINS requires a needle".to_string(), &SpanContext::line_only(0)))
1932 }
1933 let needle = join_value(remaining, "ASSERT_CONTAINS")?;
1934 Ok(StepKind::AssertContains { haystack, needle })
1935 },
1936 ],
1937
1938 HashSha256 => [
1939 name: "HASH_SHA256",
1940 variant: HashSha256 { path: Arg },
1941 syntax: "HASH_SHA256 <path>",
1942 summary: "Print SHA-256.",
1943 description: "Computes digest.",
1944 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: true, fallback_stream: None } ],
1945 flags: &[],
1946 default_output: Some(Stream::Stdout),
1947 examples: &[ Example { name: "hash", fence_meta: None, code: indoc! {r#"
1948 WRITE payload.txt hello
1949 HASH_SHA256 payload.txt
1950
1951 LET $digest: STRING = HASH_SHA256 payload.txt
1952 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\n"
1953 "#} } ],
1954 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)))? }),
1955 ],
1956
1957 Exit => [
1958 name: "EXIT",
1959 variant: Exit(Arg),
1960 syntax: "EXIT <code>",
1961 summary: "Exit pipeline.",
1962 description: indoc! {r#"
1963 Stops the pipeline immediately with an `EXIT requested with code <code>`
1964 error; steps after it never run, at any nesting depth.
1965
1966 Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state,
1967 anonymous background tasks are killed synchronously, and files written
1968 before the EXIT persist.
1969
1970 The code reaches the OS: the CLI exits with `<code>` clamped to
1971 0..=255, and a guest EXIT relays through `REMOTE` the same way.
1972 "#},
1973 args: &[ ArgSpec { name: "code", arg_type: ArgType::Int, description: "Code", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1974 flags: &[],
1975 default_output: None,
1976 examples: &[ Example { name: "exit", fence_meta: Some("expect_error:\"EXIT requested with code 0\""), code: indoc! {r#"EXIT 0"#} } ],
1977 lower: |_flags, args| {
1978 let code = args.into_iter().next().ok_or_else(|| ParseError::validation("EXIT", "EXIT requires a code".to_string(), &SpanContext::line_only(0)))?;
1981 Ok(StepKind::Exit(code))
1982 },
1983 ],
1984
1985 Sleep => [
1986 name: "SLEEP",
1987 variant: Sleep { duration: Arg },
1988 syntax: "SLEEP <duration>",
1989 summary: "Pause execution for a duration.",
1990 description: indoc! {r#"
1991 Parks the step for the duration (e.g. 500ms, 10s, 2m).
1992
1993 Cooperative: checks for cancellation so an enclosing TIMEOUT or task
1994 teardown interrupts the sleep. Cross-platform alternative to shell sleep
1995 for testing time boundaries.
1996 "#},
1997 args: &[ ArgSpec { name: "duration", arg_type: ArgType::Duration, description: "How long to sleep", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1998 flags: &[],
1999 default_output: None,
2000 examples: &[
2001 Example { name: "sleep", fence_meta: None, code: indoc! {r#"SLEEP 100ms"#} },
2002 Example {
2003 name: "sleep variable duration",
2004 fence_meta: None,
2005 code: indoc! {r#"
2006 # Durations resolve at runtime, so variables work too:
2007 # quoted or bare, both bind the same string.
2008 LET $pause: STRING = "100ms"
2009 SLEEP $pause
2010
2011 LET $bare: STRING = 100ms
2012 SLEEP $bare
2013 "#},
2014 },
2015 ],
2016 lower: |_flags, args| {
2017 let mut it = args.into_iter();
2018 let raw = it
2019 .next()
2020 .ok_or_else(|| ParseError::validation("SLEEP", "SLEEP requires a duration (e.g. SLEEP 500ms)".to_string(), &SpanContext::line_only(0)))?;
2021 if it.next().is_some() {
2022 return Err(ParseError::validation("SLEEP", "SLEEP takes exactly one duration argument".to_string(), &SpanContext::line_only(0)))
2023 }
2024 Ok(StepKind::Sleep { duration: raw })
2027 },
2028 ],
2029
2030 ListAppend => [
2031 name: "LIST_APPEND",
2032 variant: ListAppend { list: String, item: Arg },
2033 syntax: "LIST_APPEND $list <item>",
2034 summary: "Append an item to a LIST variable in place.",
2035 description: indoc! {r#"
2036 Appends the item to the LIST variable in place.
2037
2038 When the binding holds the only reference the push runs in
2039 amortized constant time. Aliased buffers detach first, so
2040 other holders keep their contents.
2041 "#},
2042 args: &[
2043 ArgSpec { name: "list", arg_type: ArgType::List, description: "Target LIST variable (`$name`)", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2044 ArgSpec { name: "item", arg_type: ArgType::Any, description: "Item to append (any value)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
2045 ],
2046 flags: &[],
2047 default_output: None,
2048 examples: &[ Example { name: "list append", fence_meta: None, code: indoc! {r#"
2049 # Appends accumulate in order.
2050 LET $items: LIST<STRING> = []
2051 LIST_APPEND $items "first"
2052 LIST_APPEND $items "second"
2053
2054 LET $want: LIST<STRING> = ["first", "second"]
2055 ASSERT_EQ $items $want
2056 "#} } ],
2057 lower: |_flags, args| {
2058 let mut it = args.into_iter();
2059 let raw_list = it
2060 .next()
2061 .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)))?;
2062 let list = match raw_list {
2063 Arg::Expr(Expr::Var(name)) => name,
2064 Arg::String(s, _) => s.trim_start_matches('$').to_string(),
2065 other => return Err(ParseError::validation("LIST_APPEND", format!("LIST_APPEND requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2066 };
2067 if list.is_empty() {
2068 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))
2069 }
2070 let item = it
2071 .next()
2072 .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)))?;
2073 if it.next().is_some() {
2074 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>".to_string(), &SpanContext::line_only(0)))
2075 }
2076 Ok(StepKind::ListAppend { list, item })
2077 },
2078 ],
2079}
2080
2081pub fn all_structural_metadata() -> Vec<CommandMeta> {
2089 vec![
2090 CommandMeta {
2091 name: "WITH_IO",
2092 syntax: "WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> }",
2093 summary: "Reroute standard streams.",
2094 description: indoc! {r#"
2095 Reroutes the standard streams of the next command or, in block form,
2096 of every enclosed command.
2097
2098 Bindings map streams (`stdin`, `stdout`, `stderr`) to a PIPE-typed
2099 variable (`stdout=$p`, `stdin=$p`), resolved from the variable
2100 when the step runs. Both stdout and stderr pipes capture output
2101 the same way. Declare the handle first with `LET $p: PIPE`.
2102
2103 Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a
2104 producer can finish before the consumer starts.
2105
2106 If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or
2107 not, the pipe is a zero copy OS kernel pipe instead: pair it with a
2108 consumer that runs while the producer is alive, since output past the
2109 64 KiB kernel buffer stalls until drained. That promotion never crosses
2110 a function boundary: pipes created, bound, or passed by variable inside FUNC
2111 bodies are always script pipes, even when the surrounding task would
2112 otherwise promote.
2113
2114 A second producer or consumer on a live handle is an explicit
2115 error. A handle bound as output can later feed another
2116 command's `stdin`, connecting commands without touching the
2117 terminal. Binding `stdout` and `stderr` to the same live
2118 handle fails deterministically. Merge streams in shell
2119 via `2>&1` instead.
2120
2121 Nested blocks stack defaults; inline bindings override inherited ones for
2122 their command only; closing a block restores previous wiring.
2123 "#},
2124 args: &[],
2125 flags: &[],
2126 default_output: None,
2127 examples: &[
2128 Example {
2129 name: "with_io block",
2130 fence_meta: None,
2131 code: indoc! {r#"
2132 LET $log: PIPE
2133 WITH_IO [stdout=$log] {
2134 ECHO first
2135 ECHO second
2136 }
2137 WITH_IO [stdin=$log] WRITE captured.txt
2138
2139 # The piped bytes landed in the file.
2140 LET $body: STRING = READ captured.txt
2141 ASSERT_CONTAINS $body "first"
2142 ASSERT_CONTAINS $body "second"
2143 "#},
2144 },
2145 Example {
2146 name: "variable pipe binding",
2147 fence_meta: None,
2148 code: indoc! {r#"
2149 # Declare the pipe first: `LET $p: PIPE` mints a fresh
2150 # backend without touching a stream. A plain string here
2151 # would be a TypeMismatch.
2152 LET $p: PIPE
2153 WITH_IO [stdout=$p] ECHO hello
2154 WITH_IO [stdin=$p] READ_LINE $line
2155 ASSERT_EQ $line "hello"
2156 "#},
2157 },
2158 ],
2159 },
2160 CommandMeta {
2161 name: "FOR",
2162 syntax: "FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }",
2163 summary: "Iterate over a list or map.",
2164 description: indoc! {r#"
2165 The loop variable receives each element (lists) or value (maps); with
2166 two variables, the first receives the key.
2167
2168 Loop variables are declared with explicit types and scoped per iteration;
2169 they do not leak outward. The body may be a braced block
2170 or a single-line `{ ... }` command.
2171
2172 `GLOB("...")` patterns must be quoted (`*` is not a bare word, so
2173 `GLOB(*)` is a parse error); GLOB returns a root-relative sorted list,
2174 empty when nothing matches, and rejects `..` escapes.
2175 "#},
2176 args: &[],
2177 flags: &[],
2178 default_output: None,
2179 examples: &[
2180 Example {
2181 name: "for loop",
2182 fence_meta: None,
2183 code: indoc! {r#"
2184 # Each element binds in turn; the loop body sees every one.
2185 LET $items: LIST<STRING> = ["a", "b"]
2186 FOR $item: STRING IN $items {
2187 ECHO $item
2188 }
2189 ASSERT_CONTAINS stdout "a"
2190 ASSERT_CONTAINS stdout "b"
2191
2192 # Key and value bind together for maps.
2193 LET $map: MAP<x: INT> = {"x": 1}
2194 FOR $k: STRING, $v: INT IN $map {
2195 ECHO "{{ $k }}={{ $v }}"
2196 }
2197 ASSERT_CONTAINS stdout "x=1"
2198 "#},
2199 },
2200 Example {
2201 name: "expand every match",
2202 fence_meta: None,
2203 code: indoc! {r#"
2204 # Single-line body; $x is a template path, WHO an override.
2205 IMPORT [STD]
2206 WRITE a.txt "hi \{{ env:WHO }}!"
2207 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
2208
2209 ASSERT_CONTAINS stdout "hi World!"
2210 "#},
2211 },
2212 ],
2213 },
2214 CommandMeta {
2215 name: "IF",
2216 syntax: "IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]",
2217 summary: "Conditional execution.",
2218 description: indoc! {r#"
2219 The condition is evaluated as a boolean expression.
2220
2221 Prefix `!` negates (`IF !false`); `&&` binds tighter than
2222 `||`, and both short-circuit, so `IF true || $missing`
2223 never evaluates the right side. Only Bool values are
2224 accepted as conditions.
2225 "#},
2226 args: &[],
2227 flags: &[],
2228 default_output: None,
2229 examples: &[
2230 Example {
2231 name: "if else",
2232 fence_meta: None,
2233 code: indoc! {r#"
2234 IMPORT [STD]
2235
2236 # True branch runs; the false branch is skipped.
2237 IF true {
2238 WRITE yes.txt taken
2239 } ELSE {
2240 WRITE yes.txt skipped
2241 }
2242
2243 # ELSE IF selects the first true branch.
2244 IF false {
2245 WRITE skipped.txt no
2246 } ELSE IF true {
2247 WRITE fallback.txt taken
2248 }
2249
2250 # !false evaluates to true, so this branch runs.
2251 IF !false {
2252 WRITE negated.txt taken
2253 }
2254
2255 LET $yes_body: STRING = READ yes.txt
2256 LET $fallback_body: STRING = READ fallback.txt
2257 LET $negated_body: STRING = READ negated.txt
2258 ASSERT_EQ $yes_body "taken"
2259 ASSERT_EQ $fallback_body "taken"
2260 ASSERT_EQ $negated_body "taken"
2261 LET $t: STRING = PATH_TYPE("skipped.txt")
2262 ASSERT_EQ $t "absent"
2263 "#},
2264 },
2265 Example {
2266 name: "logical condition composition",
2267 fence_meta: None,
2268 code: indoc! {r#"
2269 IMPORT [STD]
2270 LET $role: STRING = "admin"
2271 LET $level: INT = 3
2272
2273 # || is true when either side holds; && needs both.
2274 IF $role == "owner" || $level >= 5 {
2275 WRITE unexpected.txt no
2276 } ELSE {
2277 WRITE fallback.txt or-false
2278 }
2279
2280 LET $fb: STRING = READ fallback.txt
2281 ASSERT_EQ $fb "or-false"
2282 LET $t1: STRING = PATH_TYPE("unexpected.txt")
2283 ASSERT_EQ $t1 "absent"
2284
2285 IF $role == "admin" || $level >= 5 {
2286 WRITE chosen.txt or-true
2287 }
2288
2289 LET $ch: STRING = READ chosen.txt
2290 ASSERT_EQ $ch "or-true"
2291
2292 IF $role == "admin" && $level >= 5 {
2293 WRITE unexpected-too.txt no
2294 } ELSE {
2295 WRITE and.txt and-false
2296 }
2297
2298 LET $an: STRING = READ and.txt
2299 ASSERT_EQ $an "and-false"
2300 LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
2301 ASSERT_EQ $t2 "absent"
2302 "#},
2303 },
2304 ],
2305 },
2306 CommandMeta {
2307 name: "LET",
2308 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> }",
2309 summary: "Bind script-local variables.",
2310 description: indoc! {r#"
2311 Declares a script-local variable with an explicit type (STRING, INT,
2312 FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
2313 in the same scope frame is a redeclaration error; mutate with
2314 `$var = <expr>`.
2315
2316 Variables are usable in templates (`{{ $var }}`), guards, and
2317 expressions. With `ASYNC`, spawns a background task and stores its
2318 handle (see ASYNC). The `$` sigil on the name is mandatory.
2319
2320 No hoisting: a variable exists only after its LET runs, in
2321 execution order. Reading `$var` before its LET (or after the
2322 block that declared it exits) fails with
2323 `undefined variable $var`. Scopes are a stack of frames and
2324 resolution walks innermost outward, so nothing pre-declares
2325 names. Function bodies read outer variables through the same
2326 walk, but their own LETs never leak out (see FUNC).
2327
2328 The right-hand side is always an expression — literals, lists, maps,
2329 arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
2330 parentheses), comparisons (`< <= > >=` binding tighter than
2331 `== !=`), logical `&&` (tighter) and `||` with short-circuit,
2332 `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
2333 `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
2334 `{{ ... }}` template; interpolation happens in string values,
2335 not here.
2336 The one exception is pipes: `LET $p: PIPE` with no `=`
2337 and no initializer mints a fresh anonymous backend,
2338 lazily materialized at first binding, so two declarations
2339 never share a channel.
2340
2341 Numbers are numeric literals: `42` binds `INT`, `3.14` binds
2342 `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
2343 so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
2344 Division by zero, overflow, and non-finite results are errors.
2345 Both numeric sides compare numerically (`1 == 1.0` is true);
2346 otherwise `==`/`!=` compare rendered strings and ordering on
2347 non-numerics is a Type Error. Constant subtrees fold at parse
2348 time and dynamic arithmetic compiles to flat RPN with
2349 identical semantics.
2350
2351 Float equality is exact with no epsilon. Floats store decimals
2352 in binary, so a value is exact only when its reduced fraction
2353 has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
2354 (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
2355 repeat forever in binary (like 1/3 in decimal) and truncate,
2356 so `0.1 + 0.2 == 0.3` is false (the sum is
2357 `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
2358 .125, .625, .875 are exact; .1, .2, .3 and similar are
2359 approximations. Bound approximations instead of comparing
2360 them: `IF $sum > 0.299999 && $sum < 0.300001`.
2361
2362 Comparisons do not chain: `a < b < c` is a parse error, not
2363 `(a < b) < c`. Chaining would compare a `BOOL` against a
2364 number (a runtime Type Error in C-style parsing) or evaluate
2365 the middle term twice (Python-style chaining), so the grammar
2366 accepts exactly one comparison operator per level. Write the
2367 conjunction explicitly: `$a < $b && $b < $c`. The same holds
2368 for equality (`$a == $b == $c` is rejected).
2369
2370 Captured command output is a string, so convert before math:
2371 `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
2372 whitespace; `FLOAT` accepts int strings and rejects
2373 non-finite).
2374
2375 Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
2376 as quoted.
2377
2378 When the right-hand side is a synchronous command
2379 (`LET $out: STRING = ECHO hi`), the command runs to completion and its
2380 exact stdout bytes are captured into the variable as a string (no newline
2381 stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
2382 an error). Combining capture with an explicit
2383 `WITH_IO [stdout=$var]` is a parse error.
2384
2385 Coming from Bash, the capture line looks familiar but behaves
2386 strictly:
2387
2388 | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
2389 | --- | --- | --- |
2390 | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
2391 | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
2392 | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
2393 | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |
2394
2395 `LET $out: TYPE = AWAIT $var` binds the background task's
2396 explicit `RETURN` value instead (tasks stream their stdout
2397 live, so there is no output left to capture); a task that
2398 succeeded without `RETURN` yields `INT` 0, like a process
2399 exit status.
2400
2401 An inline block (`LET $var: TYPE = { <commands> }`) runs its
2402 steps in a fresh scope and binds the nearest `RETURN` value,
2403 like a zero-arg function body: fallthrough without `RETURN`
2404 binds `""`, and `BREAK`/`CONTINUE` escaping the block are
2405 errors. The block reads outer variables but its own LETs
2406 never leak out. A `{k: v}` shape still parses as a map
2407 literal; anything else in braces is a block.
2408
2409 The split is deliberate: synchronous commands capture
2410 stdout because they run inline to completion on the same
2411 thread; background tasks never capture stdout because
2412 concurrent output has no well-defined value. Task results
2413 travel only through `RETURN` (or `INT` 0 for void tasks).
2414
2415 `LET $e: STRING = env:FOO` reads the script environment into a plain
2416 string.
2417 "#},
2418 args: &[],
2419 flags: &[],
2420 default_output: None,
2421 examples: &[
2422 Example {
2423 name: "let",
2424 fence_meta: None,
2425 code: indoc! {r#"
2426 LET $name: STRING = "world"
2427 ECHO "hello, {{ $name }}"
2428 ASSERT_CONTAINS stdout "hello, world"
2429
2430 LET $items: LIST<STRING> = ["a", "b"]
2431 ASSERT_CONTAINS $items "a"
2432 ASSERT_CONTAINS $items "b"
2433
2434 LET $count: INT = 42
2435 ASSERT_EQ $count 42
2436 "#},
2437 },
2438 Example {
2439 name: "no hoisting",
2440 fence_meta: Some("expect_error:\"undefined variable\""),
2441 code: indoc! {r#"
2442 # Reading before the LET runs is an error, not an empty value.
2443 ECHO $too_early
2444 LET $too_early: STRING = "too late"
2445 "#},
2446 },
2447 Example {
2448 name: "glob binding",
2449 fence_meta: None,
2450 code: indoc! {r#"
2451 # The RHS is an expression: GLOB(...) runs and binds a list.
2452 IMPORT [STD]
2453 WRITE a.txt "x"
2454 LET $files: LIST<STRING> = GLOB("*.txt")
2455 FOR $f: STRING IN $files { ECHO $f }
2456
2457 ASSERT_CONTAINS stdout "a.txt"
2458 "#},
2459 },
2460 Example {
2461 name: "scoped variable reverts",
2462 fence_meta: None,
2463 code: indoc! {r#"
2464 # LET inside a braced block reverts when the block exits.
2465 LET $a: STRING = "outer"
2466
2467 [bool:true] {
2468 LET $a: STRING = "inner"
2469 WRITE inner.txt "{{ $a }}"
2470 }
2471
2472 WRITE outer.txt "{{ $a }}"
2473
2474 LET $in_body: STRING = READ inner.txt
2475 ASSERT_EQ $in_body "inner"
2476
2477 LET $out_body: STRING = READ outer.txt
2478 ASSERT_EQ $out_body "outer"
2479 "#},
2480 },
2481 Example {
2482 name: "capture command output",
2483 fence_meta: None,
2484 code: indoc! {r#"
2485 # Capture keeps the trailing newline.
2486 LET $out: STRING = ECHO hi
2487 ASSERT_EQ $out "hi\n"
2488 "#},
2489 },
2490 Example {
2491 name: "inline block",
2492 fence_meta: None,
2493 code: indoc! {r#"
2494 LET $who: STRING = "ada"
2495
2496 # An inline block binds its RETURN value like a function body.
2497 LET $res: STRING = {
2498 LET $loud: STRING = "{{ $who }}!"
2499 RETURN $loud
2500 }
2501 ASSERT_EQ $res "ada!"
2502
2503 # Any declared type works: the block value checks like any RHS.
2504 LET $n: INT = {
2505 RETURN 40 + 2
2506 }
2507 ASSERT_EQ $n 42
2508 "#},
2509 },
2510 Example {
2511 name: "arithmetic over captured output",
2512 fence_meta: None,
2513 code: indoc! {r#"
2514 # Captured output converts explicitly: INT() then arithmetic.
2515 IMPORT [STD]
2516 LET $size_str: STRING = ECHO 41
2517 LET $total: INT = INT($size_str) + 1
2518 ASSERT_EQ $total 42
2519
2520 # FLOAT() promotes instead of truncating.
2521 LET $ratio: FLOAT = 1 + 2.5
2522 ASSERT_EQ $ratio 3.5
2523
2524 # Int x Int stays INT: integer division truncates.
2525 LET $half: INT = 7 / 2
2526 ASSERT_EQ $half 3
2527 "#},
2528 },
2529 Example {
2530 name: "float equality is exact",
2531 fence_meta: None,
2532 code: indoc! {r#"
2533 # Binary fractions compare cleanly; decimal fractions may not:
2534 # 0.1 + 0.2 is 0.30000000000000004, so == is false.
2535 IMPORT [STD]
2536 LET $exact: BOOL = 0.5 + 0.25 == 0.75
2537 LET $decimal: BOOL = 0.1 + 0.2 == 0.3
2538 IF $exact {
2539 WRITE exact.txt yes
2540 }
2541 IF $decimal {
2542 WRITE unexpected.txt no
2543 }
2544
2545 LET $ok: STRING = READ exact.txt
2546 ASSERT_EQ $ok "yes"
2547
2548 LET $t: STRING = PATH_TYPE("unexpected.txt")
2549 ASSERT_EQ $t "absent"
2550 "#},
2551 },
2552 Example {
2553 name: "bound inexact decimals",
2554 fence_meta: None,
2555 code: indoc! {r#"
2556 # Never test inexact decimals for equality; bound them.
2557 LET $sum: FLOAT = 0.1 + 0.2
2558 IF $sum > 0.299999 && $sum < 0.300001 {
2559 WRITE bounded.txt yes
2560 }
2561
2562 LET $ok: STRING = READ bounded.txt
2563 ASSERT_EQ $ok "yes"
2564 "#},
2565 },
2566 Example {
2567 name: "inspect a variable",
2568 fence_meta: None,
2569 code: indoc! {r#"
2570 # INSPECT($var) snapshots a variable into a MAP: declared
2571 # type plus live details (pipe backend stats here), so
2572 # scripts can branch on engine state.
2573 IMPORT [STD]
2574 LET $p: PIPE
2575 WITH_IO [stdout=$p] ECHO hello
2576 LET $info: MAP<ANY> = INSPECT($p)
2577 IF $info.is_os_pipe {
2578 WRITE unexpected.txt "should be a script pipe"
2579 }
2580
2581 ASSERT_EQ $info.type "PIPE"
2582 LET $t: STRING = PATH_TYPE("unexpected.txt")
2583 ASSERT_EQ $t "absent"
2584 "#},
2585 },
2586 ],
2587 },
2588 CommandMeta {
2589 name: "MUTATION",
2590 syntax: "$var = <expr>",
2591 summary: "Mutate a declared variable.",
2592 description: indoc! {r#"
2593 Reassigns an existing variable, converting the new value to
2594 the type declared at LET time. The explicit annotation is
2595 what authorizes string-to-number conversion here (`$n = "42"`
2596 binds 42 for an INT); a non-numeric string is an error.
2597 Expressions never convert: `"100" + 1` is a Type Error, use
2598 `INT()` / `FLOAT()` to cross that boundary explicitly.
2599
2600 The leading `$` distinguishes mutation from `KEY=value` command
2601 assignments. Assigning an undeclared variable or a mismatched type is
2602 an error.
2603
2604 Mutation writes through to the scope where the variable was
2605 declared, so it survives block exit: `LET $x` outside a block
2606 followed by `$x = ...` inside still reads back the new value
2607 afterwards, for every type. This is the counterpart to LET
2608 shadowing, where `LET $x` *inside* the block declares a
2609 separate inner variable that reverts on exit.
2610
2611 Reassignment rebinds the variable to a new value: values
2612 captured earlier keep the old word (see the rebinding
2613 example below).
2614 "#},
2615 args: &[],
2616 flags: &[],
2617 default_output: None,
2618 examples: &[
2619 Example {
2620 name: "mutate",
2621 fence_meta: None,
2622 code: indoc! {r#"
2623 # Mutation writes through: the binding holds the new value.
2624 LET $count: INT = 1
2625 $count = 2
2626 ASSERT_EQ $count 2
2627 "#},
2628 },
2629 Example {
2630 name: "rebind keeps earlier captures",
2631 fence_meta: None,
2632 code: indoc! {r#"
2633 # Reassignment rebinds: a map built from `$s` still
2634 # reads the original string after `$s` moves on.
2635 LET $s: STRING = "test"
2636 LET $m: MAP<ANY> = {a: $s}
2637 $s = "changed"
2638 ASSERT_EQ $m.a "test"
2639
2640 # Appending to one list binding never touches its clones.
2641 LET $a: LIST<STRING> = ["1"]
2642 LET $b: LIST<STRING> = $a
2643 LIST_APPEND $a "2"
2644 LET $want: LIST<STRING> = ["1"]
2645 ASSERT_EQ $b $want
2646 "#},
2647 },
2648 Example {
2649 name: "convert before math",
2650 fence_meta: None,
2651 code: indoc! {r#"
2652 # Captured output is a string: `"100" + 1` is a Type Error.
2653 # Convert explicitly, then mutate with arithmetic.
2654 IMPORT [STD]
2655 LET $raw: STRING = ECHO 100
2656 LET $n: INT = INT($raw)
2657 $n = $n + 1
2658
2659 # The declared slot stays strict: strings parse only
2660 # through the explicit converter, never on assignment.
2661 $n = INT("42")
2662 ASSERT_EQ $n 42
2663
2664 # Same crossing for decimals via FLOAT().
2665 LET $frac_str: STRING = ECHO 2.5
2666 LET $f: FLOAT = FLOAT($frac_str) + 0.25
2667 ASSERT_EQ $f 2.75
2668 "#},
2669 },
2670 ],
2671 },
2672 CommandMeta {
2673 name: "ASYNC",
2674 syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE = ASYNC { <commands> }",
2675 summary: "Run steps in a background thread.",
2676 description: indoc! {r#"
2677 Runs a command or block of commands in a background thread with
2678 subshell isolation.
2679
2680 Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
2681 task handle for `AWAIT`. Task output streams live to the parent
2682 stdout; a task publishes a value with an explicit `RETURN`,
2683 which `LET $out: TYPE = AWAIT $task` binds.
2684
2685 `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
2686 then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
2687 the main thread before the worker spawns. Placing `WITH_IO` directly
2688 inside `ASYNC` is rejected at parse time.
2689 "#},
2690 args: &[],
2691 flags: &[],
2692 default_output: None,
2693 examples: &[
2694 Example {
2695 name: "async",
2696 fence_meta: None,
2697 code: indoc! {r#"
2698 # Inline and block forms both run in the background; AWAIT joins them.
2699 ASYNC ECHO "warming-up"
2700 LET $a: HANDLE = ASYNC ECHO "first"
2701 LET $b: HANDLE = ASYNC {
2702 ECHO "second"
2703 }
2704 AWAIT $a
2705 AWAIT $b
2706 ASSERT_CONTAINS stdout "first"
2707 ASSERT_CONTAINS stdout "second"
2708 "#},
2709 },
2710 Example {
2711 name: "async task handle",
2712 fence_meta: None,
2713 code: indoc! {r#"
2714 LET $task: HANDLE = ASYNC {
2715 ECHO "built"
2716 }
2717 AWAIT $task
2718 ASSERT_CONTAINS stdout "built"
2719 "#},
2720 },
2721 ],
2722 },
2723 CommandMeta {
2724 name: "AWAIT",
2725 syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
2726 summary: "Join a background task.",
2727 description: indoc! {r#"
2728 Blocks until the named task completes. Propagates errors if the task failed.
2729
2730 Task output streams live during the run; joining binds nothing by
2731 itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
2732 `RETURN` value instead, or `INT` 0 when the task succeeded
2733 without one (add `RETURN <expr>` to the task body to yield
2734 a value).
2735 "#},
2736 args: &[],
2737 flags: &[],
2738 default_output: None,
2739 examples: &[
2740 Example {
2741 name: "await",
2742 fence_meta: None,
2743 code: indoc! {r#"
2744 LET $task: HANDLE = ASYNC ECHO "done"
2745 AWAIT $task
2746 ASSERT_CONTAINS stdout "done"
2747 "#},
2748 },
2749 Example {
2750 name: "await capture",
2751 fence_meta: None,
2752 code: indoc! {r#"
2753 LET $task: HANDLE = ASYNC {
2754 ECHO "logged"
2755 RETURN "returned"
2756 }
2757
2758 # AWAIT binds the RETURN value, not the streamed output.
2759 LET $out: STRING = AWAIT $task
2760 ASSERT_EQ $out "returned"
2761 "#},
2762 },
2763 ],
2764 },
2765 CommandMeta {
2766 name: "CANCEL",
2767 syntax: "CANCEL $var",
2768 summary: "Synchronously cancel a background task.",
2769 description: indoc! {r#"
2770 Kills the named background task spawned via LET $var: HANDLE = ASYNC ....
2771
2772 Blocking: returns only after the task thread has been joined and its OS
2773 process reaped, so no residual filesystem or stream mutation follows. A
2774 later AWAIT $var reports cancellation. Only named tasks can be cancelled.
2775 "#},
2776 args: &[],
2777 flags: &[],
2778 default_output: None,
2779 examples: &[
2780 Example {
2781 name: "cancel",
2782 fence_meta: None,
2783 code: indoc! {r#"
2784 LET $task: HANDLE = ASYNC SLEEP 30s
2785 CANCEL $task
2786 "#},
2787 },
2788 Example {
2789 name: "await after cancel reports cancellation",
2790 fence_meta: Some("expect_error:\"was cancelled\""),
2791 code: indoc! {r#"
2792 # A cancelled task stays cancelled: joining it reports.
2793 LET $task: HANDLE = ASYNC SLEEP 30s
2794 CANCEL $task
2795 AWAIT $task
2796 "#},
2797 },
2798 ],
2799 },
2800 CommandMeta {
2801 name: "TIMEOUT",
2802 syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
2803 summary: "Enforce an execution deadline.",
2804 description: indoc! {r#"
2805 Aborts the wrapped step or block with a deadline error if it exceeds the
2806 duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
2807
2808 A blocking foreground process is killed.
2809
2810 ASYNC composes in either nesting order with order-dependent deadline
2811 semantics: `LET $task: HANDLE = ASYNC TIMEOUT 30s RUN "build"` enforces
2812 the deadline inside the background thread (a later `AWAIT $task`
2813 surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
2814 preempts a hung task from the awaiting side.
2815 "#},
2816 args: &[],
2817 flags: &[],
2818 default_output: None,
2819 examples: &[
2820 Example {
2821 name: "timeout",
2822 fence_meta: None,
2823 code: indoc! {r#"
2824 TIMEOUT 30s WRITE heartbeat.txt alive
2825 LET $beat: STRING = READ heartbeat.txt
2826 ASSERT_EQ $beat "alive"
2827 "#},
2828 },
2829 Example {
2830 name: "timeout block",
2831 fence_meta: None,
2832 code: indoc! {r#"
2833 TIMEOUT 30s {
2834 WRITE a.txt one
2835 WRITE b.txt two
2836 }
2837 LET $a: STRING = READ a.txt
2838 LET $b: STRING = READ b.txt
2839 ASSERT_EQ $a "one"
2840 ASSERT_EQ $b "two"
2841 "#},
2842 },
2843 Example {
2844 name: "deadline aborts the step",
2845 fence_meta: Some("expect_error:\"TIMEOUT after\""),
2846 code: indoc! {r#"
2847 # 50ms expires long before the sleep does: the step dies
2848 # with a deadline error instead of running out the clock.
2849 TIMEOUT 50ms SLEEP 30s
2850 "#},
2851 },
2852 Example {
2853 name: "timeout variable duration",
2854 fence_meta: None,
2855 code: indoc! {r#"
2856 # Durations resolve at runtime, so variables work too.
2857 LET $budget: DURATION = "30s"
2858 TIMEOUT $budget WRITE heartbeat.txt alive
2859
2860 LET $beat: STRING = READ heartbeat.txt
2861 ASSERT_EQ $beat "alive"
2862 "#},
2863 },
2864 Example {
2865 name: "timeout await",
2866 fence_meta: None,
2867 code: indoc! {r#"
2868 # AWAIT form bounds a task join instead of a step.
2869 LET $quick: HANDLE = ASYNC {
2870 ECHO hi
2871 }
2872 TIMEOUT 30s AWAIT $quick
2873 "#},
2874 },
2875 ],
2876 },
2877 CommandMeta {
2878 name: "ISOLATED",
2879 syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
2880 summary: "Run steps with the seeded script environment.",
2881 description: indoc! {r#"
2882 Resets the script environment for the block to the session
2883 seed: spawned children see the sandbox defaults plus names
2884 the block re-adds through its leading `INHERIT_ENV`.
2885
2886 The allowlist resolves against the outer scope, never the
2887 host. Absent names stay absent silently, matching top-level
2888 `INHERIT_ENV`.
2889
2890 Script variables, pipes, and files flow through untouched;
2891 only `env:` is reset. Files share the session workspace:
2892 blocks selecting the same `WORKSPACE` target resolve to the
2893 same directory with no per-block overlay, so one block's
2894 writes are visible to another.
2895
2896 Blocks nest (each level re-seeds from the same seed, so
2897 nesting only narrows through the allowlists) and compose
2898 with `ASYNC` and `FUNC`. Scope exit restores the prior
2899 environment.
2900 "#},
2901 args: &[],
2902 flags: &[],
2903 default_output: None,
2904 examples: &[
2905 Example {
2906 name: "isolated scope",
2907 fence_meta: None,
2908 code: indoc! {r#"
2909 # The block sees a clean env; plain steps still run and
2910 # outer bindings survive untouched.
2911 ENV MODE=outer
2912 ISOLATED {
2913 ENV MODE=inner
2914 WRITE inner.txt "{{ env:MODE }}"
2915 }
2916 LET $back: STRING = "{{ env:MODE }}"
2917 ASSERT_EQ $back "outer"
2918 LET $body: STRING = READ inner.txt
2919 ASSERT_EQ $body "inner"
2920 "#},
2921 },
2922 Example {
2923 name: "reseeded child env",
2924 fence_meta: None,
2925 code: indoc! {r#"
2926 # The block resets to the session seed: plain steps and
2927 # spawns run with zero prelude, while outer customs
2928 # stay out.
2929 ENV OUTER_CUSTOM=outer-val
2930 WRITE top-path.txt "{{ env:PATH }}"
2931 ISOLATED {
2932 WRITE inner-path.txt "{{ env:PATH }}"
2933 WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
2934 RUN "echo seed-ok"
2935 }
2936 LET $top: STRING = READ top-path.txt
2937 LET $inner: STRING = READ inner-path.txt
2938 ASSERT_EQ $inner $top
2939 LET $custom: STRING = READ inner-custom.txt
2940 ASSERT_EQ $custom ""
2941 ASSERT_CONTAINS stdout "seed-ok"
2942 "#},
2943 },
2944 Example {
2945 name: "absent names stay absent",
2946 fence_meta: None,
2947 code: indoc! {r#"
2948 # Listing a name the outer scope lacks is not an error:
2949 # the block simply runs without it.
2950 ISOLATED {
2951 INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
2952 ECHO still-runs
2953 }
2954 ASSERT_CONTAINS stdout "still-runs"
2955 "#},
2956 },
2957 Example {
2958 name: "nesting narrows",
2959 fence_meta: None,
2960 code: indoc! {r#"
2961 # Each level snapshots the already-scrubbed parent, so
2962 # an inner block cannot recover what the outer dropped.
2963 ENV KEEP=yes
2964 ISOLATED {
2965 INHERIT_ENV [KEEP]
2966 ISOLATED {
2967 ENV KEEP=inner
2968 WRITE deep.txt "{{ env:KEEP }}"
2969 }
2970 LET $mid: STRING = "{{ env:KEEP }}"
2971 ASSERT_EQ $mid "yes"
2972 }
2973 LET $deep: STRING = READ deep.txt
2974 ASSERT_EQ $deep "inner"
2975 "#},
2976 },
2977 ],
2978 },
2979 CommandMeta {
2980 name: "REMOTE",
2981 syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
2982 summary: "Run a sealed block on a remote target.",
2983 description: indoc! {r#"
2984 Runs the braced block on the named remote target, which the
2985 host binds at startup (`--remote`). The block is sealed:
2986 only header-listed `$var` and `env:NAME` entries cross, the
2987 guest starts empty, and results return through declared
2988 transfers or `WITH_IO` pipes.
2989
2990 The target is a static literal, never a variable. Unknown
2991 targets fail before execution starts.
2992
2993 Bodies check twice: the host static pass validates the
2994 body before anything ships, and the guest re-validates on
2995 arrival through the same entry point, so a body type error
2996 fails locally, never mid-run on the remote.
2997
2998 A failing guest fails the host step: EXIT in the body
2999 exits the guest, and the host relays the code to its own
3000 process exit status (see EXIT).
3001 "#},
3002 args: &[],
3003 flags: &[],
3004 default_output: None,
3005 examples: &[
3006 Example {
3007 name: "sealed header values cross, outer scope does not",
3008 fence_meta: Some("mock_remote:prod"),
3009 code: indoc! {r#"
3010 # Only header-listed names arrive: `$version` is visible
3011 # on the guest, `$secret` was never sent.
3012 LET $version: STRING = "1.2.3"
3013 LET $secret: STRING = "host-only"
3014 REMOTE prod [$version] {
3015 WRITE version.txt "{{ $version }}"
3016 COPY --to-host ./version.txt back.txt
3017 }
3018
3019 # The pushed file proves the guest saw the injected value.
3020 LET $back: STRING = READ back.txt
3021 ASSERT_EQ $back "1.2.3"
3022 "#},
3023 },
3024 Example {
3025 name: "background tasks stream through shared pipes",
3026 fence_meta: Some("mock_remote:prod"),
3027 code: indoc! {r#"
3028 # Two background REMOTEs share one capture pipe while a
3029 # WITH_IO block holds the write end open.
3030 IMPORT [STD]
3031 LET $cap: PIPE
3032 WITH_IO [stdout=$cap] {
3033 LET $a: HANDLE = ASYNC REMOTE prod {
3034 ECHO "from-a"
3035 }
3036 LET $b: HANDLE = ASYNC REMOTE prod {
3037 ECHO "from-b"
3038 }
3039 AWAIT $a
3040 AWAIT $b
3041 }
3042
3043 # EOF ends the drain: no sentinel line, no baked-in count.
3044 LET $n: INT = 0
3045 WHILE !EOF($cap) {
3046 WITH_IO [stdin=$cap] READ_LINE $line
3047 $n = $n + 1
3048 }
3049 ASSERT_EQ $n 2
3050 "#},
3051 },
3052 Example {
3053 name: "declared files cross both directions",
3054 fence_meta: Some("mock_remote:prod roots:unified"),
3055 code: indoc! {r#"
3056 # Fetches ride in, pushes ride back. Anything undeclared
3057 # never leaves its side.
3058 WRITE send.txt "payload"
3059 REMOTE prod {
3060 COPY --from-host ./send.txt got.txt
3061 LET $v: STRING = READ got.txt
3062 ASSERT_EQ $v "payload"
3063 WRITE back.txt "returned"
3064 COPY --to-host ./back.txt back.txt
3065 }
3066
3067 # The push landed on the host; guest staging is gone.
3068 LET $b: STRING = READ back.txt
3069 ASSERT_EQ $b "returned"
3070 "#},
3071 },
3072 Example {
3073 name: "guest workspace selection stays on the guest",
3074 fence_meta: Some("mock_remote:prod"),
3075 code: indoc! {r#"
3076 # WORKSPACE switches inside the block resolve against the
3077 # guest staging dir, which serves as both the SNAPSHOT
3078 # root and the LOCAL build context. The host selection
3079 # restores when the block exits.
3080 REMOTE prod {
3081 WORKSPACE SNAPSHOT
3082 WRITE out.txt "from-snapshot"
3083 COPY --to-host ./out.txt snap.txt
3084 }
3085
3086 LET $s: STRING = READ snap.txt
3087 ASSERT_EQ $s "from-snapshot"
3088 "#},
3089 },
3090 Example {
3091 name: "guest cache persists across execs",
3092 fence_meta: Some("mock_remote:prod"),
3093 code: indoc! {r#"
3094 # WORKSPACE CACHE addresses guest-local persistent
3095 # storage: the second block reads what the first wrote,
3096 # while the guest staging starts empty every time.
3097 REMOTE prod {
3098 WORKSPACE CACHE
3099 WRITE marker.txt "run-marker"
3100 }
3101 REMOTE prod {
3102 WORKSPACE CACHE
3103 LET $m: STRING = READ marker.txt
3104 ASSERT_EQ $m "run-marker"
3105 }
3106 "#},
3107 },
3108 Example {
3109 name: "pushes outside staging fail closed",
3110 fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
3111 code: indoc! {r#"
3112 # WORKSPACE SYSTEM exposes the whole guest machine, but
3113 # transfers stay staging scoped: a push source outside
3114 # staging fails loudly instead of crossing.
3115 REMOTE prod {
3116 WORKSPACE SYSTEM
3117 COPY --to-host /no/such/file.txt got.txt
3118 }
3119 "#},
3120 },
3121 Example {
3122 name: "guest exit fails the step, host survives",
3123 fence_meta: Some(
3124 "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
3125 ),
3126 code: indoc! {r#"
3127 # EXIT in the body exits the guest with code 3. The
3128 # host is unaffected: it keeps executing after the
3129 # guest is already dead, and the failure surfaces as
3130 # a host step error carrying the same code. The CLI
3131 # then exits with it, so the guest code reaches the OS.
3132 LET $t: HANDLE = ASYNC REMOTE prod {
3133 EXIT 3
3134 }
3135 WRITE host-alive.txt "still here"
3136 AWAIT $t
3137 "#},
3138 },
3139 Example {
3140 name: "remote block without a runner",
3141 fence_meta: Some("expect_error:\"has no registered session\""),
3142 code: indoc! {r#"
3143 # Without a bound session, the block bails instead of
3144 # executing anywhere unexpected.
3145 REMOTE prod {
3146 ECHO "do something on remote"
3147 }
3148 "#},
3149 },
3150 ],
3151 },
3152 CommandMeta {
3153 name: "FUNC",
3154 syntax: "FUNC NAME([$param: TYPE, ...]) { <commands> }",
3155 summary: "Define a user function.",
3156 description: indoc! {r#"
3157 Defines a user function with UPPERCASE name and explicitly typed
3158 parameters.
3159
3160 Params bind by position, converting each argument to its
3161 declared parameter type before the body runs.
3162 Bodies run in a fresh variable scope; LETs inside do not leak. A nested
3163 FUNC definition is scoped to its block and reverts on exit. Names share
3164 one namespace with native and host-registered functions, which a FUNC
3165 may never shadow.
3166
3167 Functions resolve like variables: a name is visible from its
3168 definition line, so recursion works but mutual recursion does
3169 not (the second name does not exist while the first body
3170 lowers). Calls name their module (`STD::GLOB(...)`) unless
3171 imported; see IMPORT.
3172
3173 Invoke any function with one syntax: `NAME(...)` as a statement
3174 (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
3175 the RETURN value (fallthrough without RETURN captures as "").
3176 "#},
3177 args: &[],
3178 flags: &[],
3179 default_output: None,
3180 examples: &[
3181 Example {
3182 name: "func def call",
3183 fence_meta: None,
3184 code: indoc! {r#"
3185 FUNC GREET($name: STRING) {
3186 RETURN $name
3187 }
3188
3189 LET $res: STRING = GREET("ada")
3190 ASSERT_EQ $res "ada"
3191
3192 # Statement form: parens stay, the value drops.
3193 GREET("bex")
3194 "#},
3195 },
3196 Example {
3197 name: "call with pipes",
3198 fence_meta: None,
3199 code: indoc! {r#"
3200 # A pipe handle travels into a function as a typed argument
3201 # and is usable as a binding target in both directions.
3202 # `LET $p: PIPE` mints the handle; `$p` passes it on.
3203 FUNC DRAIN($q: PIPE) {
3204 WITH_IO [stdin=$q] READ_LINE $line
3205 RETURN $line
3206 }
3207
3208 LET $p: PIPE
3209 WITH_IO [stdout=$p] ECHO "payload"
3210
3211 LET $got: STRING = DRAIN($p)
3212 ASSERT_EQ $got "payload"
3213 "#},
3214 },
3215 ],
3216 },
3217 CommandMeta {
3218 name: "RETURN",
3219 syntax: "RETURN [<expr>]",
3220 summary: "Return a value from a function, task, or inline block.",
3221 description: indoc! {r#"
3222 Ends the nearest enclosing boundary with a value: a function
3223 call, an `ASYNC` task (bound by `LET $o = AWAIT $t`), or an
3224 inline `LET` block. Bare `RETURN` with no expression yields
3225 `""`.
3226
3227 Falling off the end without RETURN yields "". RETURN with no
3228 enclosing boundary (including at top level) is an error; use
3229 EXIT or ECHO there.
3230 "#},
3231 args: &[],
3232 flags: &[],
3233 default_output: None,
3234 examples: &[Example {
3235 name: "return",
3236 fence_meta: None,
3237 code: indoc! {r#"
3238 FUNC PICK($flag: BOOL) {
3239 IF $flag {
3240 RETURN "yes"
3241 }
3242 RETURN "no"
3243 }
3244
3245 LET $res: STRING = PICK(true)
3246 ASSERT_EQ $res "yes"
3247
3248 # Fallthrough without RETURN yields its own value.
3249 LET $no: STRING = PICK(false)
3250 ASSERT_EQ $no "no"
3251 "#},
3252 }],
3253 },
3254 CommandMeta {
3255 name: "WHILE",
3256 syntax: "WHILE <bool-expr> { <commands> }",
3257 summary: "Loop while a condition holds.",
3258 description: indoc! {r#"
3259 Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
3260 non-Bool is a type error).
3261
3262 Each iteration runs in a fresh scope; mutate outer state with $var = ...
3263 so the next check observes it. BREAK exits the loop; CONTINUE skips to
3264 the next check.
3265 "#},
3266 args: &[],
3267 flags: &[],
3268 default_output: None,
3269 examples: &[Example {
3270 name: "while loop",
3271 fence_meta: None,
3272 code: indoc! {r#"
3273 # The condition re-evaluates every iteration: three passes, then stop.
3274 LET $n: INT = 0
3275 WHILE $n < 3 {
3276 WRITE tick.txt "{{ $n }}"
3277 $n = $n + 1
3278 }
3279
3280 ASSERT_EQ $n 3
3281 LET $tick: STRING = READ tick.txt
3282 ASSERT_EQ $tick "2"
3283 "#},
3284 }],
3285 },
3286 CommandMeta {
3287 name: "BREAK",
3288 syntax: "BREAK",
3289 summary: "Exit the innermost loop.",
3290 description: indoc! {r#"
3291 Exits the innermost enclosing FOR or WHILE loop.
3292
3293 BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
3294 "#},
3295 args: &[],
3296 flags: &[],
3297 default_output: None,
3298 examples: &[Example {
3299 name: "break",
3300 fence_meta: None,
3301 code: indoc! {r#"
3302 # BREAK leaves after the first pass: only "a" is written.
3303 FOR $x: STRING IN ["a", "b"] {
3304 WRITE picked.txt "{{ $x }}"
3305 BREAK
3306 }
3307
3308 LET $body: STRING = READ picked.txt
3309 ASSERT_EQ $body "a"
3310 "#},
3311 }],
3312 },
3313 CommandMeta {
3314 name: "CONTINUE",
3315 syntax: "CONTINUE",
3316 summary: "Skip to the next loop iteration.",
3317 description: indoc! {r#"
3318 Skips the rest of the innermost enclosing FOR or WHILE body and starts
3319 the next iteration.
3320
3321 CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
3322 "#},
3323 args: &[],
3324 flags: &[],
3325 default_output: None,
3326 examples: &[Example {
3327 name: "continue",
3328 fence_meta: None,
3329 code: indoc! {r#"
3330 # CONTINUE skips the write on "a": only "b" lands.
3331 FOR $x: STRING IN ["a", "b"] {
3332 IF $x == "a" {
3333 CONTINUE
3334 }
3335 WRITE picked.txt "{{ $x }}"
3336 }
3337
3338 LET $body: STRING = READ picked.txt
3339 ASSERT_EQ $body "b"
3340 "#},
3341 }],
3342 },
3343 CommandMeta {
3344 name: KEYWORD_IMPORT,
3345 syntax: "IMPORT [<module>, ...] | IMPORT <module>",
3346 summary: "Bring module functions into bare-call scope.",
3347 description: indoc! {r#"
3348 Every function call names its module (`STD::GLOB(...)`,
3349 `MOCK::READ_CSV(...)`) unless the module is imported:
3350 `IMPORT [STD]` lets the rest of the scope call `GLOB(...)`
3351 bare. Calls resolve at parse time against `SCRIPT`
3352 definitions first, then imported modules; unknown modules,
3353 unknown functions, and unimported bare calls are parse
3354 errors, never runtime surprises.
3355
3356 IMPORT is a lowering directive, not a step: it applies from
3357 its line to the enclosing block exit, then reverts, exactly
3358 like `LET` scoping but with no runtime footprint. Guards do
3359 not apply to it. Two imported modules exporting one name is
3360 an ambiguity error: qualify the call instead.
3361
3362 `EXPORT` is reserved for future script-module support and
3363 cannot be used yet.
3364 "#},
3365 args: &[],
3366 flags: &[],
3367 default_output: None,
3368 examples: &[Example {
3369 name: "import",
3370 fence_meta: None,
3371 code: indoc! {r#"
3372 # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
3373 WRITE a.txt "hi \{{ env:WHO }}!"
3374 IMPORT [STD]
3375 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
3376 ASSERT_CONTAINS stdout "hi World!"
3377 "#},
3378 }],
3379 },
3380 ]
3381}
3382
3383impl fmt::Display for StepKind {
3386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3387 match self {
3388 StepKind::InheritEnv { keys } => write!(f, "INHERIT_ENV [{}]", keys.join(", ")),
3389 StepKind::Workdir(a) => write!(f, "WORKDIR {}", fmt_value(a, quote_arg)),
3390 StepKind::Workspace(t) => write!(f, "WORKSPACE {}", t),
3391 StepKind::Env { key, value } => {
3392 write!(f, "ENV {}={}", key, fmt_value(value, quote_arg))
3393 }
3394 StepKind::Run(c) => write!(f, "RUN {}", fmt_value(c, quote_run)),
3395 StepKind::RunExec { argv } => {
3396 let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
3397 write!(f, "RUN [{}]", parts.join(", "))
3398 }
3399 StepKind::Echo(m) => write!(f, "ECHO {}", fmt_value(m, quote_msg)),
3400 StepKind::Copy {
3401 from_workspace,
3402 from_host,
3403 to_host,
3404 from,
3405 to,
3406 } => {
3407 let mut head = String::from("COPY");
3408 if let Some(target) = from_workspace {
3409 head.push_str(&format!(" --from-workspace {target}"));
3410 }
3411 if *from_host {
3412 head.push_str(" --from-host");
3413 }
3414 if *to_host {
3415 head.push_str(" --to-host");
3416 }
3417 write!(
3418 f,
3419 "{head} {} {}",
3420 fmt_value(from, quote_arg),
3421 fmt_value(to, quote_arg)
3422 )
3423 }
3424 StepKind::Symlink {
3425 from_workspace,
3426 from,
3427 to,
3428 } => {
3429 if let Some(target) = from_workspace {
3430 write!(
3431 f,
3432 "SYMLINK --from-workspace {} {} {}",
3433 target,
3434 fmt_value(from, quote_arg),
3435 fmt_value(to, quote_arg)
3436 )
3437 } else {
3438 write!(
3439 f,
3440 "SYMLINK {} {}",
3441 fmt_value(from, quote_arg),
3442 fmt_value(to, quote_arg)
3443 )
3444 }
3445 }
3446 StepKind::Mkdir(a) => write!(f, "MKDIR {}", fmt_value(a, quote_arg)),
3447 StepKind::Install { from, to } => write!(
3448 f,
3449 "INSTALL {} {}",
3450 fmt_value(from, quote_arg),
3451 fmt_value(to, quote_arg)
3452 ),
3453 StepKind::Archive { src, dst, raw } => {
3454 if *raw {
3455 write!(
3456 f,
3457 "ARCHIVE --raw {} {}",
3458 fmt_value(src, quote_arg),
3459 fmt_value(dst, quote_arg)
3460 )
3461 } else {
3462 write!(
3463 f,
3464 "ARCHIVE {} {}",
3465 fmt_value(src, quote_arg),
3466 fmt_value(dst, quote_arg)
3467 )
3468 }
3469 }
3470 StepKind::Unarchive {
3471 src,
3472 dst,
3473 max_bytes,
3474 } => {
3475 write!(f, "UNARCHIVE")?;
3476 if let Some(n) = max_bytes {
3477 write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
3478 }
3479 write!(
3480 f,
3481 " {} {}",
3482 fmt_value(src, quote_arg),
3483 fmt_value(dst, quote_arg)
3484 )
3485 }
3486 StepKind::Ls(a) => {
3487 write!(f, "LS")?;
3488 if let Some(x) = a {
3489 write!(f, " {}", fmt_value(x, quote_arg))?;
3490 }
3491 Ok(())
3492 }
3493 StepKind::Cwd => write!(f, "CWD"),
3494 StepKind::Read(a) => {
3495 write!(f, "READ")?;
3496 if let Some(x) = a {
3497 write!(f, " {}", fmt_value(x, quote_arg))?;
3498 }
3499 Ok(())
3500 }
3501 StepKind::ReadLine { var } => write!(f, "READ_LINE ${}", var),
3502 StepKind::Prompt {
3503 var,
3504 message,
3505 default,
3506 } => {
3507 write!(f, "PROMPT ${} {}", var, fmt_value(message, quote_arg))?;
3508 if let Some(d) = default {
3509 write!(f, " {}", fmt_value(d, quote_arg))?;
3510 }
3511 Ok(())
3512 }
3513 StepKind::Write { path, contents } => {
3514 write!(f, "WRITE {}", fmt_value(path, quote_arg))?;
3515 if let Some(b) = contents {
3516 write!(f, " {}", fmt_value(b, quote_msg))?;
3517 }
3518 Ok(())
3519 }
3520 StepKind::Append { path, contents } => {
3521 write!(f, "APPEND {}", fmt_value(path, quote_arg))?;
3522 if let Some(b) = contents {
3523 write!(f, " {}", fmt_value(b, quote_msg))?;
3524 }
3525 Ok(())
3526 }
3527 StepKind::Remove { path, recursive } => {
3528 if *recursive {
3529 write!(f, "REMOVE --recursive {}", fmt_value(path, quote_arg))
3530 } else {
3531 write!(f, "REMOVE {}", fmt_value(path, quote_arg))
3532 }
3533 }
3534 StepKind::Expand { path, overrides } => {
3535 write!(f, "EXPAND")?;
3536 if let Some(p) = path {
3537 write!(f, " {}", fmt_value(p, quote_arg))?;
3538 }
3539 for (k, v) in overrides {
3540 write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
3541 }
3542 Ok(())
3543 }
3544 StepKind::AssertEq {
3545 hash,
3546 actual,
3547 expected,
3548 } => {
3549 if let Some(d) = hash {
3550 write!(f, "ASSERT_EQ --hash {d} {}", fmt_assert_target(actual))?;
3551 } else {
3552 write!(
3553 f,
3554 "ASSERT_EQ {} {}",
3555 fmt_assert_target(actual),
3556 fmt_value(
3557 expected
3558 .as_ref()
3559 .expect("Display of ASSERT_EQ without --hash needs expected"),
3560 quote_msg
3561 )
3562 )?;
3563 }
3564 Ok(())
3565 }
3566 StepKind::AssertContains { haystack, needle } => write!(
3567 f,
3568 "ASSERT_CONTAINS {} {}",
3569 fmt_assert_target(haystack),
3570 fmt_value(needle, quote_msg)
3571 ),
3572 StepKind::WithIo { bindings, cmd } => {
3573 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3574 write!(f, "WITH_IO [{}] {}", p.join(", "), cmd)
3575 }
3576 StepKind::WithIoBlock { bindings } => {
3577 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3578 write!(f, "WITH_IO [{}] {{...}}", p.join(", "))
3579 }
3580 StepKind::CopyGit {
3581 rev,
3582 from,
3583 to,
3584 include_dirty,
3585 } => {
3586 if *include_dirty {
3587 write!(
3588 f,
3589 "COPY_GIT --include-dirty {} {} {}",
3590 fmt_value(rev, quote_arg),
3591 fmt_value(from, quote_arg),
3592 fmt_value(to, quote_arg)
3593 )
3594 } else {
3595 write!(
3596 f,
3597 "COPY_GIT {} {} {}",
3598 fmt_value(rev, quote_arg),
3599 fmt_value(from, quote_arg),
3600 fmt_value(to, quote_arg)
3601 )
3602 }
3603 }
3604 StepKind::HashSha256 { path } => {
3605 write!(f, "HASH_SHA256 {}", fmt_value(path, quote_arg))
3606 }
3607 StepKind::Exit(code) => write!(f, "EXIT {}", fmt_raw_arg(code)),
3608 StepKind::Sleep { duration } => write!(f, "SLEEP {}", fmt_raw_arg(duration)),
3609 StepKind::ListAppend { list, item } => {
3610 write!(f, "LIST_APPEND ${} {}", list, fmt_raw_arg(item))
3611 }
3612 StepKind::For {
3613 key_var,
3614 key_type,
3615 var,
3616 var_type,
3617 in_expr,
3618 body,
3619 } => {
3620 match key_var {
3621 Some(k) => {
3622 let kt = key_type.as_deref().unwrap_or("STRING");
3623 write!(
3624 f,
3625 "FOR ${}: {}, ${}: {} IN {} {{",
3626 k, kt, var, var_type, in_expr
3627 )?
3628 }
3629 None => write!(f, "FOR ${}: {} IN {} {{", var, var_type, in_expr)?,
3630 }
3631 for s in body {
3632 write!(f, "\n {}", s)?;
3633 }
3634 write!(f, "\n}}")
3635 }
3636 StepKind::If {
3637 cond,
3638 then_body,
3639 else_ifs,
3640 else_body,
3641 } => {
3642 write!(f, "IF {} {{", cond)?;
3643 for s in then_body {
3644 write!(f, "\n {}", s)?;
3645 }
3646 write!(f, " }}")?;
3647 for (c, b) in else_ifs {
3648 write!(f, " ELSE IF {} {{", c)?;
3649 for s in b {
3650 write!(f, "\n {}", s)?;
3651 }
3652 write!(f, " }}")?;
3653 }
3654 if let Some(b) = else_body {
3655 write!(f, " ELSE {{")?;
3656 for s in b {
3657 write!(f, "\n {}", s)?;
3658 }
3659 write!(f, " }}")?;
3660 }
3661 Ok(())
3662 }
3663 StepKind::Assign {
3664 var,
3665 decl_type,
3666 expr,
3667 } => {
3668 if matches!(expr, Expr::FreshPipe) {
3670 write!(f, "LET ${}: {}", var, decl_type)
3671 } else {
3672 write!(f, "LET ${}: {} = {}", var, decl_type, expr)
3673 }
3674 }
3675 StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
3676 StepKind::AssignCapture {
3677 var,
3678 decl_type,
3679 cmd,
3680 } => {
3681 write!(f, "LET ${}: {} = {}", var, decl_type, cmd)
3682 }
3683 StepKind::AsyncBlock { body } => {
3684 write!(f, "ASYNC {{")?;
3685 for s in body {
3686 write!(f, "\n {}", s)?;
3687 }
3688 write!(f, "\n}}")
3689 }
3690 StepKind::AssignAsync {
3691 var,
3692 decl_type,
3693 body,
3694 } => {
3695 write!(f, "LET ${}: {} = ASYNC {{", var, decl_type)?;
3696 for s in body {
3697 write!(f, "\n {}", s)?;
3698 }
3699 write!(f, "\n}}")
3700 }
3701 StepKind::Await { var } => write!(f, "AWAIT ${}", var),
3702 StepKind::AwaitCapture {
3703 out_var,
3704 out_type,
3705 task_var,
3706 } => {
3707 write!(f, "LET ${}: {} = AWAIT ${}", out_var, out_type, task_var)
3708 }
3709 StepKind::Cancel { var } => write!(f, "CANCEL ${}", var),
3710 StepKind::Timeout { duration, body } => {
3711 let budget = fmt_raw_arg(duration);
3712 if body.len() == 1 {
3713 write!(f, "TIMEOUT {} {}", budget, body[0].kind)
3714 } else {
3715 write!(f, "TIMEOUT {} {{", budget)?;
3716 for s in body {
3717 write!(f, "\n {}", s)?;
3718 }
3719 write!(f, "\n}}")
3720 }
3721 }
3722 StepKind::Isolated { body } => {
3723 if body.len() == 1 {
3724 write!(f, "ISOLATED {}", body[0].kind)
3725 } else {
3726 write!(f, "ISOLATED {{")?;
3727 for s in body {
3728 write!(f, "\n {}", s)?;
3729 }
3730 write!(f, "\n}}")
3731 }
3732 }
3733 StepKind::IsolatedInheritEnv { keys } => {
3734 write!(f, "INHERIT_ENV [{}]", keys.join(", "))
3738 }
3739 StepKind::RemoteBlock {
3740 target,
3741 vars,
3742 env,
3743 body,
3744 } => {
3745 let mut entries: Vec<String> = vars.iter().map(|v| format!("${v}")).collect();
3746 entries.extend(env.iter().map(|e| format!("env:{e}")));
3747 if entries.is_empty() {
3748 write!(f, "REMOTE {target} {{")?;
3749 } else {
3750 write!(f, "REMOTE {target} [{}] {{", entries.join(", "))?;
3751 }
3752 for s in body {
3753 write!(f, "\n {}", s)?;
3754 }
3755 write!(f, "\n}}")
3756 }
3757 StepKind::FuncDef { name, params, body } => {
3758 let ps: Vec<String> = params
3759 .iter()
3760 .map(|(p, t)| format!("${}: {}", p, t))
3761 .collect();
3762 write!(f, "FUNC {}({}) {{", name, ps.join(", "))?;
3763 for s in body {
3764 write!(f, "\n {}", s)?;
3765 }
3766 write!(f, "\n}}")
3767 }
3768 StepKind::Call { name, args } => {
3769 let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
3770 write!(f, "{}({})", name, ps.join(", "))
3771 }
3772 StepKind::Return { expr } => write!(f, "RETURN {}", expr),
3773 StepKind::TypeAlias { name, target } => write!(f, "TYPE {} = {}", name, target),
3774 StepKind::While { cond, body } => {
3775 write!(f, "WHILE {} {{", cond)?;
3776 for s in body {
3777 write!(f, "\n {}", s)?;
3778 }
3779 write!(f, "\n}}")
3780 }
3781 StepKind::Break => write!(f, "BREAK"),
3782 StepKind::Continue => write!(f, "CONTINUE"),
3783 }
3784 }
3785}
3786
3787#[cfg(test)]
3788mod tests {
3789 use super::*;
3790 use crate::command::{
3791 format_byte_count, format_duration, parse_byte_count, parse_duration,
3792 strip_digit_separators,
3793 };
3794 use crate::parser::parse_script;
3795
3796 fn parse_err(script: &str) -> String {
3797 parse_script(script, lower_command)
3798 .expect_err("script must fail to parse")
3799 .to_string()
3800 }
3801
3802 #[test]
3803 fn malformed_with_io_binding_names_the_bad_binding() {
3804 let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
3805 assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
3806 assert!(!err.contains("unknown command"), "{err}");
3807 assert!(err.contains("stdout=discard"), "{err}");
3808 assert!(err.contains("[stdout=$p]"), "{err}");
3809 }
3810
3811 #[test]
3812 fn connect_is_unknown_command() {
3813 let err = parse_err("CONNECT 127.0.0.1:8080\n");
3816 assert!(err.contains("unknown command"), "{err}");
3817 assert!(err.contains("CONNECT"), "{err}");
3818 }
3819
3820 #[test]
3821 fn listen_is_unknown_command() {
3822 let err = parse_err("LISTEN 127.0.0.1:8080\n");
3825 assert!(err.contains("unknown command"), "{err}");
3826 assert!(err.contains("LISTEN"), "{err}");
3827 }
3828
3829 #[test]
3830 fn await_without_task_variable_points_at_syntax() {
3831 let err = parse_err("AWAIT ECHO \"test\"\n");
3832 assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
3833 assert!(!err.contains("unknown command"), "{err}");
3834 assert!(err.contains("AWAIT $t"), "{err}");
3835 assert!(err.contains("ECHO"), "{err}");
3836 }
3837
3838 #[test]
3839 fn bare_let_without_type_points_at_typed_syntax() {
3840 let err = parse_err("LET $x = 1\n");
3841 assert!(err.contains("invalid syntax for command LET"), "{err}");
3842 assert!(err.contains("LET $name: STRING = <expr>"), "{err}");
3843 }
3844
3845 #[test]
3846 fn workspace_accepts_all_four_targets_uppercase_only() {
3847 for (spelling, target) in [
3850 ("SNAPSHOT", WorkspaceTarget::Snapshot),
3851 ("LOCAL", WorkspaceTarget::Local),
3852 ("CACHE", WorkspaceTarget::Cache { local: false }),
3853 ("SYSTEM", WorkspaceTarget::System),
3854 ] {
3855 let steps =
3856 parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
3857 assert_eq!(steps.len(), 1);
3858 assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
3859 assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
3860 }
3861 for spelling in ["snapshot", "local", "cache", "system"] {
3862 let err = parse_err(&format!("WORKSPACE {spelling}\n"));
3863 assert!(
3864 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
3865 "{spelling}: {err}"
3866 );
3867 }
3868 let err = parse_err("WORKSPACE REMOTE\n");
3869 assert!(
3870 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
3871 "{err}"
3872 );
3873
3874 let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
3877 assert_eq!(
3878 steps[0].kind,
3879 StepKind::Workspace(WorkspaceTarget::Cache { local: true })
3880 );
3881 assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
3882 for bad in [
3883 "WORKSPACE SNAPSHOT --local\n",
3884 "WORKSPACE LOCAL --local\n",
3885 "WORKSPACE SYSTEM --local\n",
3886 ] {
3887 let err = parse_err(bad);
3888 assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
3889 }
3890 }
3891
3892 #[test]
3893 fn archive_unarchive_parse_and_round_trip() {
3894 let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
3895 match &steps[0].kind {
3896 StepKind::Archive { src, dst, raw } => {
3897 assert_eq!(src.as_str(), "bundle");
3898 assert_eq!(dst.as_str(), "bundle.tar.gz");
3899 assert!(!raw);
3900 }
3901 other => panic!("expected Archive, got {other:?}"),
3902 }
3903 assert_eq!(
3904 steps[0].kind.to_string(),
3905 "ARCHIVE bundle \"bundle.tar.gz\""
3906 );
3907
3908 let steps =
3909 parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
3910 assert!(
3911 matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
3912 "unexpected lowering: {:?}",
3913 steps[0].kind
3914 );
3915 assert_eq!(
3916 steps[0].kind.to_string(),
3917 "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
3918 );
3919
3920 let steps =
3921 parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
3922 match &steps[0].kind {
3923 StepKind::Unarchive {
3924 src,
3925 dst,
3926 max_bytes,
3927 } => {
3928 assert_eq!(src.as_str(), "pack.tar.gz");
3929 assert_eq!(dst.as_str(), "unpacked");
3930 assert_eq!(max_bytes, &None);
3931 }
3932 other => panic!("expected Unarchive, got {other:?}"),
3933 }
3934 assert_eq!(
3935 steps[0].kind.to_string(),
3936 "UNARCHIVE \"pack.tar.gz\" unpacked"
3937 );
3938
3939 let steps = parse_script(
3940 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
3941 lower_command,
3942 )
3943 .expect("parses");
3944 match &steps[0].kind {
3945 StepKind::Unarchive {
3946 src,
3947 dst,
3948 max_bytes,
3949 } => {
3950 assert_eq!(src.as_str(), "pack.tar.gz");
3951 assert_eq!(dst.as_str(), "unpacked");
3952 assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
3953 }
3954 other => panic!("expected Unarchive, got {other:?}"),
3955 }
3956 assert_eq!(
3957 steps[0].kind.to_string(),
3958 "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
3959 );
3960
3961 for script in [
3962 "ARCHIVE bundle bundle.tar.gz\n",
3963 "ARCHIVE --raw tool.bin tool.tar\n",
3964 "UNARCHIVE pack.tar.gz unpacked\n",
3965 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
3966 ] {
3967 let first = parse_script(script, lower_command).expect("parses");
3968 let rendered = first[0].kind.to_string() + "\n";
3969 let second = parse_script(&rendered, lower_command).expect("reparses");
3970 assert_eq!(
3973 second[0].kind.to_string(),
3974 first[0].kind.to_string(),
3975 "Display must fixpoint for {script:?}"
3976 );
3977 }
3978
3979 for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
3980 let err = parse_err(bad);
3981 assert!(
3982 err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
3983 "{bad}: {err}"
3984 );
3985 }
3986 }
3987
3988 #[test]
3989 fn copy_from_workspace_selects_source_root() {
3990 for (spelling, target) in [
3991 ("SNAPSHOT", WorkspaceTarget::Snapshot),
3992 ("LOCAL", WorkspaceTarget::Local),
3993 ("CACHE", WorkspaceTarget::Cache { local: false }),
3994 ("SYSTEM", WorkspaceTarget::System),
3995 ] {
3996 let steps = parse_script(
3997 &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
3998 lower_command,
3999 )
4000 .expect("parses");
4001 assert!(
4002 matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
4003 "unexpected lowering for {spelling}: {:?}",
4004 steps[0].kind
4005 );
4006 }
4007 for script in [
4010 "COPY --from-workspace=CACHE a.txt b.txt\n",
4011 "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
4012 ] {
4013 let steps = parse_script(script, lower_command).expect("parses");
4014 assert!(
4015 matches!(
4016 &steps[0].kind,
4017 StepKind::Copy {
4018 from_workspace: Some(WorkspaceTarget::Cache { local: false }),
4019 ..
4020 }
4021 ),
4022 "unexpected lowering for {script:?}: {:?}",
4023 steps[0].kind
4024 );
4025 }
4026 let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
4028 assert!(
4029 matches!(
4030 &steps[0].kind,
4031 StepKind::Copy {
4032 from_workspace: None,
4033 ..
4034 }
4035 ),
4036 "unexpected lowering: {:?}",
4037 steps[0].kind
4038 );
4039 for bad in ["REMOTE", "local"] {
4041 let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
4042 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4043 }
4044 }
4045
4046 #[test]
4047 fn symlink_from_workspace_selects_source_root() {
4048 for (spelling, target) in [
4049 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4050 ("LOCAL", WorkspaceTarget::Local),
4051 ("CACHE", WorkspaceTarget::Cache { local: false }),
4052 ("SYSTEM", WorkspaceTarget::System),
4053 ] {
4054 let steps = parse_script(
4055 &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
4056 lower_command,
4057 )
4058 .expect("parses");
4059 assert!(
4060 matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
4061 "unexpected lowering for {spelling}: {:?}",
4062 steps[0].kind
4063 );
4064 let roundtrip = steps[0].kind.to_string();
4065 assert!(
4066 roundtrip.contains("--from-workspace"),
4067 "display should round-trip the flag: {roundtrip}"
4068 );
4069 }
4070 let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
4071 assert!(
4072 matches!(
4073 &steps[0].kind,
4074 StepKind::Symlink {
4075 from_workspace: None,
4076 ..
4077 }
4078 ),
4079 "unexpected lowering: {:?}",
4080 steps[0].kind
4081 );
4082 for bad in ["REMOTE", "local"] {
4083 let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
4084 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4085 }
4086 let steps = parse_script(
4088 "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
4089 lower_command,
4090 )
4091 .expect("parses");
4092 assert!(
4093 matches!(
4094 &steps[0].kind,
4095 StepKind::Symlink {
4096 from_workspace: Some(WorkspaceTarget::Local),
4097 ..
4098 }
4099 ),
4100 "unexpected lowering: {:?}",
4101 steps[0].kind
4102 );
4103 }
4104
4105 #[test]
4106 fn dash_dash_equals_tokens_bypass_assignment() {
4107 let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
4110 let StepKind::Env { key, value } = &steps[0].kind else {
4111 panic!("expected Env, got {:?}", steps[0].kind);
4112 };
4113 assert_eq!(key, "--foo");
4114 assert_eq!(value.as_str(), "bar");
4115
4116 let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
4117 let StepKind::Run(cmd) = &steps[0].kind else {
4118 panic!("expected Run, got {:?}", steps[0].kind);
4119 };
4120 assert!(
4121 cmd.as_str().contains("--foo=bar"),
4122 "unexpected RUN lowering: {cmd:?}"
4123 );
4124
4125 let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
4126 let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
4127 .expect("parses");
4128 let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
4129 panic!("expected AssertEq, got {:?}", steps[0].kind);
4130 };
4131 assert_eq!(hash.as_deref(), Some(digest));
4132
4133 let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
4135 let StepKind::Expand { path, overrides } = &steps[0].kind else {
4136 panic!("expected Expand, got {:?}", steps[0].kind);
4137 };
4138 assert!(path.is_none());
4139 assert_eq!(overrides.len(), 1);
4140 assert_eq!(overrides[0].0.as_str(), "--k");
4141 }
4142
4143 #[test]
4144 fn space_before_paren_is_not_a_call() {
4145 let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
4148 assert_eq!(steps.len(), 1);
4149 assert!(
4150 !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
4151 "space before paren must not route to a call: {:?}",
4152 steps[0].kind
4153 );
4154 }
4155
4156 #[test]
4157 fn unknown_type_tag_parses_as_custom() {
4158 let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
4162 let StepKind::Assign { decl_type, .. } = &steps[0].kind else {
4163 panic!("expected Assign, got {:?}", steps[0].kind);
4164 };
4165 assert_eq!(decl_type, "FOO");
4166 }
4167
4168 #[test]
4169 fn bare_for_without_types_is_rejected() {
4170 let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
4171 assert!(err.contains("FOR requires explicit types"), "{err}");
4172 }
4173
4174 #[test]
4175 fn mutate_statement_parses_without_keyword() {
4176 let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
4177 assert!(matches!(steps[0].kind, StepKind::Set { .. }));
4178 }
4179
4180 #[test]
4181 fn set_keyword_is_rejected_with_mutation_hint() {
4182 let err = parse_err("SET $y = 2\n");
4183 assert!(err.contains("not a keyword"), "{err}");
4184 assert!(err.contains("$var = <expr>"), "{err}");
4185 }
4186
4187 #[test]
4188 fn structural_fallthrough_commits_per_keyword() {
4189 for (script, cmd) in [
4190 ("CANCEL foo\n", "CANCEL"),
4191 ("TIMEOUT foo\n", "TIMEOUT"),
4192 ("FOR foo\n", "FOR"),
4193 ("IF foo\n", "IF"),
4194 ("LET foo\n", "LET"),
4195 ("ASYNC\n", "ASYNC"),
4199 ("ELSE foo\n", "ELSE"),
4200 ] {
4201 let err = parse_err(script);
4202 assert!(
4203 err.contains(&format!("invalid syntax for command {cmd}")),
4204 "{cmd}: {err}"
4205 );
4206 assert!(!err.contains("unknown command"), "{cmd}: {err}");
4207 }
4208 }
4209
4210 #[test]
4211 fn leaf_arity_errors_carry_invalid_syntax_prefix() {
4212 let err = parse_err("SLEEP 1s 2s\n");
4213 assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
4214 assert!(!err.contains("unknown command"), "{err}");
4215 }
4216
4217 #[test]
4218 fn list_append_lowers_variable_and_item() {
4219 let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
4220 let StepKind::ListAppend { list, item } = &steps[0].kind else {
4221 panic!("expected ListAppend, got {:?}", steps[0].kind);
4222 };
4223 assert_eq!(list, "items");
4224 assert!(matches!(item, Arg::String(s, _) if s == "hi"));
4225 assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
4226 }
4227
4228 #[test]
4229 fn list_append_rejects_wrong_arity() {
4230 for script in [
4231 "LIST_APPEND\n",
4232 "LIST_APPEND $items\n",
4233 "LIST_APPEND $items \"a\" \"b\"\n",
4234 ] {
4235 let err = parse_err(script);
4236 assert!(
4237 err.contains("invalid syntax for command LIST_APPEND"),
4238 "{script}: {err}"
4239 );
4240 assert!(!err.contains("unknown command"), "{script}: {err}");
4241 }
4242 }
4243
4244 #[test]
4245 fn list_append_rejects_non_variable_target() {
4246 let err = parse_err("LIST_APPEND items \"a\"\n");
4247 assert!(
4248 err.contains("invalid syntax for command LIST_APPEND"),
4249 "{err}"
4250 );
4251 assert!(!err.contains("unknown command"), "{err}");
4252 }
4253
4254 #[test]
4255 fn read_line_rejects_bare_word_target() {
4256 let err = parse_err("READ_LINE reply\n");
4260 assert!(err.contains("READ_LINE requires a $variable"), "{err}");
4261 assert!(!err.contains("unknown command"), "{err}");
4262 }
4263
4264 #[test]
4265 fn genuinely_unknown_command_keeps_bare_message() {
4266 let err = parse_err("FROBNICATE hi\n");
4267 assert!(err.contains("unknown command: FROBNICATE"), "{err}");
4268 assert!(!err.contains("did you mean"), "{err}");
4269 }
4270
4271 #[test]
4272 fn lowercase_command_suggests_uppercase() {
4273 let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
4277 .expect_err("must fail")
4278 .to_string();
4279 assert!(err.contains("unknown command: echo"), "{err}");
4280 assert!(err.contains("did you mean `ECHO`"), "{err}");
4281 }
4282
4283 #[test]
4284 fn func_def_requires_typed_uppercase_name() {
4285 let steps = parse_script(
4286 "FUNC GREET($name: STRING) {\n RETURN $name\n}\n",
4287 lower_command,
4288 )
4289 .expect("func def parses");
4290 let StepKind::FuncDef { name, params, body } = &steps[0].kind else {
4291 panic!("expected FuncDef, got {:?}", steps[0].kind);
4292 };
4293 assert_eq!(name, "GREET");
4294 assert_eq!(
4295 params,
4296 &vec![("name".to_string(), "STRING".to_string())],
4297 "{params:?}"
4298 );
4299 assert!(matches!(body[0].kind, StepKind::Return { .. }));
4300 }
4301
4302 #[test]
4303 fn lowercase_func_name_is_rejected() {
4304 let err = parse_err("FUNC greet($x: STRING) {\n RETURN $x\n}\n");
4305 assert!(err.contains("FUNC"), "{err}");
4306 }
4307
4308 #[test]
4309 fn call_and_while_lower_correctly() {
4310 let steps = parse_script(
4311 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nGREET(\"ada\")\n",
4312 lower_command,
4313 )
4314 .expect("call parses");
4315 assert!(
4316 matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
4317 "{:?}",
4318 steps[1].kind
4319 );
4320 let steps = parse_script(
4321 "FUNC GREET($a: STRING, $b: STRING) {\n RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
4322 lower_command,
4323 )
4324 .expect("spaced call parses");
4325 assert!(
4326 matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
4327 "{:?}",
4328 steps[1].kind
4329 );
4330 let steps = parse_script(
4331 indoc! {r#"
4332 WHILE !$done {
4333 BREAK
4334 }
4335 "#},
4336 lower_command,
4337 )
4338 .expect("while parses");
4339 let StepKind::While { body, .. } = &steps[0].kind else {
4340 panic!("expected While, got {:?}", steps[0].kind);
4341 };
4342 assert!(matches!(body[0].kind, StepKind::Break));
4343 }
4344
4345 #[test]
4346 fn let_capture_call_and_async_call_lower() {
4347 let steps = parse_script(
4350 indoc! {r#"
4351 FUNC GREET($name: STRING) {
4352 RETURN $name
4353 }
4354 LET $r: STRING = GREET("ada")
4355 "#},
4356 lower_command,
4357 )
4358 .expect("capture call parses");
4359 let StepKind::Assign { var, expr, .. } = &steps[1].kind else {
4360 panic!("expected Assign, got {:?}", steps[1].kind);
4361 };
4362 assert_eq!(var, "r");
4363 assert!(
4364 matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
4365 "{expr:?}"
4366 );
4367 let steps = parse_script(
4368 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nLET $t: HANDLE = ASYNC GREET(\"a\")\n",
4369 lower_command,
4370 )
4371 .expect("async call parses");
4372 assert!(
4373 matches!(&steps[1].kind, StepKind::AssignAsync { .. }),
4374 "{:?}",
4375 steps[1].kind
4376 );
4377 }
4378
4379 #[test]
4380 fn multiline_call_args_span_lines() {
4381 let steps = parse_script(
4385 "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",
4386 lower_command,
4387 )
4388 .expect("multiline call parses");
4389 let StepKind::Assign { expr, .. } = &steps[1].kind else {
4390 panic!("expected Assign, got {:?}", steps[1].kind);
4391 };
4392 let Expr::Call { name, args } = expr else {
4393 panic!("expected Call expr, got {expr:?}");
4394 };
4395 assert_eq!(name, "SCRIPT::SERVE");
4396 assert_eq!(args.len(), 4);
4397 assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
4398 let rendered = steps[1].to_string();
4400 assert!(!rendered.contains('\n'), "{rendered}");
4401 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";
4402 let again = parse_script(script, lower_command).expect("reparse ok");
4403 assert_eq!(again, steps);
4404 }
4405
4406 #[test]
4407 fn multiline_bare_call_and_list_span_lines() {
4408 let steps = parse_script(
4409 indoc! {r#"
4410 FUNC GREET($a: STRING) {
4411 RETURN $a
4412 }
4413 GREET(
4414 "ada"
4415 )
4416 "#},
4417 lower_command,
4418 )
4419 .expect("multiline bare call parses");
4420 let StepKind::Call { name, args } = &steps[1].kind else {
4421 panic!("expected Call, got {:?}", steps[1].kind);
4422 };
4423 assert_eq!(name, "SCRIPT::GREET");
4424 assert_eq!(args.len(), 1);
4425 let steps = parse_script(
4426 indoc! {r#"
4427 LET $l: LIST = [
4428 "a",
4429 "b"
4430 ]
4431 "#},
4432 lower_command,
4433 )
4434 .expect("multiline list parses");
4435 let StepKind::Assign { expr, .. } = &steps[0].kind else {
4436 panic!("expected Assign, got {:?}", steps[0].kind);
4437 };
4438 assert!(
4439 matches!(expr, Expr::List(items) if items.len() == 2),
4440 "{expr:?}"
4441 );
4442 }
4443
4444 #[test]
4445 fn parse_duration_units() {
4446 use std::time::Duration;
4447 assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4448 assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
4449 assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
4450 assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4451 assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
4452 assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
4454 assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
4455 }
4456
4457 #[test]
4458 fn parse_duration_rejects_garbage() {
4459 assert!(parse_duration("").is_err());
4460 assert!(parse_duration("banana").is_err());
4461 assert!(parse_duration("10x").is_err());
4462 assert!(parse_duration("0s").is_err());
4463 assert!(parse_duration("0").is_err());
4464 assert!(parse_duration("-5s").is_err());
4465 assert!(parse_duration("30 s s").is_err());
4467 assert!(parse_duration("3 0s").is_err());
4468 }
4469
4470 #[test]
4471 fn parse_byte_count_units() {
4472 assert_eq!(parse_byte_count("500").unwrap(), 500);
4473 assert_eq!(parse_byte_count("500B").unwrap(), 500);
4474 assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
4475 assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
4476 assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
4477 assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
4478 assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
4479 assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
4480 assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
4481 assert_eq!(
4482 parse_byte_count("1TIB").unwrap(),
4483 1_024 * 1_024 * 1_024 * 1_024
4484 );
4485 assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
4487 assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
4488 assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
4489 assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
4490 assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
4492 assert_eq!(
4493 parse_byte_count("1_000_000_000_000").unwrap(),
4494 1_000_000_000_000
4495 );
4496 assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
4497 assert_eq!(
4498 parse_byte_count("1_0GiB").unwrap(),
4499 10 * 1_024 * 1_024 * 1_024
4500 );
4501 assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
4503 assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
4504 assert_eq!(parse_byte_count(" 2MB ").unwrap(), 2_000_000);
4505 assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
4507 assert!(parse_byte_count("-1 GB").is_err());
4508 }
4509
4510 #[test]
4511 fn parse_byte_count_rejects_garbage() {
4512 for bad in [
4513 "",
4514 "banana",
4515 "10x",
4516 "1G",
4517 "1K",
4518 "1.5GB",
4519 "-5",
4520 "-5GB",
4521 "0",
4522 "0GB",
4523 "_100",
4524 "100_",
4525 "1__000",
4526 "_",
4527 "1_GB",
4528 "1 G B",
4530 "1 2",
4531 "1 0",
4532 "1000000000000000000000000",
4534 "1000000000TB",
4535 ] {
4536 assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
4537 }
4538 }
4539
4540 #[test]
4541 fn format_byte_count_round_trips() {
4542 for text in [
4543 "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
4544 ] {
4545 let parsed = parse_byte_count(text).unwrap();
4546 let rendered = format_byte_count(parsed);
4547 assert_eq!(
4548 parse_byte_count(&rendered).unwrap(),
4549 parsed,
4550 "round-trip failed for {text}"
4551 );
4552 }
4553 assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
4554 assert_eq!(format_byte_count(1_000_000_000), "1GB");
4555 }
4556
4557 #[test]
4558 fn strip_digit_separators_passes_signs_through() {
4559 assert_eq!(strip_digit_separators("-1_000"), "-1000");
4563 assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
4564 assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
4565 assert_eq!(strip_digit_separators("1_000"), "1000");
4566 for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
4567 assert_eq!(strip_digit_separators(untouched), untouched);
4568 }
4569 assert!(parse_byte_count("-1_000").is_err());
4572 assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
4573 }
4574
4575 #[test]
4576 fn format_byte_count_is_lossless() {
4577 for n in [
4582 1,
4583 500,
4584 999,
4585 1_000,
4586 1_024,
4587 1_500,
4588 1_000_000,
4589 1_048_576,
4590 1_000_000_000,
4591 1_073_741_824,
4592 1_000_000_000_000,
4593 1_099_511_627_776,
4594 u64::MAX,
4595 ] {
4596 assert_eq!(
4597 parse_byte_count(&format_byte_count(n)).unwrap(),
4598 n,
4599 "lossless round-trip failed for {n}"
4600 );
4601 }
4602 }
4603
4604 #[test]
4605 fn format_duration_round_trips() {
4606 for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
4607 let parsed = parse_duration(text).unwrap();
4608 let rendered = format_duration(&parsed);
4609 assert_eq!(
4610 parse_duration(&rendered).unwrap(),
4611 parsed,
4612 "round-trip failed for {text}"
4613 );
4614 }
4615 assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
4616 assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
4617 }
4618
4619 #[test]
4620 fn structural_metadata_covers_all_structural_kinds() {
4621 use crate::ast::Value;
4622
4623 fn metadata_name(kind: &StepKind) -> Option<&'static str> {
4627 match kind {
4628 StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some("WITH_IO"),
4629 StepKind::For { .. } => Some("FOR"),
4630 StepKind::If { .. } => Some("IF"),
4631 StepKind::Assign { .. } => Some("LET"),
4632 StepKind::Set { .. } => Some("MUTATION"),
4633 StepKind::AssignCapture { .. } => Some("LET"),
4634 StepKind::AwaitCapture { .. } => Some("AWAIT"),
4635 StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => Some("ASYNC"),
4636 StepKind::Await { .. } => Some("AWAIT"),
4637 StepKind::Cancel { .. } => Some("CANCEL"),
4638 StepKind::Timeout { .. } => Some("TIMEOUT"),
4639 StepKind::Isolated { .. } => Some("ISOLATED"),
4640 StepKind::IsolatedInheritEnv { .. } => Some("ISOLATED"),
4641 StepKind::RemoteBlock { .. } => Some("REMOTE"),
4642 StepKind::FuncDef { .. } => Some("FUNC"),
4643 StepKind::Call { .. } => None,
4646 StepKind::Return { .. } => Some("RETURN"),
4647 StepKind::While { .. } => Some("WHILE"),
4648 StepKind::Break => Some("BREAK"),
4649 StepKind::Continue => Some("CONTINUE"),
4650 StepKind::TypeAlias { .. } => Some("LET"),
4654 StepKind::RunExec { .. } => None,
4655 StepKind::Workdir(_)
4656 | StepKind::Workspace(_)
4657 | StepKind::Env { .. }
4658 | StepKind::InheritEnv { .. }
4659 | StepKind::Run(_)
4660 | StepKind::Echo(_)
4661 | StepKind::Copy { .. }
4662 | StepKind::Symlink { .. }
4663 | StepKind::Mkdir(_)
4664 | StepKind::Archive { .. }
4665 | StepKind::Unarchive { .. }
4666 | StepKind::Install { .. }
4667 | StepKind::Ls(_)
4668 | StepKind::Cwd
4669 | StepKind::Read(_)
4670 | StepKind::ReadLine { .. }
4671 | StepKind::Prompt { .. }
4672 | StepKind::Write { .. }
4673 | StepKind::Append { .. }
4674 | StepKind::Remove { .. }
4675 | StepKind::Expand { .. }
4676 | StepKind::AssertEq { .. }
4677 | StepKind::AssertContains { .. }
4678 | StepKind::CopyGit { .. }
4679 | StepKind::HashSha256 { .. }
4680 | StepKind::Exit(_)
4681 | StepKind::Sleep { .. }
4682 | StepKind::ListAppend { .. } => None,
4683 }
4684 }
4685
4686 let dummies: Vec<StepKind> = vec![
4689 StepKind::WithIo {
4690 bindings: Vec::new(),
4691 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
4692 "x".to_string(),
4693 false,
4694 ))),
4695 },
4696 StepKind::For {
4697 key_var: None,
4698 key_type: None,
4699 var: "i".to_string(),
4700 var_type: "STRING".to_string(),
4701 in_expr: Expr::Literal(Value::bool(true)),
4702 body: Vec::new(),
4703 },
4704 StepKind::If {
4705 cond: Box::new(Expr::Literal(Value::bool(true))),
4706 then_body: Vec::new(),
4707 else_ifs: Vec::new(),
4708 else_body: None,
4709 },
4710 StepKind::Assign {
4711 var: "v".to_string(),
4712 decl_type: "BOOL".to_string(),
4713 expr: Expr::Literal(Value::bool(true)),
4714 },
4715 StepKind::Set {
4716 var: "v".to_string(),
4717 expr: Expr::Literal(Value::bool(true)),
4718 },
4719 StepKind::AssignCapture {
4720 var: "v".to_string(),
4721 decl_type: "STRING".to_string(),
4722 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
4723 "x".to_string(),
4724 false,
4725 ))),
4726 },
4727 StepKind::AwaitCapture {
4728 out_var: "o".to_string(),
4729 out_type: "STRING".to_string(),
4730 task_var: "t".to_string(),
4731 },
4732 StepKind::AsyncBlock { body: Vec::new() },
4733 StepKind::AssignAsync {
4734 var: "t".to_string(),
4735 decl_type: "HANDLE".to_string(),
4736 body: Vec::new(),
4737 },
4738 StepKind::Await {
4739 var: "t".to_string(),
4740 },
4741 StepKind::Cancel {
4742 var: "t".to_string(),
4743 },
4744 StepKind::Timeout {
4745 duration: Arg::String("1s".to_string(), false),
4746 body: Vec::new(),
4747 },
4748 StepKind::Isolated { body: Vec::new() },
4749 StepKind::IsolatedInheritEnv { keys: Vec::new() },
4750 StepKind::RemoteBlock {
4751 target: "prod".to_string(),
4752 vars: Vec::new(),
4753 env: Vec::new(),
4754 body: Vec::new(),
4755 },
4756 StepKind::FuncDef {
4757 name: "F".to_string(),
4758 params: Vec::new(),
4759 body: Vec::new(),
4760 },
4761 StepKind::Call {
4762 name: "F".to_string(),
4763 args: Vec::new(),
4764 },
4765 StepKind::Return {
4766 expr: Box::new(Expr::Literal(Value::bool(true))),
4767 },
4768 StepKind::While {
4769 cond: Box::new(Expr::Literal(Value::bool(true))),
4770 body: Vec::new(),
4771 },
4772 StepKind::Break,
4773 StepKind::Continue,
4774 StepKind::TypeAlias {
4775 name: "PERSON".to_string(),
4776 target: "MAP<name: STRING>".to_string(),
4777 },
4778 ];
4779 let registry = all_structural_metadata();
4780 for kind in &dummies {
4781 let Some(name) = metadata_name(kind) else {
4783 continue;
4784 };
4785 assert!(
4786 registry.iter().any(|meta| meta.name == name),
4787 "no structural metadata entry for {}",
4788 name
4789 );
4790 }
4791 }
4792}