Run a program in the target repository
Run a program in a shell step when your pipeline needs to know whether the code of the target repository passes its tests, its linter or its build. In this guide you run run_program, the example pipeline that runs one program with cb.shell_step, on a small repository with a test. At the end, codeband run prints ✓ program#0 exit code 0 for a test that passes, stopped: the program exited with code 1: and the test’s output for a test that fails, and hello, Grace from a program that got the variable GREETER_NAME by name. If a function step fails, see Troubleshooting at the end of this page.
Before you start
Section titled “Before you start”- You did the Quickstart: you have a clone of codeband with the binary at
build/codeband, and the tools that the Quickstart lists. - jq for the check at the end, as
jq --versionshows. - Your terminal is in the
codebandfolder. Run each command from there unless a function step says otherwise.
How a shell step runs
Section titled “How a shell step runs”A shell step runs one program in a new workspace: a checked-out commit of the target repository, by default the run head, which the engine makes for this one step and removes after it. The engine, the part of the daemon that executes runs, runs the program, not the code server. The program gets PATH, HOME and USER from the daemon’s environment, the variables of the [env] table of the config file, and each variable that the shell step names. Nothing else of the daemon’s environment reaches it. A program that fails raises no error in your pipeline code. Your code reads how the program ended and decides what follows.
-
Call
cb.shell_stepin the pipelinerun_programinexamples/py-factoryruns the program of its run input and stops the run when the program fails:examples/py-factory/py_factory/program.py """The pipeline run_program: a shell step that runs a program in the target repository.The engine runs the program, not the code server. It runs it in a new workspace, which holds the files of the run head, anddiscards what the program changes there."""from datetime import timedeltafrom typing import Annotated, Finalimport codeband as cbfrom pydantic import Field_OUTPUT_LINES: Final = 10"""How many of the last output lines the stop reason holds."""# The hints of the run input's fields, which the start form of the web interface shows.Argv = Annotated[tuple[str, ...],Field(description='The program and its arguments. No shell reads them: write ["sh", "-c", "..."] to use one.'),]Env = Annotated[tuple[str, ...],Field(description="Names of variables of the daemon's environment. The run records the names, never the values."),]@cb.pipelinedef run_program(argv: Argv, env: Env = (), timeout_seconds: int = 600) -> cb.RunResult | None:"""Run the program in the target repository. The run stops when the program fails.A failed program does not raise: the shell step gives ok=False, and the pipeline code decides what follows."""result = cb.shell_step(argv, name="program", env=env, timeout=timedelta(seconds=timeout_seconds))if not result.ok:raise cb.Stop(stop_reason(result))return Nonedef stop_reason(result: cb.ShellStep) -> str:"""Say how the program ended, followed by the last lines of its output."""if result.timed_out:reason = "the program ran longer than its timeout"elif result.exit_code is None:# The program did not start, a signal stopped it, or the daemon's environment does not set a named variable.reason = "the program did not run to its end"else:reason = f"the program exited with code {result.exit_code}"lines = result.output_tail.rstrip("\n").splitlines()[-_OUTPUT_LINES:]if not lines:return f"{reason} and wrote no output"return reason + ":\n" + "\n".join(lines)run_programpasses each argument ofcb.shell_stepfrom its run input, so one pipeline can run any program:Argument run_programpassesWhat it does argvargvof the run inputThe program and its arguments. No shell reads them, so ["sh", "-c", "make test && make lint"]is how to use onename"program"The name of the shell step. Its first call has the step ID program#0envenvof the run inputThe names of the variables that the program gets from the daemon’s environment timeouttimeout_secondsof the run input, 600 by defaultThe engine stops the program after this time. Without it, the timeout is 10 minutes In a pipeline of your own, the program is usually fixed, such as
cb.shell_step(["make", "test"], name="tests"). The reference lists the other argument,at, which starts the workspace at another commit. -
Read how the program ended
cb.shell_stepreturns acb.ShellStepwhen the program has ended.stop_reasonin the same file reads four of its fields:Field Holds run_programuses it forokTruewhen the program exited with code 0 within its timeoutStopping the run when it is Falseexit_codeThe exit code, or Nonewhen it is unknown: after a timeout or a signal, or when the program did not startthe program exited with code Ntimed_outTruewhen the program ran longer than its timeoutthe program ran longer than its timeoutoutput_tailThe last 64 KiB of standard output and standard error, in the order the program wrote them The last 10 lines of the stop reason Test
ok, notexit_code. A program that timed out or did not start hasexit_codeNone, whichif result.exit_code:reads as a success.run_programraisescb.Stopwith the reason, socodeband runprints it and exits with code 3. -
Start the daemon and the code server with a variable
If
codeband devfrom the Quickstart still runs, press Ctrl-C in its terminal. Open a second terminal, change to thecodebandfolder and startcodeband devin the example, with a variable in its environment:Terminal window GREETER_NAME=Grace just examples/py-factory/devThe code server logs the pipelines it loaded,
run_programamong them, and the daemon logsListening. Both keep running:Output Nov 25 20:56:22.670 INF Loaded pipelines comp=codeserver pipelines="[intake run_program ship_feature write_hello]" folder=…/codeband/examples/py-factoryNov 25 20:56:22.698 INF Serving pipelines comp=codeserver address=unix:~/.local/state/codeband/codeserver.sock…Nov 25 20:56:22.710 INF Listening comp=daemon socket=…/codeband/daemon.sockGREETER_NAMEis now in the daemon’s environment. No program gets it until a shell step names it, as step 6 does. -
Make a target repository
Back in the first terminal, make a git repository with a program and its test:
Terminal window git init /tmp/greetcat > /tmp/greet/greet.sh <<'EOF'echo "hello, ${GREETER_NAME:-world}"EOFcat > /tmp/greet/test.sh <<'EOF'got=$(GREETER_NAME=Ada sh greet.sh)if [ "$got" = "hello, Ada" ]; thenecho "ok: greet.sh greets Ada"elseecho "FAIL: greet.sh printed '$got'"exit 1fiEOFgit -C /tmp/greet add greet.sh test.shgit -C /tmp/greet commit -m "Add greet.sh and its test"greet.shgreets the name inGREETER_NAME, orworldwhen the variable is not set.test.shchecks that it greets Ada, and exits with code 1 when it doesn’t. The last command prints the new commit and2 files changed. A run starts at theHEADcommit of its target repository, so the files must be committed. -
Run the test
codeband devserves the example under the name of its folder,py-factory, so the pipeline ispy-factory/run_program.Terminal window build/codeband run -v --repo /tmp/greet py-factory/run_program --input '{"argv": ["sh", "test.sh"]}'The program runs in the root of the workspace, so
test.shis a path in the repository.-vprints the output of the program as it comes. The test passes, socodeband runprintsno code changeand exits with code 0. Your run ID is different:Output Started run hprcv1my8z▸ program#0 shell step: sh test.shok: greet.sh greets Ada✓ program#0 exit code 0 after 0.1sno code changeWithout
-v,codeband runprints the output of a shell step only when it fails, as its last 20 lines. -
Pass an environment variable by name
Run
greet.shwithout naming the variable:Terminal window build/codeband run -v --repo /tmp/greet py-factory/run_program --input '{"argv": ["sh", "greet.sh"]}'The daemon’s environment holds
GREETER_NAME, but the program doesn’t get it, so it printshello, world:Output Started run pmnz8xv9d4▸ program#0 shell step: sh greet.shhello, world✓ program#0 exit code 0 after 0.1sno code changeNow name the variable in
envof the run input, whichrun_programpasses tocb.shell_step:Terminal window build/codeband run -v --repo /tmp/greet py-factory/run_program --input '{"argv": ["sh", "greet.sh"], "env": ["GREETER_NAME"]}'The program gets the daemon’s value and prints
hello, Grace:Output Started run fb77p5rh6m▸ program#0 shell step: sh greet.shhello, Grace✓ program#0 exit code 0 after 0.1sno code changeThe run records the name
GREETER_NAME, never its value, so a token can reach a program this way. We recommendenvofcb.shell_stepfor a variable that one program needs. A variable that every shell step and every agent step needs, such as a token from a password manager, fits the[env]table ofcodeband.tomlbetter. -
See a test fail
Change
greet.shso that it sayshi, commit the change and run the test again, without-v:Terminal window echo 'echo "hi, ${GREETER_NAME:-world}"' > /tmp/greet/greet.shgit -C /tmp/greet commit -am "Say hi instead of hello"build/codeband run --repo /tmp/greet py-factory/run_program --input '{"argv": ["sh", "test.sh"]}'The test exits with code 1, so the shell step is not ok, and
run_programstops the run.codeband runexits with code 3:Output Started run ytbn5khhtj▸ program#0 shell step: sh test.sh✗ program#0 exit code 1 after 0.1s│ FAIL: greet.sh printed 'hi, Ada'stopped: the program exited with code 1:FAIL: greet.sh printed 'hi, Ada'codeband runprints the✗line and, without-v, the last 20 output lines after│for every failed shell step. The line afterstopped:is the reason thatstop_reasonbuilt fromexit_codeandoutput_tail.
Check that it worked
Section titled “Check that it worked”The run journal records the names of the variables that the program got, and no value. Print them for the run of step 6 that named GREETER_NAME:
jq -c '.stepStarted.shellStep // empty | {env, variables}' \ ~/.local/state/codeband/store/runs/RUN_ID/journal.jsonlPut the run ID that codeband run printed in place of RUN_ID. The command prints one line:
{"env":["GREETER_NAME"],"variables":["GREETER_NAME"]}env is what the shell step named, and variables holds the names of every variable that the program got from [env] and from env. When the daemon’s environment holds a login such as ANTHROPIC_API_KEY, variables names it too, because every shell step gets it. The run of greet.sh without env prints {"env":null,"variables":null}.
Optional: Limit how long the program runs
Section titled “Optional: Limit how long the program runs”Give the program a timeout shorter than its run time:
build/codeband run --repo /tmp/greet py-factory/run_program --input '{"argv": ["sleep", "5"], "timeout_seconds": 1}'After one second the engine sends SIGTERM to the program, and SIGKILL 10 seconds later if it still runs. The shell step has timed_out True and exit_code None, and the run stops with exit code 3:
Started run 4ggyyzkcn0▸ program#0 shell step: sleep 5✗ program#0 timed out after 1.1sstopped: the program ran longer than its timeout and wrote no outputClean up
Section titled “Clean up”Run rm -rf /tmp/greet and press Ctrl-C in the terminal of codeband dev.
Troubleshooting
Section titled “Troubleshooting”For an error that this page doesn’t cover, see Run problems.
codeband: the daemon's environment does not set GREETER_NAME
Section titled “codeband: the daemon's environment does not set GREETER_NAME”The shell step names GREETER_NAME, but you started codeband dev without it. The engine does not start the program, so the shell step is not ok, its exit_code is None, and the run stops with stopped: the program did not run to its end: and this line. Press Ctrl-C in the terminal of codeband dev and start it again as in step 3.
codeband: start greet.sh: exec: "greet.sh": executable file not found in $PATH
Section titled “codeband: start greet.sh: exec: "greet.sh": executable file not found in $PATH”The first item of argv has no /, so the engine looks for the program on the PATH, not in the workspace. The program does not start, so the run stops:
✗ program#0 failed after 0.1s │ codeband: start greet.sh: exec: "greet.sh": executable file not found in $PATHstopped: the program did not run to its end:codeband: start greet.sh: exec: "greet.sh": executable file not found in $PATHRun the file through its interpreter, as in ["sh", "greet.sh"].
The program exits with code 126 and prints nothing, but passes in your terminal
Section titled “The program exits with code 126 and prints nothing, but passes in your terminal”The program of a shell step does not get the variables that your shell profile sets, and a tool manager such as asdf needs them. The line reads ✗ program#0 exit code 126 after 0.1s. Add the variables that the tool needs to the [env] table of codeband.toml, as A shell step fails, but the same command passes in an agent step shows.
The test passes after you changed greet.sh, and codeband run logs The repository has uncommitted changes. The run does not see them.
Section titled “The test passes after you changed greet.sh, and codeband run logs The repository has uncommitted changes. The run does not see them.”A run starts at the HEAD commit of its target repository, so the workspace has greet.sh as you last committed it. Commit the change with git -C /tmp/greet commit -am "Say hi instead of hello" and start the run again.
Related
Section titled “Related”- Step: the workspace of a shell step, the variables its program gets, and how the engine stops it.
- Python SDK: every argument of
cb.shell_stepand every field ofcb.ShellStep,changed_pathsamong them. - codeband.toml: the
[env]table and the order in which a program gets its variables. - codeband CLI: every line that
codeband runprints while it follows a run.