Processes and the environment

std.process, running subprocesses with a builder API, plus argv and working-directory helpers.

vlatest

std.process runs subprocesses. It wraps the raw run_cmd / run_spawn builtins in a small builder and a Result type, which is the closest thing PickleScript has to error propagation.

The one-shot call

import { proc } from std.process

fn main() {
    let r = proc(["echo", "hello"])
    if (r.ok()) {
        println("stdout: {r.firstLine()}")
    } else {
        println("failed with {r.exitCode() ?? -1}")
    }
}

proc(argv) takes the program and its arguments as one list, the first element is the program, and there is no shell involved, so no quoting or escaping is needed.

Result

Member Signature Meaning
ok ok() -> bool The process exited with code 0
exitCode exitCode() -> int? The exit code, or none
stdout stdout() -> string Everything written to stdout
stderr stderr() -> string Everything written to stderr
timedOut timedOut() -> bool The timeout was hit
firstLine firstLine() -> string The first line of stdout
lines lines() -> List<string> stdout split into lines

timedOut matters: a process killed by its timeout has an exit code, so checking ok alone is not enough to distinguish "failed" from "ran too long".

import { proc } from std.process

fn main() {
    let r = proc(["git", "--version"])
    if (r.timedOut()) {
        println("git took too long")
        return
    }
    if (r.ok()) {
        println(r.firstLine())
    } else {
        println("git failed: {r.exitCode() ?? -1}")
        println(r.stderr())
    }
}

The Proc builder

For anything beyond a quick command, a working directory, environment variables, stdin, or a timeout, use Proc. Each configuration method returns the same object, so they chain.

import { Proc } from std.process

fn main() {
    let r = Proc(["git", "status", "--porcelain"])
        .setCwd(".")
        .withEnv("GIT_TERMINAL_PROMPT", "0")
        .withoutEnv("GIT_DIR")
        .withTimeout(5000)
        .run()

    if (r.ok()) {
        println("clean: {r.stdout() == ""}")
    } else {
        println("git said: {r.stderr()}")
    }
}
Method Signature Purpose
setCwd setCwd(dir: string) -> Proc Run in a different directory
withEnv withEnv(k: string, v: string) -> Proc Add or override a variable
withoutEnv withoutEnv(k: string) -> Proc Remove a variable
withStdin withStdin(b: List<byte>?) -> Proc Feed stdin, or close it
withTimeout withTimeout(ms: int) -> Proc Kill after a deadline
run run() -> Result Run to completion
runOk runOk() -> bool Run and return just success
output output() -> Result Alias of run

withStdin takes a List<byte>, so convert with bytes("text"):

import { Proc } from std.process

fn main() {
    let r = Proc(["cat"])
        .withStdin(bytes("piped input\n"))
        .run()
    println(r.stdout())
}

Pipelines

pipe connects several commands. Each entry in the outer list is one command's argv, and the output of each becomes the input of the next.

import { pipe } from std.process

fn main() {
    let r = pipe([
        ["git", "log", "--format=%s", "-20"],
        ["sort"],
    ])
    println(r.stdout())
}

The result is a single Result for the end of the pipeline. pipe stops at the first stage that does not exit cleanly and returns that stage's Result, so r.stderr() names the command that actually failed.

import { pipe } from std.process

fn main() {
    let r = pipe([
        ["git", "log", "--format=%s", "-20"],
        ["sort"],
    ])
    if (!r.ok()) {
        println("a stage failed: {r.stderr()}")
        return
    }
    println(r.stdout())
}

git

A convenience wrapper that runs git in a given root:

import { git } from std.process

fn main() {
    let r = git(".", ["rev-parse", "HEAD"])
    if (r.ok()) {
        println(r.firstLine())
    }
}
Function Signature
git git(root: string, args: List<string>) -> Result
proc proc(argv: List<string>) -> Result
pipe pipe(commands: List<List<string>>) -> Result
currentDir currentDir() -> string?
splitLines splitLines(s: string) -> List<string>
shSplit shSplit(line: string) -> List<string>

currentDir is a second spelling of the builtin of the same name, and also returns an optional. splitLines is the string-splitting function the standard library has, since there is no std.text.split.

shSplit splits a command line into argv the way a POSIX shell would. It is useful for reading a command out of configuration:

import { shSplit, proc } from std.process

fn main() {
    let argv = shSplit("git status --porcelain")
    let r = proc(argv)
    println(r.ok())
}

std.os

Two functions, both trivial:

import { argv, exitWith } from std.os

fn main() {
    println("argc {len(argv())}")
    exitWith(0)
}
Function Signature
argv argv() -> List<string>
exitWith exitWith(code: int)

argv() is the library spelling of the args() builtin. exitWith(code) is the library spelling of exit(code).

A program that wants to report a child's status through its own exit code should read the Result and then exit with the code to use:

import { proc } from std.process
import { exitWith } from std.os

fn main() {
    let r = proc(["git", "--version"])

    println("ok: {r.ok()}")
    println("first line: {r.firstLine()}")

    match (r.exitCode()) {
        case some(code) -> { exitWith(code) }
        case none -> { exitWith(1) }
    }
}

exitCode() is an int?, so match on it before interpolating, as above. ok, timedOut and firstLine are plain values and interpolate directly.

Next steps