Documentation ¶
Overview ¶
Package streamexec provides integrations with os/exec to stream command output.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Start ¶ added in v0.9.0
func Start(cmd *exec.Cmd, modes ...StreamMode) (*streamline.Stream, error)
Start attaches a streamline.Stream to the command and starts it. It returns an error if the command fails to start. If the command successfully starts, it also starts a goroutine that waits for command completion and stops the pipe appropriately.
If no modes are provided, the default stream mode is Combined. If multiple modes are provided, they are all included.
Instead of using cmd.Wait() for command completion, callers should read the returned Stream until completion to indicate if the command has exited.
Before consuming the Stream, the caller can configure the Stream as a normal stream using e.g. WithPipeline.
Output piping is handled by buffers created by streamline/pipe.NewStream(...).
Example ¶
package main import ( "fmt" "os/exec" "go.bobheadxi.dev/streamline/streamexec" ) func main() { cmd := exec.Command("echo", "hello world\nthis is a line\nand another line!") stream, err := streamexec.Start(cmd, streamexec.Combined) if err != nil { fmt.Println("failed to start:", err.Error()) } err = stream.Stream(func(line string) { fmt.Println("received output:", line) }) if err != nil { fmt.Println("command exited with error status:", err.Error()) } }
Output: received output: hello world received output: this is a line received output: and another line!
Example (ErrWithStderr) ¶
package main import ( "fmt" "os/exec" "go.bobheadxi.dev/streamline/streamexec" ) func main() { cmd := exec.Command("bash", "-o", "pipefail", "-o", "errexit", "-c", `echo "my stdout output" ; sleep 0.001 ; >&2 echo "my stderr output" ; exit 1`) stream, err := streamexec.Start(cmd, streamexec.Stdout|streamexec.ErrWithStderr) if err != nil { fmt.Println("failed to start: ", err.Error()) } out, err := stream.String() fmt.Println("got error:", err.Error()) // error includes stderr fmt.Println("got output:", out) }
Output: got error: exit status 1: my stderr output got output: my stdout output
Types ¶
type StreamMode ¶
type StreamMode int
StreamMode indicates what output(s) to attach.
const ( // Combined streams both Stdout and Stderr. It is the default stream mode. Combined StreamMode = Stdout | Stderr // Stdout only streams cmd.Stdout. Stdout StreamMode = 1 << iota // Stderr only streams cmd.Stderr. Stderr // ErrWithStderr collects Stderr output and includes it in the returned error from // Cmd.Start(). Best used with the Stdout StreamMode to avoid duplicating stderr // output in the stream and in the returned error. ErrWithStderr )