task

package module
v1.1.9 Latest Latest
Warning

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

Go to latest
Published: May 16, 2024 License: BSD-3-Clause Imports: 15 Imported by: 8

README

Task

Task runs a sequence of actions. Errors and failures are handled centerally. Rollback actions can be defined and added as the task progresses.

Commands and flags may be defined to begin the correct task.

Documentation

Overview

Package task handles running a sequence of tasks. State context is separated from script actions. Native context support.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Environ

func Environ() map[string]string

Environ calls os.Environ and maps it to key value pairs.

func ExpandEnv

func ExpandEnv(text any, st *State) string

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 Run

func Run(ctx context.Context, st *State, a Action) error

Run is the entry point for actions. It is a short-cut for ScriptAdd and Run.

func Start

func Start(ctx context.Context, stopTimeout time.Duration, run StartFunc) error

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

type Action interface {
	Run(ctx context.Context, st *State, sc Script) error
}

Action is a unit of work that gets run.

func AddRollback

func AddRollback(a ...Action) Action

AddRollback adds rollback actions to the current Script. Rollback actions are only executed on failure under non-Continue policies.

func CloseFile added in v1.1.1

func CloseFile(file any) Action

CloseFile closes the file. File may be a VAR or io.Closer.

func Copy

func Copy(old, new any, only func(p string, st *State) bool) Action

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

func Defer(a ...Action) Action

Defer actions to the current end of the script. Always execute on error or success.

func Delete

func Delete(filename any) Action

Delete file. The filename may be VAR or string.

func Env

func Env(env ...string) Action

Env sets one or more environment variables. To delete an environment variable just include the key, no equals.

Env("GOOS=linux", "GOARCH=arm64")

func Exec

func Exec(executable any, args ...any) Action

Exec runs an executable. The executable and args may be of type VAR or string.

func ExecStdin added in v1.1.0

func ExecStdin(stdin any, executable any, args ...any) Action

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 Move

func Move(old, new any) Action

Move file. The filenames old and new may be VAR or string.

func OpenFile added in v1.1.1

func OpenFile(filename any, file any) Action

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

func ReadFile(filename any, output any) Action

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 Rollback added in v1.1.2

func Rollback(a ...Action) Action

Rollback adds actions to the current rollback script.

func Switch

func Switch(f Action, sw map[Branch]Action) Action

Switch will run the f action, read the state branch value, and then execute the given action in sw.

func WithPolicy

func WithPolicy(p Policy, a Action) Action

WithPolicy sets the state policy for a single action.

func WithStd added in v1.1.9

func WithStd(stdout, stderr any, a Action) Action

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

func WithStdCombined(std any, a Action) Action

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.

func WriteFile added in v1.1.0

func WriteFile(filename any, perm os.FileMode, input any) Action

WriteFile writes the given file from the input. Input may be a VAR, []byte, string, or io.Reader. The filename may be VAR or string.

type ActionFunc

type ActionFunc func(ctx context.Context, st *State, sc Script) error

ActionFunc runs a function like an Action.

func (ActionFunc) Run

func (f ActionFunc) Run(ctx context.Context, st *State, sc Script) error

Run the ActionFunc.

type Branch

type Branch int64

Branch represents a branch condition used in Switch.

const (
	BranchUnset Branch = iota
	BranchTrue
	BranchFalse
	BranchCommit
	BranchRollback

	// BranchCustom is the smallest custom branch value that may be used.
	BranchCustom Branch = 1024
)

Typical branch values.

type Command

type Command struct {
	Name     string
	Usage    string
	Flags    []*Flag
	Commands []*Command
	Action   Action
}

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)

func (*Command) Exec

func (c *Command) Exec(args []string) Action

Exec takes a command arguments and returns an Action, ready to be run.

type ErrUsage

type ErrUsage string

ErrUsage signals that the error returned is not a runtime error but a usage message.

func (ErrUsage) Error

func (err ErrUsage) Error() string

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 FlagType

type FlagType byte

FlagType is set in Flag and determins how the value is parsed.

const (
	FlagAuto FlagType = iota
	FlagString
	FlagBool
	FlagInt64
	FlagFloat64
	FlagDuration
)

FlagType options. If a default is present the flag type may be left as Auto to choose the parse type based on the default type.

type Policy

type Policy byte

Policy describes the current error policy.

const (
	PolicyFail     Policy = 0
	PolicyContinue Policy = 1 << iota
	PolicyLog
	PolicySkipRollback
)

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

func NewScript added in v1.1.0

func NewScript(a ...Action) Script

NewScript creates a script and appends the given actions to it.

type StartFunc

type StartFunc func(ctx context.Context) error

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

func (st *State) Default(name string, v interface{}) interface{}

Default gets the variable called name from the state bucket. If no value is present, return v.

func (*State) Delete

func (st *State) Delete(name string)

Delete the variable called name.

func (*State) Error

func (st *State) Error(err error)

Error reports an error to the ErrorLogger if present.

func (*State) Filepath

func (st *State) Filepath(filename string) string

Filepath returns filename if absolute, or State.Dir + filename if not.

func (*State) Get

func (st *State) Get(name string) interface{}

Get the variable called name from the state bucket.

func (*State) Log

func (st *State) Log(msg string)

Log a message to the MsgLogger if present.

func (*State) Logf

func (st *State) Logf(f string, v ...interface{})

Logf logs a formatted message to the MsgLogger if present.

func (*State) Set

func (st *State) Set(name string, v interface{})

Set the variable v to the name.

func (*State) Values added in v1.1.0

func (st *State) Values() map[string]interface{}

Values of the state.

type VAR added in v1.1.5

type VAR string

VAR represents a state variable name. When passed to a function, resolves to the state variable name.

Directories

Path Synopsis
Package fsop has common file system operations.
Package fsop has common file system operations.

Jump to

Keyboard shortcuts

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