Cmd
type Cmd = { program: string, args: Array[string] = [], dir: string | null = null, env: Map[string, string] | null = null }Cmd is a program to run, as a value: a Cmd says what to run, and a function of Cmd says how. Nothing runs it through a shell. program is looked up in PATH when it has no path separator, and is taken relative to dir otherwise; the child runs in dir and with env as its whole environment when they are given. A child ended by signal n has the status 128 + n, as a shell reports it.
A Cmd is a record that names a program, its arguments, and optionally the directory and environment it runs in. Building one runs nothing. The functions of the Cmd namespace run it: in the foreground, for its output, for its status and both outputs, or in the background. A command is built once and then run, logged, or passed to a helper like any other record, and Cmd.pipe joins commands into a pipeline that every one of those functions runs too.
Details
- No shell runs the command:
argsarrive as they are, with no globbing, variables, quoting, or|. Join commands with Cmd.pipe instead. - A
programwithout a path separator is looked up in the program's ownPATH, never in thePATHofenv. Os.which shows what that lookup finds. envis the child's whole environment. To add one variable, start from Os.environ.- A nonzero status is
Okfor Cmd.run, Cmd.capture, and Cmd.wait, andErrfor Cmd.read and Cmd.readBytes. Every function that runs a command isErrwhen the command cannot be started. When itsctxends first, the command is killed and the call isErrwith the context's reason; for Cmd.start, everyCmd.waitisErrinstead. - A command started with Cmd.start and still running when the script ends is left running. Stop it in a deferred block.
Basic examples
Cmd.new builds a command, and Cmd.read runs it and returns what it prints:
let greeting = try Cmd.read(Cmd.new("echo", ["hello"]))
println(greeting.toUpper())HELLOA Cmd is a record, and Cmd.new fills in the same defaults as a literal:
Cmd.new("git", ["status"]) // Cmd{ program: "git", args: ["status"], dir: null, env: null }
Cmd.new("ls") == Cmd{ program: "ls" } // trueCmd.run lets the command use the program's own streams and returns its status:
let status = try Cmd.run(Cmd.new("sh", ["-c", "echo working; exit 3"]))
println("status ${status}")working
status 3Scope
A Cmd changes like any record before it runs. Cmd.string writes it as a shell would need it quoted, for a log:
let verbose = true
let build = Cmd.new("go", ["build"])
if verbose {
build.args.push("-v")
}
build.args.push("./...")
println("running ${build.string()}")running go build -v ./...A Cmd.Pipeline runs wherever a Cmd runs:
let paths = Cmd.pipe([
Cmd.new("grep", ["^GET"]),
Cmd.new("cut", ["-d", " ", "-f", "2"]),
Cmd.new("sort", ["-u"]),
])
println(try paths.read(input: "GET /\nPOST /login\nGET /about\nGET /\n"))/
/aboutCmd.capture gives the status and both outputs, and a nonzero status is still Ok:
let out = try Cmd.new("sh", ["-c", "echo data; echo oops >&2; exit 2"]).capture()
println(out.status)
println(out.stdout.trim())
println(out.stderr.trim())2
data
oopsCmd.start runs a command in the background and returns a Cmd.Process. Cmd.wait gives its status, and Cmd.stop ends it. Cmd.stop gives 143, the status of a child that SIGTERM ended:
let quick = try Cmd.start(Cmd.new("echo", ["in the background"]))
println(try quick.wait())
let slow = try Cmd.start(Cmd.new("sleep", ["10"]))
println(try slow.stop())in the background
0
143Named arguments
dir runs the command in another directory:
println(try Cmd.new("ls", dir: "notes").read())todo.txtenv replaces the environment, so add a variable to a copy of Os.environ:
let env = Os.environ()
env["GREETING"] = "hi"
println(try Cmd.new("sh", ["-c", "echo $GREETING"], env: env).read())hiinput is what the command reads on standard input:
println(try Cmd.new("sort").read(input: "pear\napple\n"))apple
pearEvery function that runs a command takes a ctx. When it ends before the command exits, the command is killed and the call is Err with the context's reason:
let ctx = Context.new(timeout: 100ms)
println(Cmd.new("sleep", ["10"]).run(ctx: ctx))Err{ error: Error{ message: "timeout" } }Functions by job
Building
- Cmd.new: a command from a program, its arguments, a directory, and an environment
- Cmd.pipe: commands joined as a shell's
|joins them - Cmd.string: a command as a shell-quoted line for a log
Running to the end
- Cmd.run: run in the foreground with the program's streams, and return the status
- Cmd.read: the standard output as text,
Erron a nonzero status - Cmd.readBytes: the standard output as bytes, exactly as written
- Cmd.capture: the status and both outputs,
Okon a nonzero status - Cmd.captureBytes: the status and both outputs as bytes
Running in the background
- Cmd.start: start a command with the handles given, and return at once
- Cmd.wait: the status once the command has exited
- Cmd.kill: send a signal by name
- Cmd.stop: SIGTERM, then SIGKILL after a grace period
- Cmd.pid: the process id of the last stage
Types
- Cmd.Pipeline: commands run at once, each one's output the next one's input
- Cmd.Output: what
Cmd.capturecollects - Cmd.OutputBytes: what
Cmd.captureBytescollects - Cmd.Process: a command started by
Cmd.start
Applications
Read a value from a command, and fall back when the command fails:
func branch(dir: string): string {
let head = Cmd.new("git", ["rev-parse", "--abbrev-ref", "HEAD"], dir: dir).read()
head.unwrapOr("unknown")
}
println(branch("/"))unknownCheck that the tools a script needs are installed before it runs any of them:
let missing = ["sh", "no-such-tool-ant"].filter({ Os.which(x) == null })
if !missing.isEmpty() {
println("missing: ${missing | String.join(", ")}")
}missing: no-such-tool-antStart a helper in the background, stop it when the script ends, and read its output through a pipe:
let out = try Os.openPipe()
defer { out.read.close() }
let ticker = try Cmd.start(Cmd.new("sh", ["-c", "echo ready; sleep 10"]), stdout: out.write)
defer { ticker.stop() }
try out.write.close()
println(try out.read.readLine())readyRun steps in order, log each, and stop at the first that fails:
let steps = [Cmd.new("echo", ["compiling"]), Cmd.new("false"), Cmd.new("echo", ["deploying"])]
for step in steps {
println("+ ${step.string()}")
let status = try step.run()
if status != 0 {
eprintln("failed with status ${status}")
Os.exit(status)
}
}+ echo compiling
compiling
+ falseProperties and relations
Cmd.read is the standard output that Cmd.capture collects, without one final newline:
let c = Cmd.new("printf", ["one\ntwo\n"])
let out = try c.capture()
assert(try c.read() == out.stdout.trimSuffix("\n"))Cmd.string leaves out env and dir, so a secret in the environment stays out of the log:
let deploy = Cmd.new("deploy", ["--prod"], dir: "/srv", env: Map{ "TOKEN": "secret" })
assert(deploy.string() == Cmd.new("deploy", ["--prod"]).string())Possible issues
Cmd is a type. Build a command with Cmd.new or a literal:
let ls = Cmd("ls") // error: Cmd is a type, not a functionA whole command line in program names a program that does not exist. Split it into program and args:
println(Cmd.new("echo hello").run().isOk())
println(try Cmd.new("echo", ["hello"]).read())false
hellotry does not stop on a nonzero status from Cmd.run, since that is Ok. Cmd.read makes it an Err, with the program's standard error in the message:
println(Cmd.new("false").run())
println(Cmd.new("sh", ["-c", "echo bad >&2; exit 2"]).read())Ok{ value: 1 }
Err{ error: Error{ message: "sh: exit status 2: bad" } }Cmd.read removes one final newline and no other white space:
println(Cmd.new("printf", ["a\n\n"]).read())Ok{ value: "a\n" }See also
Cmd.new · Cmd.pipe · Cmd.run · Cmd.read · Cmd.capture · Cmd.start · Os · Os.which · Os.environ · Os.openPipe · Context
