exec

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 23, 2023 License: MIT Imports: 15 Imported by: 0

README

Exec

GitHub Releases Build Status codecov Go Report Card GoDevDoc Donate

Package exec runs external commands.

Prerequisites

  • Go >= 1.19

Install

go get go.nhat.io/exec

Usage

Run a command:

package example_test

import (
	"bytes"
	"fmt"

	"go.nhat.io/exec"
)

func ExampleRun() {
	outBuf := new(bytes.Buffer)
	errBuf := new(bytes.Buffer)

	_, err := exec.Run("echo", exec.WithArgs("hello world"),
		exec.WithStdout(outBuf),
		exec.WithStderr(errBuf),
	)

	if err != nil {
		panic(err)
	}

	fmt.Println(outBuf.String())
	fmt.Println(errBuf.String())

	// Output:
	// hello world
	//
}

Run a command with pipes:

package example_test

import (
    "bytes"
    "fmt"

    "go.nhat.io/exec"
)

func ExampleRun_pipe() {
	outBuf := new(bytes.Buffer)
	errBuf := new(bytes.Buffer)

	_, err := exec.Run("echo", exec.WithArgs("hello world"),
		exec.WithStdout(outBuf),
		exec.WithStderr(errBuf),
		exec.Pipe("grep", "-o", "hello"),
		exec.Pipe("tr", "[:lower:]", "[:upper:]"),
	)

	if err != nil {
		panic(err)
	}

	fmt.Println(outBuf.String())
	fmt.Println(errBuf.String())

	// Output:
	// HELLO
	//
}

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

paypal

       or scan this

Documentation

Overview

Package exec is a wrapper around os/exec that provides a few extra features.

Package exec is a wrapper around os/exec that provides a few extra features.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNotFound = exec.ErrNotFound

ErrNotFound is the error resulting if a path search failed to find an executable file.

Functions

func LookPath

func LookPath(file string) (string, error)

LookPath searches for an executable named file in the directories named by the PATH environment variable. If file contains a slash, it is tried directly and the PATH is not consulted. Otherwise, on success, the result is an absolute path.

Types

type Cmd

type Cmd struct {
	*exec.Cmd
	Next *Cmd
	// contains filtered or unexported fields
}

Cmd is a wrapper around exec.Cmd.

func Command

func Command(name string, opts ...Option) *Cmd

Command returns the Cmd struct to execute the named program with the given arguments.

See os/exec.Command for more information.

func CommandContext

func CommandContext(ctx context.Context, name string, opts ...Option) *Cmd

CommandContext is like Command but includes a context.

See os/exec.CommandContext for more information.

func Run

func Run(name string, opts ...Option) (*Cmd, error)

Run runs the command.

See os/exec.Command.Run for more information.

Example
package main

import (
	"bytes"
	"fmt"

	"go.nhat.io/exec"
)

func main() {
	stdout := new(bytes.Buffer)
	stderr := new(bytes.Buffer)

	_, err := exec.Run("echo", exec.WithArgs("hello world"),
		exec.WithStdout(stdout),
		exec.WithStderr(stderr),
	)
	if err != nil {
		panic(err)
	}

	fmt.Println(stdout.String())
	fmt.Println(stderr.String())

}
Output:

hello world
Example (Pipe)
package main

import (
	"bytes"
	"fmt"

	"go.nhat.io/exec"
)

func main() {
	stdout := new(bytes.Buffer)
	stderr := new(bytes.Buffer)

	_, err := exec.Run("echo", exec.WithArgs("hello world"),
		exec.WithStdout(stdout),
		exec.WithStderr(stderr),
		exec.Pipe("grep", "-o", "hello"),
		exec.Pipe("tr", "[:lower:]", "[:upper:]"),
	)
	if err != nil {
		panic(err)
	}

	fmt.Println(stdout.String())
	fmt.Println(stderr.String())

}
Output:

HELLO
Example (Stdin)
package main

import (
	"bytes"
	"fmt"
	"strings"

	"go.nhat.io/exec"
)

func main() {
	stdin := strings.NewReader("hello world")
	stdout := new(bytes.Buffer)
	stderr := new(bytes.Buffer)

	_, err := exec.Run("cat",
		exec.WithStdin(stdin),
		exec.WithStdout(stdout),
		exec.WithStderr(stderr),
	)
	if err != nil {
		panic(err)
	}

	fmt.Println(stdout.String())
	fmt.Println(stderr.String())

}
Output:

hello world

func RunWithContext

func RunWithContext(ctx context.Context, name string, opts ...Option) (_ *Cmd, err error)

RunWithContext runs the command with the given context.

See os/exec.Command.Run for more information.

func (*Cmd) Run

func (c *Cmd) Run() error

Run starts the specified command and waits for it to complete.

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

If the command starts but does not complete successfully, the error is of type *ExitError. Other error types may be returned for other situations.

If the calling goroutine has locked the operating system thread with runtime.LockOSThread and modified any inheritable OS-level thread state (for example, Linux or Plan 9 name spaces), the new process will inherit the caller's thread state.

func (*Cmd) Start

func (c *Cmd) Start() error

Start starts the specified command but does not wait for it to complete.

If Start returns successfully, the c.Process field will be set.

After a successful call to Start the Wait method must be called in order to release associated system resources.

func (*Cmd) String

func (c *Cmd) String() string

String returns a human-readable description of c. It is intended only for debugging. In particular, it is not suitable for use as input to a shell.

The output of String may vary across Go releases.

func (*Cmd) Wait

func (c *Cmd) Wait() (err error)

Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

The command must have been started by Start.

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

If the command fails to run or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for I/O problems.

If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits for the respective I/O loop copying to or from the process to complete.

Wait releases any resources associated with the Cmd.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is an option to configure the Cmd.

func AppendArgs added in v0.3.0

func AppendArgs(args ...string) Option

AppendArgs appends the arguments to the existing ones.

func Pipe

func Pipe(name string, args ...string) Option

Pipe pipes the output to the next command.

func RedactArgs added in v0.5.0

func RedactArgs(args ...string) Option

RedactArgs redacts the given arguments in traces and logs.

func WithArgs

func WithArgs(args ...string) Option

WithArgs sets the arguments.

func WithArgsRedactor added in v0.6.0

func WithArgsRedactor(r redact.Redactor) Option

WithArgsRedactor sets the redactor to redact the arguments.

func WithEnv

func WithEnv(key, value string) Option

WithEnv sets the environment variable.

func WithEnvs

func WithEnvs(envs map[string]string) Option

WithEnvs sets the environment variables.

func WithLogger

func WithLogger(logger ctxd.Logger) Option

WithLogger sets the logger.

func WithStderr

func WithStderr(err io.Writer) Option

WithStderr sets the standard error.

func WithStdin

func WithStdin(in io.Reader) Option

WithStdin sets the standard input.

func WithStdout

func WithStdout(out io.Writer) Option

WithStdout sets the standard output.

func WithTracer

func WithTracer(tracer trace.Tracer) Option

WithTracer sets the tracer.

Directories

Path Synopsis
Package test provides helpers to test the exec package.
Package test provides helpers to test the exec package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL