The standard library
Slide 59 of 85
59execThe standard library

Running other programs

Three calls run another program, and none of them goes through a shell: the arguments are a vector rather than a line of text, so nothing in one can be read as a command. Each takes the command, its arguments, and the folder to run it in — "" for the current one.

  • exec(command, arguments, directory) waits for it and answers with everything it wrote, standard output and standard error together, as written and untrimmed. A status other than zero is a Result.Error.
  • execWith(command, arguments, directory, environment) is exec with a hive.map.Map<Str, Str> of variables set on top of this program's own environment — an overlay, never a replacement, so PATH and HOME are still there, and an empty map is exactly exec.
  • attach(command, arguments, directory) hands the command this program's own terminal and answers with its exit status, capturing nothing: the command talks to whoever started this one. A command that could not start answers -1.

A failure is a hive.term.ExecError, carrying the command, the code it exited with — -1 when it could not start at all, as for a folder that does not exist — the output it wrote before failing, and a message.

Running another program
proc main(): void {
	result := hive.term.exec("hostname", [], "")
	if result is Result.Ok(output) {
		echo "this machine is called: {output}"
	} else if result is Result.Error(why) {
		echo "could not run hostname: {why.message}"
	}
}
Running one with an environment
proc main(): void {
	mut hive.map.Map<Str, Str> asked = hive.map.new()
	hive.map.set(asked, "GOOS", "linux")
	hive.map.set(asked, "GOARCH", "arm64")

	// An overlay, not a replacement: these two on top of everything this
	// program was started with, so `go` is still found on the PATH.
	result := hive.term.execWith("go", ["env", "GOOS", "GOARCH"], "", asked)
	if result is Result.Ok(output) {
		echo output
	} else if result is Result.Error(why) {
		echo "no Go on this machine: {why.message}"
	}
}