Doc system test

Post-template commands

How the shell commands templates list are collected from every current template tree and run in the folder after the files are written.

Meta block front matter of this doc
namespaces
  • durian.cloud/cyanprint/project-lifecycle
  • durian.cloud/cyanprint/composition
type
algorithm
code
  • sulfone.iridium/cyanprint/src/command_executor.rs
  • sulfone.iridium/cyanprint/src/run.rs
  • sulfone.iridium/cyancoordinator/src/operations/composition/operator.rs

The problem. Some templates need a step after their files exist: npm install, git init, a code generator. The CLI must run them in the right folder, let a person stop them, and not break the machine-readable output of a headless run.

The idea. Each template version lists its post-template commands in cyan.yaml; the registry stores them with the version. After a batch run writes the folder and saves the state file, the CLI runs every command of every current template tree, in order, with sh -c in the target folder.

The picture shows the two ways commands run.

flowchart TD
  C["commands from every node of every current template spec"] --> F[drop blank commands]
  F --> H{headless?}
  H -- no --> L["list them; ask: Do you want to proceed with execution? (default No)"]
  L -- No --> AB[aborted: run fails]
  L -- Yes --> RI["run each with sh -c in the folder"]
  RI -- a command fails --> Q["ask: continue? (default No)"]
  Q -- No --> AB
  Q -- Yes --> RI
  H -- yes --> RH["run each with sh -c; its stdout goes to stderr"]
  RH --> E{any failed?}
  E -- yes --> ER[error envelope, exit 1]
  E -- no --> D[done]
  RI --> D
Interactive and headless command runs

How it works

  1. Collect. For each current template spec, the commands of every node in its flattened tree are appended in run order (children first). Previous specs give none: they only build the merge base.
  2. Filter. Blank or whitespace-only commands are dropped.
  3. Run, interactive. The list is printed; the user confirms (default No). Each command runs with sh -c in the target folder, one after another. On a failure the user is asked whether to continue (default No).
  4. Run, headless. No prompts. Every command runs; its stdout and stderr are captured and written to stderr, so stdout keeps only the JSON envelope. Any failure makes the run an error (exit 1).
  5. Outcome. A refusal or an abort fails the command with "Command execution aborted". The files and the state file are already written by then.

Here is the real code.

sulfone.iridiumcyancoordinator/src/operations/composition/operator.rs
  1. lines 702-711Commands of every node in the flattened tree, in run order; no de-duplication.
    cyancoordinator/src/operations/composition/operator.rs:702-711rust
    pub fn collect_commands(dependencies: &[ResolvedDependency]) -> Vec<String> {
    let mut commands = Vec::new();
    for dep in dependencies {
    let template_commands = &dep.template.commands;
    if !template_commands.is_empty() {
    commands.extend(template_commands.iter().cloned());
    }
    }
    commands
    }
  2. sulfone.iridium/cyanprint/src/run.rs:337-339Only current specs' commands: the previous specs are just the merge base.
    cyanprint/src/run.rs:337-339rust
    // Use resolved commands from execute_template which includes the full dependency tree
    // (prev is just the 3-way-merge baseline; its commands would be duplicates or stale)
    let all_commands = curr_resolved_commands;
  3. sulfone.iridium/cyanprint/src/command_executor.rs:52-57Blank commands are dropped.
    cyanprint/src/command_executor.rs:52-57rust
    // feeds local cyan.yaml entries directly into this executor.
    let commands: Vec<&str> = commands
    .iter()
    .map(String::as_str)
    .filter(|cmd| !cmd.trim().is_empty())
    .collect();
  4. sulfone.iridium/cyanprint/src/command_executor.rs:69-78Interactive: one approval for the whole list, default No.
    cyanprint/src/command_executor.rs:69-78rust
    let proceed = Confirm::new("Do you want to proceed with execution?")
    .with_default(false)
    .prompt()
    .map_err(|e| Box::new(e) as Box<dyn Error + Send>)?;
    if !proceed {
    let mut result = CommandExecutionResult::new(commands.len());
    result.aborted = true;
    println!("⏹️ Command execution cancelled by user");
    return Ok(result);
  5. sulfone.iridium/cyanprint/src/command_executor.rs:89-120sh -c in the target folder; on failure, ask to continue, default No.
    cyanprint/src/command_executor.rs:89-120rust
    let exit_status = Command::new("sh")
    .arg("-c")
    .arg(cmd)
    .current_dir(working_dir)
    .spawn()
    .map_err(|e| Box::new(e) as Box<dyn Error + Send>)?
    .wait()
    .map_err(|e| Box::new(e) as Box<dyn Error + Send>)?;
    if exit_status.success() {
    println!(" ✅ Success");
    result.succeeded += 1;
    } else {
    let exit_code = exit_status.code().unwrap_or(-1);
    println!(" ❌ Failed (exit code: {exit_code})");
    result.failed += 1;
    result.failed_indices.push(i);
    // Ask user whether to continue
    let continue_prompt = Confirm::new(&format!(
    "Command failed (exit code: {exit_code}). Continue executing remaining commands?",
    ))
    .with_default(false)
    .prompt()
    .map_err(|e| Box::new(e) as Box<dyn Error + Send>)?;
    if !continue_prompt {
    result.aborted = true;
    println!("⏹️ Command execution aborted by user");
    break;
    }
    }
  6. sulfone.iridium/cyanprint/src/command_executor.rs:168-186Headless: capture both streams and forward them to stderr.
    cyanprint/src/command_executor.rs:168-186rust
    for (i, cmd) in commands.iter().copied().enumerate() {
    let mut command = Command::new("sh");
    command.arg("-c").arg(cmd).current_dir(working_dir);
    let exit_status = if suppress_stdout {
    // Capture stdout+stderr (no inherited fds → nothing reaches the process's
    // stdout), then forward both to STDERR so the output stays visible without
    // breaking the machine-readable stdout contract. `output()` reads both
    // pipes to completion, so there is no fill-the-buffer deadlock.
    let out = command
    .output()
    .map_err(|e| Box::new(e) as Box<dyn Error + Send>)?;
    if !out.stdout.is_empty() {
    eprint!("{}", String::from_utf8_lossy(&out.stdout));
    }
    if !out.stderr.is_empty() {
    eprint!("{}", String::from_utf8_lossy(&out.stderr));
    }
    out.status
  7. sulfone.iridium/cyanprint/src/run.rs:900-913Headless: any failed command turns done into an error.
    cyanprint/src/run.rs:900-913rust
    if headless && !exec_result.all_succeeded() {
    // The non-interactive path runs every command and records failures in
    // the result but returns Ok — it never sets `aborted`. Without this check a
    // failed post-template command (e.g. a command exiting non-zero) would be
    // silently ignored and the run would report `done` / exit 0. In headless mode
    // there is no interactive "continue?" prompt to surface the failure, so treat
    // any partial failure as an error → error envelope / exit 1 (the still-armed
    // `session_guard` releases the sessions on return). Interactive mode keeps its
    // existing behavior: the user already chose whether to continue.
    return Err(Box::new(std::io::Error::other(format!(
    "Command execution failed: {}/{} succeeded, {}/{} failed",
    exec_result.succeeded, exec_result.total, exec_result.failed, exec_result.total
    ))));
    }

Worked example: ./shop, steps 1 and 3

node-base:3 and ci:2 each list npm install (from the shop example). Step through which commands run.

Commands in ./shop
  1. Step 1: create web:5

    One current spec, web:5. Its tree is docker:7, lint:2, node-base:3, web:5; only node-base:3 has a command.

    commandsnpm install
    runs1
  2. Step 3: create ci:2

    Two current specs. web:5's tree gives npm install again; ci:2 adds its own. Nothing removes the duplicate.

    commandsnpm install, npm install
    runs2
  3. Step 4: update

    Current specs web:6 and ci:2: the same two commands run again, whether or not anything changed.

    commandsnpm install, npm install
    runs2

Why it works this way

Hard cases

  • Commands run on every create and update, for every stacked template, changed or not.
  • No de-duplication. The same command from two trees runs twice.
  • Files first, commands after. A failed command never rolls back the written files or the state file.
  • Commands from a dependency run too, in run order: a dependency's command runs before its parent's.
  • Interactive default is No. Pressing Enter at the approval skips every command and fails the run.

Questions for the designer

  1. Should commands run only for templates whose version or answers changed?
  2. Should identical commands from different trees run once?