gexe

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2021 License: MIT Imports: 6 Imported by: 19

README

Go Reference Go Report Card Build

Project gexe

Script-like OS interaction wrapped in the security and type safety of the Go programming language!

The goal of project gexe is to make it dead simple to write code that interacts with the OS (and/or other components) with the type safety of the Go programming language.

What can you do with gexe?

  • Prse and execute OS comands provided as plain and clear text as you would in a shell.
  • Support for variable exapansion in command string (i.e. gexe.Run("echo $HOME"))
  • Get process information (i.e. PID, status, exit code, etc)
  • Stream data from stdout while process is executing
  • Get program information (i.e. args, binary name, working dir, etc)
  • Easily read file content into different targets (string, bytes, io.Writer, etc)
  • Easily write file content from different sources (i.e. string, bytes, io.Reader, 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

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 = New()
)

Functions

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 Prog

func Prog() *prog.ProgInfo

Prog returns program information via *prog.ProgInfo

func Read

func Read(path string) fs.FileReader

Read creates an fs.FileReader that can be used to read content from files.

func Run

func Run(cmdStr string) string

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

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 Runout

func Runout(cmdStr string)

Runout executes command cmdStr and prints out the result

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 Val

func Val(name string) string

Val retrieves a session or environment variable

func Variables

func Variables() *vars.Variables

func Write

func Write(path string) fs.FileWriter

Write creates an fs.FileWriter that can be used to write content to files

Types

type Config

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

Config stores configuration

func (*Config) GetEscapeChar

func (c *Config) GetEscapeChar() rune

func (*Config) IsPanicOnErr

func (c *Config) IsPanicOnErr() bool

IsPanicOnErr returns panic-on-error flag

func (*Config) IsVerbose

func (c *Config) IsVerbose() bool

IsVerbose returns verbosity flag

func (*Config) SetEscapeChar

func (c *Config) SetEscapeChar(r rune) *Config

SetEscapeChar sets the escape char for command-line parsing

func (*Config) SetPanicOnErr

func (c *Config) SetPanicOnErr(val bool) *Config

SetPanicOnErr panics program on any error

func (*Config) SetVerbose

func (c *Config) SetVerbose(val bool) *Config

SetVerbose sets verbosity

type Echo

type Echo struct {
	Conf *Config // session config
	// contains filtered or unexported fields
}

Echo represents a new Echo session

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(val string) *Echo

Vars declares session-scope variables using a multi-line space-separated list:

Envs("foo=bar platform=amd64")

Session vars can be used in string values using Eval("My foo=$foo").

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

func (*Echo) Envs

func (e *Echo) 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 (*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) Prog

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

func (*Echo) Read

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

func (*Echo) Run

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

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

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) 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) StartProc

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

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

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

func (*Echo) Vars

func (e *Echo) Vars(val string) *Echo

Vars declares session-scope variables using a multi-line space-separated list:

Envs("foo=bar platform=amd64")

Session vars can be used in string values using Eval("My foo=$foo").

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

func (*Echo) Write

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

Directories

Path Synopsis
examples
build command
filesys command
git command
helloecho command
ping command

Jump to

Keyboard shortcuts

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