runutil

package
v0.0.0-...-abfb8b1 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2016 License: BSD-3-Clause Imports: 17 Imported by: 21

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetOriginalError

func GetOriginalError(err error) error

GetOriginalError gets the original error wrapped in the supplied err. If the given err has not been wrapped by Sequence, then the supplied error is returned.

func IsExist

func IsExist(err error) bool

IsExist returns a boolean indicating whether the error is known to report that a file or directory already exists.

func IsNotExist

func IsNotExist(err error) bool

IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist.

func IsPermission

func IsPermission(err error) bool

IsPermission returns a boolean indicating whether the error is known to report that permission is denied.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout returns a boolean indicating whether the error is a result of a timeout.

func TranslateExitCode

func TranslateExitCode(err error) error

TranslateExitCode translates errors from the "os/exec" package that contain exit codes into cmdline.ErrExitCode errors.

Types

type Handle

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

Handle represents a command running in the background.

func (*Handle) Kill

func (h *Handle) Kill() error

Kill terminates the currently running background process.

func (*Handle) Pid

func (h *Handle) Pid() int

Pid returns the pid of the running process.

func (*Handle) Signal

func (h *Handle) Signal(sig os.Signal) error

func (*Handle) Wait

func (h *Handle) Wait() error

Wait waits for the currently running background process to terminate.

type Sequence

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

Sequence provides for convenient chaining of multiple calls to its methods to avoid repeated tests for error returns. The usage is:

err := s.Run("echo", "a").Run("echo", "b").Done()

The first method to encounter an error short circuits any following methods and the result of that first error is returned by the Done method or any of the other 'terminating methods' (see below). Sequence is not thread safe. It also good practice to use a new instance of a Sequence in defer's.

Unless directed to specific stdout and stderr io.Writers using Capture(), the stdout and stderr output from the command is discarded, unless an error is encountered, in which case the output from the command that failed (both stdout and stderr) is written to the stderr io.Writer specified via NewSequence. In addition, in verbose mode, command execution logging is written to the stdout and stderr io.Writers configured via NewSequence, and never to the stdout specified via Capture if the command succeeded.

Modifier methods are provided that influence the behaviour of the next invocation of the Run method to set timeouts (Timed), to capture output (Capture), input (Read) and to set the environment (Env). For example, the following will result in a timeout error.

err := s.Timeout(time.Second).Run("sleep","10").Done() err := s.Timeout(time.Second).Last("sleep","10")

A sequence of commands must be terminated with a call to a 'terminating' method. The simplest are the Done or Last methods used in the examples above, but there are other methods which typically return results in addition to error, such as ReadFile(filename string) ([]byte, error). Here the usage would be:

o.Stdout, _ = os.Create("foo") data, err := s.Capture(o, nil).Run("echo","b").ReadFile("foo") // data == "b"

Note that terminating functions, even those that take an action, may return an error generated by a previous method.

In addition to Run which will always run a command as a subprocess, the Call method will invoke a function. Note that Capture and Timeout do not affect such calls.

Errors returned by Sequence augment those returned by the underlying packages with details of the exact call that generated those errors. This means that it is not possible to test directly for errors from those packages. The GetOriginalError function can be used to obtain the error from the underlying package, or the IsTimeout, IsNotExists etc functions can be used on the wrapped error. The ExitCode method is also provided to convert to the exit codes expected by the v.io/x/lib/cmdline package which is often used in conjunction with Sequence.

Example
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"regexp"

	"v.io/jiri/runutil"
)

func rmLineNumbers(s string) string {
	re := regexp.MustCompile("(.*\\.go):\\d+:(.*)")
	return re.ReplaceAllString(s, "$1:-:$2")
}

func main() {
	seq := runutil.NewSequence(nil, os.Stdin, ioutil.Discard, ioutil.Discard, false, false)
	err := seq.
		Capture(os.Stdout, nil).Run("echo", "a").
		Capture(os.Stdout, nil).Last("echo", "b")
	err = seq.
		Run("echo", "c").
		Run("xxxxxxx").
		Capture(os.Stdout, nil).Last("echo", "d")
	// Get rid of the line#s in the error output.
	fmt.Println(rmLineNumbers(err.Error()))
}
Output:

a
b
sequence_test.go:-: Run("xxxxxxx"): exec: "xxxxxxx": executable file not found in $PATH

func NewSequence

func NewSequence(env map[string]string, stdin io.Reader, stdout, stderr io.Writer, color, verbose bool) Sequence

NewSequence creates an instance of Sequence with default values for its environment, stdin, stderr, stdout and other supported options. If the environment parameter is nil or empty then the current value of os.Environ() will be used instead.

func (Sequence) AssertDirExists

func (s Sequence) AssertDirExists(dirname string) Sequence

AssertDirExists asserts that the specified directory exists with appropriate logging.

func (Sequence) AssertFileExists

func (s Sequence) AssertFileExists(file string) Sequence

AssertFileExists asserts that the specified file exists with appropriate logging.

func (Sequence) Call

func (s Sequence) Call(fn func() error, format string, args ...interface{}) Sequence

Call runs the given function. Note that Capture and Timeout have no effect on invocations of Call, but Opts can control logging.

func (Sequence) Capture

func (s Sequence) Capture(stdout, stderr io.Writer) Sequence

Capture arranges for the next call to Run or Last to write its stdout and stderr output to the supplied io.Writers. This will be cleared and not used for any calls to Run or Last beyond the next one. Specifying nil for a writer will result in using the the corresponding io.Writer supplied to NewSequence. ioutil.Discard should be used to discard output.

func (Sequence) Chdir

func (s Sequence) Chdir(dir string) Sequence

Chdir is a wrapper around os.Chdir that handles options such as "verbose".

func (Sequence) Chmod

func (s Sequence) Chmod(dir string, mode os.FileMode) Sequence

Chmod is a wrapper around os.Chmod that handles options such as "verbose".

func (Sequence) Copy

func (s Sequence) Copy(dst io.Writer, src io.Reader) (n int64, err error)

Copy is a wrapper around io.Copy that handles options such as "verbose". Copy is a terminating function.

func (Sequence) Create

func (s Sequence) Create(name string) (f *os.File, err error)

Create is a wrapper around os.Create that handles options such as "verbose" . Create is a terminating function.

func (Sequence) Dir

func (s Sequence) Dir(dir string) Sequence

Dir sets the working directory for the next subprocess that is created via Run, Call, Start or Last to the supplied parameter. This is the only way to safely set the working directory of a command when multiple threads are used.

func (Sequence) Done

func (s Sequence) Done() error

Done returns the error stored in the Sequence and pops back to the first entry in the directory stack if Pushd has been called. Done is a terminating function. There is no need to ensure that Done is called before returning from a function that uses a sequence unless it is necessary to pop the stack.

func (Sequence) Env

func (s Sequence) Env(env map[string]string) Sequence

Env arranges for the next call to Run, Call, Start or Last to use the result of merging the supplied environment variables with those specified when the sequence was created or with those set by the most recent call to the Env method. These will be cleared and not used for any calls to Run, Call or Last beyond the next one.

func (Sequence) Error

func (s Sequence) Error() error

Error returns the error, if any, stored in the Sequence.

func (Sequence) Fprintf

func (s Sequence) Fprintf(f io.Writer, format string, args ...interface{}) Sequence

Fprintf calls fmt.Fprintf.

func (Sequence) IsDir

func (s Sequence) IsDir(dirname string) (bool, error)

IsDir is a wrapper around os.Stat with appropriate logging that returns true of dirname exists and is a directory. IsDir is a terminating function.

func (Sequence) IsFile

func (s Sequence) IsFile(file string) (bool, error)

IsFile is a wrapper around os.Stat with appropriate logging that returns true if file exists and is not a directory. IsFile is a terminating function.

func (Sequence) Last

func (s Sequence) Last(path string, args ...string) error

Last runs the given command as a subprocess and returns an error immediately terminating the sequence, it is equivalent to calling s.Run(path, args...).Done().

func (Sequence) Lstat

func (s Sequence) Lstat(name string) (fi os.FileInfo, err error)

Lstat is a wrapper around os.Lstat that handles options such as "verbose". Lstat is a terminating function.

func (Sequence) MkdirAll

func (s Sequence) MkdirAll(dir string, mode os.FileMode) Sequence

MkdirAll is a wrapper around os.MkdirAll that handles options such as "verbose".

func (Sequence) Open

func (s Sequence) Open(name string) (f *os.File, err error)

Open is a wrapper around os.Open that handles options such as "verbose". Open is a terminating function.

func (Sequence) OpenFile

func (s Sequence) OpenFile(name string, flag int, perm os.FileMode) (f *os.File, err error)

OpenFile is a wrapper around os.OpenFile that handles options such as "verbose". OpenFile is a terminating function.

func (Sequence) Output

func (s Sequence) Output(output []string) Sequence

Output logs the given list of lines using the currently in effect verbosity as specified by Opts, or the default otherwise.

func (Sequence) Popd

func (s Sequence) Popd() Sequence

Popd popds the last directory from the directory stack and chdir's to it. Calling any termination function will pop back to the first element in the stack on completion of that function.

func (Sequence) Pushd

func (s Sequence) Pushd(dir string) Sequence

Pushd pushes the current directory onto a stack and changes directory to the specified one. Calling any terminating function will pop back to the first element in the stack on completion of that function.

func (Sequence) Read

func (s Sequence) Read(stdin io.Reader) Sequence

Read arranges for the next call to Run or Last to read from the supplied io.Reader. This will be cleared and not used for any calls to Run or Last beyond the next one. Specifying nil will result in reading from os.DevNull.

func (Sequence) ReadDir

func (s Sequence) ReadDir(dirname string) (fi []os.FileInfo, err error)

ReadDir is a wrapper around ioutil.ReadDir that handles options such as "verbose". ReadDir is a terminating function.

func (Sequence) ReadFile

func (s Sequence) ReadFile(filename string) (bytes []byte, err error)

ReadFile is a wrapper around ioutil.ReadFile that handles options such as "verbose". ReadFile is a terminating function.

func (s Sequence) Readlink(name string) (link string, err error)

Readlink is a wrapper around os.Readlink that handles options such as "verbose". Lstat is a terminating function.

func (Sequence) Remove

func (s Sequence) Remove(file string) Sequence

Remove is a wrapper around os.Remove that handles options such as "verbose".

func (Sequence) RemoveAll

func (s Sequence) RemoveAll(dir string) Sequence

RemoveAll is a wrapper around os.RemoveAll that handles options such as "verbose".

func (Sequence) Rename

func (s Sequence) Rename(src, dst string) Sequence

Rename is a wrapper around os.Rename that handles options such as "verbose".

func (Sequence) Run

func (s Sequence) Run(path string, args ...string) Sequence

Run runs the given command as a subprocess.

func (Sequence) RunOpts

func (s Sequence) RunOpts() (verbose bool)

RunOpts returns the value of verbose that was used to create this sequence.

func (Sequence) SetEnv

func (s Sequence) SetEnv(env map[string]string) Sequence

SetEnv arranges for the next call to Run, Call, Start or Last to use the supplied environment variables. These will be cleared and not used for any calls to Run, Call or Last beyond the next one.

func (Sequence) Start

func (s Sequence) Start(path string, args ...string) (*Handle, error)

Start runs the given command as a subprocess in background and returns a handle that can be used to kill and/or wait for that background process. Start is a terminating function.

func (Sequence) Stat

func (s Sequence) Stat(name string) (fi os.FileInfo, err error)

Stat is a wrapper around os.Stat that handles options such as "verbose". Stat is a terminating function.

func (s Sequence) Symlink(src, dst string) Sequence

Symlink is a wrapper around os.Symlink that handles options such as "verbose".

func (Sequence) TempDir

func (s Sequence) TempDir(dir, prefix string) (tmpDir string, err error)

TempDir is a wrapper around ioutil.TempDir that handles options such as "verbose". TempDir is a terminating function.

func (Sequence) TempFile

func (s Sequence) TempFile(dir, prefix string) (f *os.File, err error)

TempFile is a wrapper around ioutil.TempFile that handles options such as "verbose".

func (Sequence) Timeout

func (s Sequence) Timeout(timeout time.Duration) Sequence

Timeout arranges for the next call to Run, Start or Last to be subject to the specified timeout. The timeout will be cleared and not used any calls to Run or Last beyond the next one. It has no effect for calls to Call.

func (Sequence) Verbose

func (s Sequence) Verbose(verbosity bool) Sequence

Verbosity arranges for the next call to Run, Call, Start or Last to use the specified verbosity. This will be cleared and not used for any calls to Run, Call or Last beyond the next one.

func (Sequence) WriteFile

func (s Sequence) WriteFile(filename string, data []byte, perm os.FileMode) Sequence

WriteFile is a wrapper around ioutil.WriteFile that handles options such as "verbose".

Jump to

Keyboard shortcuts

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