gexe

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2024 License: MIT Imports: 12 Imported by: 18

README

Go Reference Go Report Card Build

Project gexe

Package with script-like API for system operation and automation!

The goal of project gexe is to make it simple to write code for system operation and task automation using a script-like API that offers the security and the type safety of the Go programming language (see /examples).

NOTE: this project got renamed from Echo to Gexe (see Project Name Change)

What can you do with gexe?

  • Parse and execute OS plain text commands, as you would in a shell.
  • Support for variable expansion in command string (i.e. gexe.Run("echo $HOME"))
  • Ability to pipe processes: gexe.Pipe("cat /etc/hosts", "wc -l")
  • Run processes concurrently: gexe.RunConcur('wget https://example.com/files'; "date")
  • Get process information (i.e. PID, status, exit code, etc)
  • Get program information (i.e. args, binary name, working dir, etc)
  • Easily read and write file content using different sources (string, bytes, io.Writer, etc)
  • Integrate with your shell script using go run

Using gexe

Get the package
go get github.com/vladimirvivien/gexe
Run a process

The following executes command echo "Hello World!" and prints the result:

fmt.Println(gexe.Run(`echo "Hello World!"`))

Alternatively, you can create your own gexe session for more control and error hanlding:

g := gexe.New()
proc := g.RunProc(`echo "Hello World"`)
if proc.Err() != nil {
    fmt.Println(proc.Err())
    os.Exit(proc.ExitCode())    
}
fmt.Println(proc.Result())

Examples

Find more examples here!

Building project $gexe with gexe

This example shows how gexe can be used to build Go project binaries for multiple platforms and OSes. Note the followings:

  • The command string is naturally expressed as you would in a shell.
  • The use of variable expansion in the commands.
func main() {
	for _, arch := range []string{"amd64"} {
		for _, opsys := range []string{"darwin", "linux"} {
			gexe.SetVar("arch", arch).SetVar("os", opsys)
			gexe.SetVar("binpath", fmt.Sprintf("build/%s/%s/mybinary", arch, opsys))
			result := gexe.Envs("CGO_ENABLED=0 GOOS=$os GOARCH=$arch").Run("go build -o $binpath .")
			if result != "" {
				fmt.Printf("Build for %s/%s failed: %s\n", arch, opsys, result)
				os.Exit(1)
			}
			fmt.Printf("Build %s/%s: %s OK\n", arch, opsys, echo.Eval("$binpath"))
		}
	}
}

See ./examples/build/main.go

Long-running process

This example shows how gexe can be used to launch a long-running process and stream its output. The code invokes the ping command, streams its output, displays the result, and then kills the process after 5 seconds.

func main() {
	execTime := time.Second * 5
	fmt.Println("ping golang.org...")

	p := gexe.StartProc("ping golang.org")

	if p.Err() != nil {
		fmt.Println("ping failed:", p.Err())
		os.Exit(1)
	}

	go func() {
		if _, err := io.Copy(os.Stdout, p.StdOut()); err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}()

	<-time.After(execTime)
	p.Kill()
	fmt.Printf("Pinged golang.org for %s\n", execTime)
}
Using a shell

This example uses the git command to print logs and commit info by using /bin/sh to start a shell for command piping:

func main() {
	cmd := `/bin/sh -c "git log --reverse --abbrev-commit --pretty=oneline | cut -d ' ' -f1"`
	for _, p := range strings.Split(gexe.Run(cmd), "\n") {
		gexe.SetVar("patch", p)
		cmd := `/bin/sh -c "git show --abbrev-commit -s --pretty=format:'%h %s (%an) %n' ${patch}"`
		fmt.Println(gexe.Run(cmd))
	}
}

Project Name Change

Originally this project was named echo. However, another Go project by that name has gotten really popular. So this project was renamed gexe (pronounced Jesse).

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultEcho surfaces an Echo session used for all package functions
	DefaultEcho = New()
)

Functions

func AddExecPath added in v0.3.0

func AddExecPath(execPath string)

AddExecPath adds an executable path to PATH

func Commands added in v0.2.0

func Commands(cmdStrs ...string) *exec.CommandBuilder

Commands returns a *exe.CommandBuilder to build a multi-command execution flow.

func Eval

func Eval(str string) string

Eval returns the string str with its content expanded with variable values i.e. Eval("I am $HOME") returns "I am </user/home/path>"

func FileRead added in v0.3.0

func FileRead(path string) *fs.FileReader

FileRead provides methods to read file content from path

func FileReadWithContext added in v0.4.1

func FileReadWithContext(ctx context.Context, path string) *fs.FileReader

FileRead uses context ctx to read file content from path

func FileWrite added in v0.3.0

func FileWrite(path string) *fs.FileWriter

FileWrite provides methods to write file content to path

func FileWriteWithContext added in v0.4.1

func FileWriteWithContext(ctx context.Context, path string) *fs.FileWriter

FileWriteWithContext uses context ctx to write file content to path

func Get added in v0.4.0

func Get(url string, paths ...string) *http.Response

Get is a convenient alias for HttpGet that retrieves specified resource at given URL/path

func HttpGet added in v0.4.0

func HttpGet(url string, paths ...string) *http.ResourceReader

HttpGet starts an HTTP GET operation to retrieve resource at URL/path

func HttpGetWithContext added in v0.4.1

func HttpGetWithContext(ctx context.Context, url string, paths ...string) *http.ResourceReader

HttpGetWithContext uses context ctx to start an HTTP GET operation to retrieve resource at URL/path

func HttpPost added in v0.4.0

func HttpPost(url string, paths ...string) *http.ResourceWriter

HttpPost starts an HTTP POST operation to post resource to URL/path

func HttpPostWithContext added in v0.4.1

func HttpPostWithContext(ctx context.Context, url string, paths ...string) *http.ResourceWriter

HttpPostWithContext uses context ctx to start an HTTP POST operation to post resource to URL/path

func MkDir added in v0.3.0

func MkDir(path string) *fs.FSInfo

MkDir creates a directory with default mode 0744

func MkDirs added in v0.3.0

func MkDirs(path string, mode os.FileMode) *fs.FSInfo

MkDirs creates one or more directories along the specified path

func NewProc added in v0.2.0

func NewProc(cmdStr string) *exec.Proc

NewProc setups a new process with specified command cmdStr and returns immediately without starting. Information about the running process is stored in *exec.Proc.

func NewProcWithContext added in v0.4.1

func NewProcWithContext(ctx context.Context, cmdStr string) *exec.Proc

NewProcWithContext setups a new process with specified context and command cmdStr and returns immediately without starting. Information about the running process is stored in *exec.Proc.

func PathExists added in v0.3.0

func PathExists(path string) bool

PathExists returns true if specified path exists. Any error will cause it to return false.

func PathInfo added in v0.3.0

func PathInfo(path string) *fs.FSInfo

PathInfo returns information for specified path (i.e. size, etc)

func Pipe added in v0.2.0

func Pipe(cmdStrs ...string) *exec.PipedCommandResult

Pipe executes each command, in cmdStrs, by piping the result of the previous command as input to the next command until done.

func Post added in v0.4.0

func Post(data []byte, url string) *http.Response

Post is a convenient alias for HttpPost to post data at specified URL

func Prog

func Prog() *prog.Info

Prog returns program information via *prog.Info

func ProgAvail added in v0.3.0

func ProgAvail(program string) string

ProgAvail returns the full path of the program if available.

func RmPath added in v0.3.0

func RmPath(path string) *fs.FSInfo

RmPath removes files or directories along specified path

func Run

func Run(cmdStr string) string

Run executes cmdStr, waits, and returns the result as a string.

func RunAll added in v0.2.0

func RunAll(cmdStrs ...string) *exec.CommandResult

RunAll executes each command, in cmdStrs, successively and wait for their completion.

func RunConcur added in v0.2.0

func RunConcur(cmdStrs ...string) *exec.CommandResult

RunConcur executes each command, in cmdStrs, concurrently and waits their completion.

func RunProc

func RunProc(cmdStr string) *exec.Proc

RunProc executes command in cmdStr and waits for the result. It returns a *Proc with information about the executed process.

func RunProcWithContext added in v0.4.1

func RunProcWithContext(ctx context.Context, cmdStr string) *exec.Proc

RunProcWithContext executes command in cmdStr, with specified ctx, and waits for the result. It returns a *Proc with information about the executed process.

func RunWithContext added in v0.4.1

func RunWithContext(ctx context.Context, cmdStr string) string

RunWithContext executes cmdStr, with specified context, and waits for completion. It returns the result as a string.

func Runout

func Runout(cmdStr string)

Runout executes command cmdStr and prints out the result

func StartAll added in v0.2.0

func StartAll(cmdStrs ...string) *exec.CommandResult

StartAll starts the exection of each command sequentially and does not wait for their completion.

func StartConcur added in v0.2.0

func StartConcur(cmdStrs ...string) *exec.CommandResult

StartConcur starts the exection of each command concurrently and does not wait for their completion.

func StartProc

func StartProc(cmdStr string) *exec.Proc

StartProc executes the command in cmdStr and returns immediately without waiting. Information about the running process is stored in *exec.Proc.

func StartProcWithContext added in v0.4.1

func StartProcWithContext(ctx context.Context, cmdStr string) *exec.Proc

StartProcWith executes the command in cmdStr with the specified contex and returns immediately without waiting. Information about the running process is stored in *exec.Proc.

func String added in v0.3.0

func String(s string) *str.Str

func Val

func Val(name string) string

Val retrieves a session or environment variable

func Variables

func Variables() *vars.Variables

Variables returns variable map for DefaultEcho session

func Workdir added in v0.3.0

func Workdir() string

Workdir returns the current program's working directory

Types

type Echo

type Echo struct {
	// contains filtered or unexported fields
}

Echo represents a new Echo session used for accessing Gexe types and methods.

func Envs

func Envs(val ...string) *Echo

Envs declares environment variables using a multi-line space-separated list:

Envs("GOOS=linux GOARCH=amd64")

Environment vars can be used in string values using Eval("building for os=$GOOS")

func New

func New() *Echo

New creates a new Echo session

func SetEnv

func SetEnv(name, value string) *Echo

SetEnv sets a process environment variable.

func SetVar

func SetVar(name, value string) *Echo

SetVar declares a session variable.

func Vars

func Vars(variables ...string) *Echo

Vars declares multiple session-scope variables using string literals:

Envs("foo=bar", "platform=amd64", `"data="info ${platform}"`)

Note that session vars are only available for the running process.

func (*Echo) AddExecPath added in v0.3.0

func (e *Echo) AddExecPath(execPath string)

AddExecPath adds an executable path to PATH

func (*Echo) AddressUsable added in v0.3.0

func (e *Echo) AddressUsable(addr string) error

func (*Echo) Commands added in v0.2.0

func (e *Echo) Commands(cmdStrs ...string) *exec.CommandBuilder

Commands returns a *exe.CommandBuilder to build a multi-command execution flow.

func (*Echo) CommandsWithContext added in v0.4.1

func (e *Echo) CommandsWithContext(ctx context.Context, cmdStrs ...string) *exec.CommandBuilder

Commands creates a *exe.CommandBuilder, with the specified context, to build a multi-command execution flow.

func (*Echo) Envs

func (e *Echo) Envs(variables ...string) *Echo

Envs declares environment variables using a multi-line space-separated list:

Envs("GOOS=linux" "GOARCH=amd64", `platform="$GOOS:$GOARCH"`)

Environment vars can be used in string values using Eval("building for os=$GOOS")

func (*Echo) Eval

func (e *Echo) Eval(str string) string

Eval returns the string str with its content expanded with variable values i.e. Eval("I am $HOME") returns "I am </user/home/path>"

func (*Echo) FileAppend added in v0.3.0

func (e *Echo) FileAppend(path string) *fs.FileWriter

FileAppend creates a new fs.FileWriter to append content to provided path

func (*Echo) FileAppendWithContext added in v0.4.1

func (e *Echo) FileAppendWithContext(ctx context.Context, path string) *fs.FileWriter

FileAppend creates a new fs.FileWriter to append content to provided path

func (*Echo) FileRead added in v0.3.0

func (e *Echo) FileRead(path string) *fs.FileReader

FileRead provides methods to read file content

func (*Echo) FileReadWithContext added in v0.4.1

func (e *Echo) FileReadWithContext(ctx context.Context, path string) *fs.FileReader

FileReadWithContext uses specified context to provide methods to read file content at path.

func (*Echo) FileWrite added in v0.3.0

func (e *Echo) FileWrite(path string) *fs.FileWriter

FileWrite creates a fs.FileWriter to write content to provided path

func (*Echo) FileWriteWithContext added in v0.4.1

func (e *Echo) FileWriteWithContext(ctx context.Context, path string) *fs.FileWriter

FileWriteWithContext uses context ctx to create a fs.FileWriter to write content to provided path

func (*Echo) Get added in v0.2.0

func (e *Echo) Get(url string, paths ...string) *http.Response

Get is convenient alias for HttpGet to retrieve a resource at given URL/path

func (*Echo) HttpGet added in v0.4.0

func (e *Echo) HttpGet(url string, paths ...string) *http.ResourceReader

HttpGetWithContext starts an HTTP GET operation to retrieve server resource from given URL/paths.

func (*Echo) HttpGetWithContext added in v0.4.1

func (e *Echo) HttpGetWithContext(ctx context.Context, url string, paths ...string) *http.ResourceReader

HttpGetWithContext uses context ctx to start an HTTP GET operation to retrieve server resource from given URL/paths.

func (*Echo) HttpPost added in v0.4.0

func (e *Echo) HttpPost(url string, paths ...string) *http.ResourceWriter

HttpPost starts an HTTP POST operation to post resource to a server at given URL/path.

func (*Echo) HttpPostWithContext added in v0.4.1

func (e *Echo) HttpPostWithContext(ctx context.Context, url string, paths ...string) *http.ResourceWriter

HttpPostWithContext uses context ctx to start an HTTP POST operation to post resource to a server at given URL/path.

func (*Echo) MkDir added in v0.3.0

func (e *Echo) MkDir(path string, mode os.FileMode) *fs.FSInfo

MkDir creates a directory at specified path with mode value. FSInfo contains information about the path or error if occured

func (*Echo) NewProc added in v0.2.0

func (e *Echo) NewProc(cmdStr string) *exec.Proc

NewProc a convenient function that calls NewProcWithContext with a default contet.

func (*Echo) NewProcWithContext added in v0.4.1

func (e *Echo) NewProcWithContext(ctx context.Context, cmdStr string) *exec.Proc

NewProc setups a new process with specified command cmdStr and returns immediately without starting. Use Proc.Wait to wait for exection and then retrieve process result. Information about the running process is stored in *exec.Proc.

func (*Echo) ParseCommand added in v0.3.0

func (e *Echo) ParseCommand(cmdStr string) (cmdName string, args []string)

ParseCommand parses the string into individual command tokens

func (*Echo) PathExists added in v0.3.0

func (e *Echo) PathExists(path string) bool

PathExists returns true if path exists. All errors causes to return false.

func (*Echo) PathInfo added in v0.3.0

func (e *Echo) PathInfo(path string) *fs.FSInfo

PathInfo

func (*Echo) Pipe added in v0.2.0

func (e *Echo) Pipe(cmdStrs ...string) *exec.PipedCommandResult

Pipe executes each command, in cmdStrs, by piping the result of the previous command as input to the next command until done.

func (*Echo) PipeWithContext added in v0.4.1

func (e *Echo) PipeWithContext(ctx context.Context, cmdStrs ...string) *exec.PipedCommandResult

Pipe uses specified context to execute each command, in cmdStrs, by piping the result of the previous command as input to the next command until done.

func (*Echo) Post added in v0.2.0

func (e *Echo) Post(data []byte, url string, paths ...string) *http.Response

Post is a convenient alias for HttpPost to post the specified data to given URL/path

func (*Echo) Prog

func (e *Echo) Prog() *prog.Info

Prog makes info available about currently executing program

func (*Echo) ProgAvail added in v0.3.0

func (e *Echo) ProgAvail(progName string) string

ProgAvail returns the full path of the program if found on exec PATH

func (*Echo) RmPath added in v0.3.0

func (e *Echo) RmPath(path string) *fs.FSInfo

RmPath removes specified path (dir or file). Error is returned FSInfo.Err()

func (*Echo) Run

func (e *Echo) Run(cmdStr string) string

Run executes cmdStr, waits, and returns the result as a string.

func (*Echo) RunAll added in v0.2.0

func (e *Echo) RunAll(cmdStrs ...string) *exec.CommandResult

RunAll executes each command sequentially, in cmdStrs, and wait for their completion.

func (*Echo) RunAllWithContext added in v0.4.1

func (e *Echo) RunAllWithContext(ctx context.Context, cmdStrs ...string) *exec.CommandResult

RunAllWithContext executes each command sequentially, in cmdStrs, and wait for their completion.

func (*Echo) RunConcur added in v0.2.0

func (e *Echo) RunConcur(cmdStrs ...string) *exec.CommandResult

RunConcur executes each command concurrently, in cmdStrs, and waits their completion.

func (*Echo) RunConcurWithContext added in v0.4.1

func (e *Echo) RunConcurWithContext(ctx context.Context, cmdStrs ...string) *exec.CommandResult

RunConcurWithContext uses context to execute each command concurrently, in cmdStrs, and waits their completion.

func (*Echo) RunProc

func (e *Echo) RunProc(cmdStr string) *exec.Proc

RunProc executes command in cmdStr and waits for the result. It returns a *Proc with information about the executed process.

func (*Echo) RunProcWithContext added in v0.4.1

func (e *Echo) RunProcWithContext(ctx context.Context, cmdStr string) *exec.Proc

RunProcWithContext executes command in cmdStr, with given context, and waits for the result. It returns a *Proc with information about the executed process.

func (*Echo) RunWithContext added in v0.4.1

func (e *Echo) RunWithContext(ctx context.Context, cmdStr string) string

Run executes cmdStr, with given context, and returns the result as a string.

func (*Echo) Runout

func (e *Echo) Runout(cmdStr string)

Runout executes command cmdStr and prints out the result

func (*Echo) SetEnv

func (e *Echo) SetEnv(name, value string) *Echo

SetEnv sets a global process environment variable.

func (*Echo) SetVar

func (e *Echo) SetVar(name, value string) *Echo

SetVar declares a session variable.

func (*Echo) StartAll added in v0.2.0

func (e *Echo) StartAll(cmdStrs ...string) *exec.CommandResult

StartAll starts the sequential execution of each command, in cmdStrs, and does not wait for their completion.

func (*Echo) StartAllWithContext added in v0.4.1

func (e *Echo) StartAllWithContext(ctx context.Context, cmdStrs ...string) *exec.CommandResult

StartAllWithContext uses the specified ctx to start sequential execution of each command, in cmdStrs, and does not wait for their completion.

func (*Echo) StartConcur added in v0.2.0

func (e *Echo) StartConcur(cmdStrs ...string) *exec.CommandResult

StartConcur starts the concurrent execution of each command, in cmdStrs, and does not wait for their completion.

func (*Echo) StartConcurWithContext added in v0.4.1

func (e *Echo) StartConcurWithContext(ctx context.Context, cmdStrs ...string) *exec.CommandResult

StartConcurWithContext uses specified context to start the concurrent execution of each command, in cmdStrs, and does not wait for their completion.

func (*Echo) StartProc

func (e *Echo) StartProc(cmdStr string) *exec.Proc

StartProc executes the command in cmdStr and returns immediately without waiting. Use Proc.Wait to wait for exection and then retrieve process result. Information about the running process is stored in *Proc.

func (*Echo) StartProcWithContext added in v0.4.1

func (e *Echo) StartProcWithContext(ctx context.Context, cmdStr string) *exec.Proc

StartProc executes the command in cmdStr, with the specified context, and returns immediately without waiting. Use Proc.Wait to wait for exection and then retrieve process result. Information about the running process is stored in *Proc.

func (*Echo) String added in v0.3.0

func (e *Echo) String(s string) *str.Str

String creates a new str.Str value with string manipulation methods

func (*Echo) UnsetVar added in v0.3.0

func (e *Echo) UnsetVar(name string) *Echo

UnsetVar removes a session variable.

func (*Echo) Val

func (e *Echo) Val(name string) string

Val retrieves a session or environment variable

func (*Echo) Variables

func (e *Echo) Variables() *vars.Variables

Variables returns the variable mapping for echo session e

func (*Echo) Vars

func (e *Echo) Vars(variables ...string) *Echo

Vars declares multiple session-scope variables using string literal format:

Envs("foo=bar", "platform=amd64", `"data="info ${platform}"`)

Note that session vars are only available for the running process.

func (*Echo) Workdir added in v0.3.0

func (e *Echo) Workdir() string

Workdir returns the current program's working directory

Directories

Path Synopsis
examples
git

Jump to

Keyboard shortcuts

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