Documentation ¶
Overview ¶
Package task handles running a sequence of tasks. State context is separated from script actions. Native context support.
Index ¶
- func Environ() map[string]string
- func ExpandEnv(text any, st *State) string
- func Run(ctx context.Context, st *State, a Action) error
- func Start(ctx context.Context, stopTimeout time.Duration, run StartFunc) error
- type Action
- func AddRollback(a ...Action) Action
- func CloseFile(file any) Action
- func Copy(old, new any, only func(p string, st *State) bool) Action
- func Defer(a ...Action) Action
- func Delete(filename any) Action
- func Env(env ...string) Action
- func Exec(executable any, args ...any) Action
- func ExecStdin(stdin any, executable any, args ...any) Action
- func Move(old, new any) Action
- func OpenFile(filename any, file any) Action
- func ReadFile(filename any, output any) Action
- func Rollback(a ...Action) Action
- func Switch(f Action, sw map[Branch]Action) Action
- func WithPolicy(p Policy, a Action) Action
- func WithStd(stdout, stderr any, a Action) Action
- func WithStdCombined(std any, a Action) Action
- func WriteFile(filename any, perm os.FileMode, input any) Action
- type ActionFunc
- type Branch
- type Command
- type ErrUsage
- type Flag
- type FlagType
- type Policy
- type Script
- type StartFunc
- type State
- func (st *State) Default(name string, v interface{}) interface{}
- func (st *State) Delete(name string)
- func (st *State) Error(err error)
- func (st *State) Filepath(filename string) string
- func (st *State) Get(name string) interface{}
- func (st *State) Log(msg string)
- func (st *State) Logf(f string, v ...interface{})
- func (st *State) Set(name string, v interface{})
- func (st *State) Values() map[string]interface{}
- type VAR
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExpandEnv ¶
ExpandEnv will expand env vars from s and return the combined string. Var names may take the form of "text${var}suffix". The source of the value will first look for current state bucket, then in the state Env. The text may be VAR or string.
func Start ¶
Start listens for an interrupt signal, and cancels the context if interrupted. It starts run in a new goroutine. If it takes more then stopTimeout before run returns after the ctx is canceled, then it returns regardless.
Example ¶
package main import ( "context" "fmt" "time" "github.com/kardianos/task" ) func main() { run := func(ctx context.Context) error { return fmt.Errorf("Return errors at top level") } err := task.Start(context.Background(), time.Second*2, run) if err != nil { fmt.Println(err) } }
Output: Return errors at top level
Types ¶
type Action ¶
Action is a unit of work that gets run.
func AddRollback ¶
AddRollback adds rollback actions to the current Script. Rollback actions are only executed on failure under non-Continue policies.
func Copy ¶
Copy file or folder recursively. If only is present, only copy path if only returns true. The filenames old and new may be VAR or string.
func Defer ¶ added in v1.1.2
Defer actions to the current end of the script. Always execute on error or success.
func Env ¶
Env sets one or more environment variables. To delete an environment variable just include the key, no equals.
Env("GOOS=linux", "GOARCH=arm64")
func ExecStdin ¶ added in v1.1.0
ExecStdin runs an executable and streams the output to stderr and stdout. The stdin takes one of: nil, "string (state variable to []byte data), []byte, or io.Reader. The executable and args may be of type VAR or string.
func OpenFile ¶ added in v1.1.1
OpenFile opens the filename and stores the file handle in file, either as in a state name (string) or as a *io.Closer. The filename may be VAR or string.
func ReadFile ¶ added in v1.1.0
ReadFile reads the given file into the stdin bucket variable as a []byte. output may be a VAR, *string, *[]byte, or io.Writer. The filename may be VAR or string.
func Switch ¶
Switch will run the f action, read the state branch value, and then execute the given action in sw.
func WithPolicy ¶
WithPolicy sets the state policy for a single action.
func WithStd ¶ added in v1.1.9
WithStd runs the child script using adjusted stdout and stderr outputs. stdout and stderr may be nil, VAR (state name stored as []byte), io.Writer, *string, or *[]byte.
func WithStdCombined ¶ added in v1.1.0
WithStdCombined runs the child script using adjusted stdout and stderr outputs. std may be nil, string (state name stored as []byte), io.Writer, or *[]byte.
type ActionFunc ¶
ActionFunc runs a function like an Action.
type Command ¶
Command represents an Action that may be invoked with a name. Flags will be mapped to State bucket values. Extra arguments at the end of a command chain will be passed to the state as "args []string". To pass arguments to a command that has sub-commands, first pass in "--" then pass in the arguments.
exec cmd arg1 arg2 # cmd has no sub-commands. exec cmd -- arg1 arg2 # cmd has one or more sub-commands.
Example ¶
package main import ( "context" "fmt" "os" "time" "github.com/kardianos/task" ) func main() { showVar := func(name string) task.Action { return task.ActionFunc(func(ctx context.Context, st *task.State, sc task.Script) error { st.Log(fmt.Sprintf("var %s = %[2]v (%[2]T)", name, st.Get(name))) return nil }) } cmd := &task.Command{ Name: "cmder", Usage: "Example Commander", Flags: []*task.Flag{ {Name: "f1", Usage: "set the current f1", Default: "ghi"}, {Name: "f2", Usage: "set the current f2", Default: "nmo"}, {Name: "f3", Usage: "set the current f3", Default: "fhg", ENV: "CMDER_F3"}, }, Commands: []*task.Command{ {Name: "run1", Usage: "run the first one here", Action: task.NewScript( task.ExecStdin("ps", "-A"), task.ExecStdin("ls", "-la"), )}, { Name: "run2", Usage: "run the second one here", Flags: []*task.Flag{ {Name: "tf", Default: false, Type: task.FlagBool}, }, Action: task.NewScript( showVar("f1"), showVar("f2"), showVar("f3"), showVar("tf"), ), }, }, } args := []string{"-f1", "xyz", "run2", "-tf"} // os.Args[1:] st := task.DefaultState() st.Env = map[string]string{ "CMDER_F3": "sky", } ctx := context.Background() err := task.Start(ctx, time.Second*3, func(ctx context.Context) error { err := task.Run(ctx, st, cmd.Exec([]string{"-help"})) fmt.Fprintf(os.Stdout, "%s", err) fmt.Println("---") return task.Run(ctx, st, cmd.Exec(args)) }) if err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } }
Output: invalid flag -help cmder - Example Commander -f1 - set the current f1 (ghi) -f2 - set the current f2 (nmo) -f3 [CMDER_F3] - set the current f3 (fhg) run1 - run the first one here run2 - run the second one here --- var f1 = xyz (string) var f2 = nmo (string) var f3 = sky (string) var tf = true (bool)
type ErrUsage ¶
type ErrUsage string
ErrUsage signals that the error returned is not a runtime error but a usage message.
type Flag ¶
type Flag struct { Name string // Name of the flag. ENV string // Optional env var to read from if flag not present. Usage string Required bool // Required flag, will error if not set. Value any Default any Type FlagType Validate func(v any) error }
Flag represents values that may be set on comments. Values will be mapped to State bucket values.
type Policy ¶
type Policy byte
Policy describes the current error policy.
Policies may be combined together. The default policy is to fail on error and run any rollback acitions. If Continue is selected then normal execution will proceed and a rollback will not be triggered. If Log is selected any error will be logged to the ErrorLogger. If SkipRollback is selected then a failure will not trigger the rollback actions. If both Continue and SkipRollbackk are selected, execution will continue and SkipRollback will be ignored.
type Script ¶
type Script interface { Add(a ...Action) // Add normal actions to the script. Rollback(a ...Action) // Add actions to only be run on rollback. Defer(a ...Action) // Add actions to be run at the end, both on error and on normal run. RunAction(ctx context.Context, st *State, a Action) error // Run a single action on the script. Run(ctx context.Context, st *State, parent Script) error // Run current script under givent state. }
Script is a list of actions. If an action
type StartFunc ¶
StartFunc is called during start-up, but should watch the context to check if it should shutdown.
type State ¶
type State struct { Env map[string]string Dir string // Current working directory. Stdout io.Writer Stderr io.Writer Branch Branch Policy Policy ErrorLogger func(err error) // Logger to use when Error is called. MsgLogger func(msg string) // Logger to use when Log or Logf is called. // contains filtered or unexported fields }
State of the current task.
func DefaultState ¶
func DefaultState() *State
DefaultState creates a new states with the current OS env.
func (*State) Default ¶
Default gets the variable called name from the state bucket. If no value is present, return v.