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

echo

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

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

Go to latest
Published: Jan 20, 2020 License: MIT Imports: 13 Imported by: 0

README

Echo$

Script-like functionalities wrapped in the rigid safety of Go!

Start

Create a session:

e := echo.New()

Then configure your session:

e.Conf.SetPanicOnError(true)

Variables

Var, SetVar

Echo supports storing values that can be accessed using method e.Var() for the duration of a session:

e.Var("Foo=Bar")
e.Var("Fuzz=${Foo} Buzz=Bazz") 

Method e.SetVar(name, value string) saves a named value one at a time.

Env, SetEnv

Values can be made visible as environment variables for externally launced commands using method e.Env(). Both methods support value expansion as shown below:

e.Env("Foo=Bar")
e.Env("Fuzz=${Foo} Buzz=Bazz")
e.Env("BAZZ=$HOME")

Method e.SetEnv(name, value string) sets environment variables one value at a time.

Expansion

All echo methods support variable value expansion using $name or ${name} which are automatically replaced with the value of the named variable.

Slices

Split

A space-separated list can be turned into a native Go []string using the e.Split() method as shown:

e.SetVar("list", "item3 item4")
for _, val := range e.Split("item0 item1 item2 $list"){  
    ...
}

An additional separator value may be provided to e.Split():

e.SetVar("list", "item3;item4")
for _, val := range e.Arr("Hello;World;!;$list", ";"){  
    fmt.Println(val)
}
Glob

Method e.Glob() expands the provided shell path pattern into a slice of matching file/directory names:

for _, f := range e.Glob("$HOME/go/src/*.com") {
  fmt.Println(f)
}

Program

Echo exposes the Prog type which provides access to methods related to the running program as listed below:

e.Prog.Name() - Then name of the running binary
e.Prog.Path() - the full path of the running binary
e.Prog.Args() - Slice of CLI parameters
e.Prog.Exit() - Exits the running program
e.Prog.Pid() - The process ID for the program
e.Prog.Ppid() - The program's parent process ID
e.Prog.Workdir() - the current working directory of the program
e.Prog.Avail(path) - Returns the full path of the specified program if available

Processes

Echo can be used to start external processes by wraping the os/exec types. Methods that start processes return a *Proc value with information about the started process.

StartProc

Method e.StartProc(<command-string>) starts a new process by running the provided command string. The method returns a Proc which can be used to track the process as shown below:

proc := e.StartProc('echo "Hello World!"')
fmt.Println("Proces id", proc.ID)

Method e.StartProc returns immediately and does not wait for the process to complete. This means Proc information may be incomplete since the process may still be running (see Managing Processes for detail).

Each proc started is also saved in the Echo session and can be reached via slice e.Procs[].

Managing Processes

When a process is launched with StartProc, it immediately returns a value of type Proc which exposes several methods to inspect the running (or completed) process.

proc.ExitCode() - the process exit code
proc.Exited() - true if program finished
proc.ID() - the process ID
proc.IsSuccess() - true if program finished with no error
proc.Peek() - Updates process state information
proc.SysTime() - the system time for the executed process
proc.UserTime() - the system user time for executed process
proc.Out() - exposes an io.Reader to stream result (generate error)
proc.Result() - reads all command result from proc.Out() and returns it as string (generate error)
proc.Wait() - Blocks, waits for a process to complete (generate error)

Type Proc stores the last error generated by invoking any of its methods. The error can be accessed as proc.Err() as shown below:

proc := e.StartProc('echo "Hello world!"')
proc.Wait()
// optionally check for error
if proc.Err() != nil {
    fmt.Printl(proc.Err())
}
RunProc

As a convenience, the Proc namespace exposes three methods that will start a process and wait for it to complete. First, method e.RunProc starts a process, wait for it to complete, then returns a value of type Proc:

e.Var("CONTAINER_IMG", "hello-world")
proc := e.RunProc('docker run --rm --detach $CONTAINER_IMG')
r := proc.Result()
if e.IsEmpty(r) || proc.Err() != nil {
    fmt.Println("found error:", proc.Err())
}
fmt.Println("Ran container container:", r)

Run

Method e.Run starts a process, wait for it to complete, and then returns a string value as the result from the executed command:

r := e.Var("CONTAINER_IMG", "hello-world").RunProc('docker run --rm --detach $CONTAINER_IMG')
if e.IsEmpty(r) || proc.Err() != nil {
    fmt.Println("found error:", proc.Err())
}
fmt.Println("Ran container container:", r)

Note that e.Run is equivalent to calling e.RunProc and then calling method Result on the returned Proc.

Runout

Method e.Runout starts a process, wait for its completion, and then prints the result to standard output:

e.Var("CONTAINER_IMG", "hello-world").Runout('docker run --rm --detach $CONTAINER_IMG')

Strings

e.Empty(string) bool
e.Lower(string) string
e.Upper(string) string
e.Streq(string, string) bool // string equal
e.Trim(string)string 

Files

File operation methods:

e.Abs()
e.Rel()
e.Base()
e.Dir()
e.PathSym()
e.Ext()
e.PathJoin()
e.PathMatched()
e.IsExit()
e.IsReg()
e.IsDir()
e.Mkdirs()
e.Rmdirs()
e.Chown()
e.Chmod()
e.AreSame() // Are files equal

User

e.Username()
e.Home()
e.Gid()
e.Uid()

Flagset

...

More to come

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

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

Proc stores process info

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

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

Out surfaces an io.Reader for proc result

func (*Proc) Peek

func (p *Proc) Peek() *Proc

Peek attempts to read process state information

func (*Proc) Result

func (p *Proc) Result() string

Result streams output into a string

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

Jump to

Keyboard shortcuts

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