Help us shape the future of Go! Take the 2026 Go Developer Survey

echo

package module
v0.0.1-alpha.6 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2020 License: MIT Imports: 11 Imported by: 0

README

echo

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

The goal of echo is to make it easy to write code that interacts with the OS (or other infrastructure components) using the security and type safety of the Go programming language.

What echo is

  • Not a tool for shell-scripting Go code
  • Designed to be used as idiomatic Go
  • Rich types for easy interactions with OS and IO
  • Support for different programming styles
  • Programs can be used as pre-compiled binaries or with go run

Using echo

Create a session:

e := echo.New()

Then, optionally configure your session:

e.Conf.SetPanicOnError(true)
Building Go with echo

This example shows how echo can be used to build Go project binaries for multiple platforms and OSes.

func main() {
	e := echo.New()
	for _, arch := range []string{"amd64"} {
		for _, opsys := range []string{"darwin", "linux"} {
			e.SetVar("arch", arch).SetVar("os", opsys)
			e.SetVar("binpath", fmt.Sprintf("build/%s/%s/mybinary", arch, opsys))
			result := e.Env("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, e.Eval("$binpath"))
		}
	}
}

See ./examples/build/main.go

Example of a long running process

The following shows how echo can be used to launch a long running process and stream its output. The code invokese 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...")

	e := echo.New()
	p := e.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("Pingged golang.org for %s\n", execTime)
}
Example using shell

This example uses git to print logs and commit info. The code invokes git as a sub-command of /bin/sh to start a shell for more complex functionalities (such as piping).

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

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

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
	Procs []Proc  // executed processes
	Prog  *prog   // progam info
	// contains filtered or unexported fields
}

Echo represents a new Echo session

func New

func New() *Echo

New creates a new Echo session

func (*Echo) Abs

func (e *Echo) Abs(path string) string

Abs returns the absolute representation for path. Returns empty string if it fails for any reason.

func (*Echo) AreSame

func (e *Echo) AreSame(path0, path1 string) bool

AreSame tests files at path0 and path to check if they are the same

func (*Echo) Base

func (e *Echo) Base(path string) string

Base returns the last portion (or name) of a path.

func (*Echo) Dir

func (e *Echo) Dir(path string) string

Dir returns parent path portion of a path (without the Base).

func (*Echo) Empty

func (e *Echo) Empty(val string) bool

Empty returns true if len(val) == 0

func (*Echo) Env

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

Env declares process environment variables using a multi-line space-separated list of KEY=VAL format: i.e. GOOS=linux GOARCH=amd64

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

func (e *Echo) Ext(path string) string

Ext returns extension part of path

func (*Echo) Glob

func (e *Echo) Glob(pathPattern string) []string

Glob uses shell file path pattern (i.e. /usr/*/*a) to return a []string of file names

func (*Echo) IsAbs

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

IsAbs returns true if path is an absolute path

func (*Echo) IsDir

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

IsDir returns true if path is a directory. All other cases (errors) will return false.

func (*Echo) IsExist

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

IsExist returns true if file is 1) accessible 2) exists. All other conditions returns false.

func (*Echo) IsReg

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

IsReg returns true if path is a regular file. All other cases (errors) will return false.

func (*Echo) Lower

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

Lower returns val as lower case

func (*Echo) Mkdirs

func (e *Echo) Mkdirs(paths string, modes ...uint32)

Mkdirs creates one or more space-separated directories using the optional filemods. If no mode is provided, it defaults to 0777. When mode is provided only modes[0] is applied.

func (*Echo) OpenFile

func (e *Echo) OpenFile(filename string) *File

OpenFile saves the filename for IO operation

func (*Echo) PathJoin

func (e *Echo) PathJoin(paths ...string) string

PathJoin collate individual paths together for a longer path

func (*Echo) PathMatched

func (e *Echo) PathMatched(pattern, path string) bool

PathMatched returns true if path matches shell file pattern

func (*Echo) PathSplit

func (e *Echo) PathSplit(path string) []string

PathSplit splits an OS-specific list of path into []string

func (*Echo) PathSym

func (e *Echo) PathSym(path string) string

PathSym returns the evaluated symbolic link for path. Returns empty if symbolic evaluation fails.

func (*Echo) Rel

func (e *Echo) Rel(base string, target string) string

Rel returns path that is relative to base/target. Returns an empty path if error.

func (*Echo) Rmdirs

func (e *Echo) Rmdirs(paths string)

Rmdirs removes one or more space-separated directories

func (*Echo) Run

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

Run parses and executes cmdStr and returns the result as a string. This uses RunProc and extracts the result as a string.

func (*Echo) RunProc

func (e *Echo) RunProc(cmdStr string) *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 parses and executes command cmdStr and prints out the result

func (*Echo) SetEnv

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

SetEnv declares a global process environment variable.

func (*Echo) SetVar

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

SetVar declares an echo session local variable.

func (*Echo) Split

func (e *Echo) Split(list string, sep ...string) []string

Split splits a space-separated (default) string into []string. An optional separator sep maybe provided as well.

func (*Echo) StartProc

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

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

func (*Echo) Streq

func (e *Echo) Streq(val0, val1 string) bool

Streq returns true if both strings are equal

func (*Echo) String

func (e *Echo) String() string

func (*Echo) Trim

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

Trim removes spaces around a val

func (*Echo) Upper

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

Upper returns val as upper case

func (*Echo) Val

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

Val retrieves a session or environment variable

func (*Echo) Var

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

Var declares variables used during current echo session using a multi-line space-separated list of KEY=VAL format: i.e. foo=bar fuzz=buzz

type File

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

func (*File) Append

func (f *File) Append(data string)

Append appends to an existing os.File (mode 0644) and writes data into it

func (*File) AppendBytes

func (f *File) AppendBytes(data []byte)

AppendBytes appends bytes to an existing os.File (mode 0644)

func (*File) AppendLines

func (f *File) AppendLines(lines []string)

AppendLines appends lines to an existing os.File (mode 0644)

func (*File) Err

func (f *File) Err() error

Err returns any execution error

func (*File) Read

func (f *File) Read() string

Read opens an *os.File and reads its content as string

func (*File) ReadBytes

func (f *File) ReadBytes() []byte

ReadBytes opens an *os.File and read its content as []byte

func (*File) ReadLines

func (f *File) ReadLines() []string

ReadLines opens an *os.File and read its content as []string

func (*File) Reader

func (f *File) Reader() io.ReadCloser

Reader opens an *os.File and returns it as io.ReadCloser Ensure to call io.ReadCloser.Close() after use.

func (*File) StreamFrom

func (f *File) StreamFrom(r io.Reader)

StreamFrom creates a new file for f and streams bytes from r into it

func (*File) StreamTo

func (f *File) StreamTo(w io.Writer)

StreamTo streams content of file f into w

func (*File) Write

func (f *File) Write(data string)

Write creates/truncates an os.File (mode 0666) and writes data into it

func (*File) WriteBytes

func (f *File) WriteBytes(data []byte)

WriteBytes opens an os.File and writes data into it

func (*File) WriteLines

func (f *File) WriteLines(lines []string)

WriteLines opens an os.File and writes data into it

func (*File) Writer

func (f *File) Writer() io.WriteCloser

Writer opens an os.File and returns it as io.WriteCloser Ensure to call io.WriterCloser.Close() after use

type Proc

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

Proc stores process info

func (*Proc) Command

func (p *Proc) Command() *exec.Cmd

Command returns the os/exec.Cmd that started the process

func (*Proc) Err

func (p *Proc) Err() error

Err returns any execution error

func (*Proc) ExitCode

func (p *Proc) ExitCode() int

ExitCode returns process exit code

func (*Proc) Exited

func (p *Proc) Exited() bool

Exited returns true if process exits ok

func (*Proc) ID

func (p *Proc) ID() int

ID returns process id

func (*Proc) IsSuccess

func (p *Proc) IsSuccess() bool

IsSuccess returns true if proc exit ok

func (*Proc) Kill

func (p *Proc) Kill() *Proc

Kill halts the process

func (*Proc) Out

func (p *Proc) Out() io.Reader

Out surfaces an io.Reader for both stdout and stderr Call after echo.RunProc

func (*Proc) Peek

func (p *Proc) Peek() *Proc

Peek attempts to read process state information

func (*Proc) Result

func (p *Proc) Result() (result string)

Result surfaces standard output and error as a string Call after echo.RunProc or, in the following sequence echo.StartProc, proc.Result, proc.Wait

func (*Proc) StdErr

func (p *Proc) StdErr() io.Reader

StdErr is a io.Reader pipe for standard error Can be streamed before Pro.Wait()

func (*Proc) StdOut

func (p *Proc) StdOut() io.Reader

StdOut is a io.Reader pipe for standard out Can be streamed before Pro.Wait()

func (*Proc) SysTime

func (p *Proc) SysTime() time.Duration

SysTime returns proc system cpu time

func (*Proc) UserTime

func (p *Proc) UserTime() time.Duration

UserTime returns proc user cpu time

func (*Proc) Wait

func (p *Proc) Wait() *Proc

Wait for associated process to complete. Any error can be accessed via p.Err()

Directories

Path Synopsis
examples
build 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