task

package
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 49 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaximumTaskCall is the max number of times a task can be called.
	// This exists to prevent infinite loops on cyclic dependencies
	MaximumTaskCall = 1000
)

Variables

View Source
var DefaultRitefile string
View Source
var ErrPreconditionFailed = errors.New("rite: precondition not met")

ErrPreconditionFailed is returned when a precondition fails

Functions

func Completion

func Completion(completion string) (string, error)

func FilterOutInternal

func FilterOutInternal(task *ast.Task) bool

FilterOutInternal removes all tasks that are marked as internal.

func FilterOutNoDesc

func FilterOutNoDesc(task *ast.Task) bool

FilterOutNoDesc removes all tasks that do not contain a description.

func IncludedRitefilePathForTest added in v1.0.1

func IncludedRitefilePathForTest(srcPath string) string

IncludedRitefilePathForTest exports includedRitefilePath for the same reason as RitefilePathForTest.

func InitRitefile

func InitRitefile(path string) (string, error)

InitRitefile creates a new Ritefile at path.

path can be either a file path or a directory path. If path is a directory, path/Ritefile.yml will be created.

The final file path is always returned and may be different from the input path.

func Migrate

func Migrate(srcPath string, warn io.Writer, opts ...MigrateOption) (dstPath string, err error)

Migrate reads a go-task Taskfile at srcPath, writes a converted Ritefile to the same directory, and emits a warning for every construct the fork's first-in-wins semantics would silently change the meaning of. Warnings go to warn; any fatal parse error is returned.

The tool does NOT attempt a deep structural rewrite — upstream's YAML is a near-superset of ours and most of it round-trips unchanged. What we DO transform on disk:

  • The entrypoint is written as `<dir>/Ritefile<ext>` (e.g. `Taskfile.yml` → `Ritefile.yml`, `Taskfile.dist.yaml` → `Ritefile.dist.yaml`).
  • Any local file referenced from any walked file's `includes:` block is recursively migrated. Each included source gets a per-source destination name derived from its basename (`ci/a.yml` → `ci/a.Ritefile.yml`; `.taskfiles/android.Taskfile.yml` → `.taskfiles/android.Ritefile.yml`). The root is the only file that claims the canonical `Ritefile<ext>` name.
  • Every `includes:` entry whose target resolves to a file we migrated is rewritten to point at the new destination. URL includes and files that don't exist on disk are skipped with a warning and left unchanged in the rewritten YAML.

Everything else flows through verbatim, preserving user comments and formatting (we string-substitute rather than re-serialize the AST).

Detected semantic drifts get printed as `rite migrate: <warn-code>: …` lines so they're grep-friendly in CI. The five warning classes mirror the user-visible breaks documented in Phase 4 of the operating manual:

OVERRIDE-VAR    task-scope vars: key shadowed by an entrypoint vars: key
                — under SPEC tier 7 the task value is now a default only.
OVERRIDE-ENV    same, for env: blocks.
DOTENV-ENTRY    task-level dotenv file whose keys collide with any
                entrypoint-level env source (explicit env:, dotenv:,
                or both) — entrypoint now wins.
SECRET-VAR      var name pattern-matches a secret (TOKEN/KEY/SECRET/
                PASSWORD/…) and lacks `export: false` — rite auto-exports
                `vars:` now, so this would leak to every cmd shell.
TEMPLATE-KEPT   a Go-template expression (`{{if}}`, `{{range}}`, sprig
                helper, etc.) that has no equivalent ${VAR} form was
                left verbatim — review manually.
SELFREF-CMD     a cmd shelled out to the `task` binary (e.g. `task lint`,
                `cd sub && task build`, `$(task --version)`); the head of
                each affected CallExpr is rewritten to `rite` so the
                migrated Ritefile drives itself instead of go-task.

The yaml-language-server `$schema=` directive pointing at taskfile.dev is rewritten to rite's hosted schema in place; the previous SCHEMA-URL warning class is gone — migrate fixes the pointer instead of complaining about it.

dstPath is the entrypoint's destination — returned even in dry-run mode so callers can echo it. Included-file destinations are not surfaced through the return value; they appear as `would write …` / `wrote …` lines in warn.

Implementation is two-phase: Phase 1 walks the include tree and builds a map from absolute source path to absolute destination path, choosing a unique destination per source. Phase 2 emits each file using that map to rewrite include targets in one coordinated pass. A prior single-pass version (pre-#76) picked `<dir>/Ritefile.yml` for every walked source, which meant N sibling includes all wrote to the same destination path (silent clobber) and the root's `includes:` block kept pointing at the original `.yml` filenames (no rewrite possible without per-source identity).

func RewriteShellCmdForTest added in v1.0.6

func RewriteShellCmdForTest(cmd string) (string, bool, bool)

RewriteShellCmdForTest exports rewriteShellCmd so unit tests in migrate_test.go can drive the rewriter directly without spinning up a full migrate cycle. Returns the rewritten cmd plus the same parseOK / changed flags rewriteShellCmd uses internally.

func RitefilePathForTest

func RitefilePathForTest(srcPath string) string

RitefilePathForTest exports ritefilePath under a test-only name so migrate_test.go can table-test filename mapping without promoting the helper to the public API.

func ShouldIgnore

func ShouldIgnore(path string) bool

Types

type Call

type Call struct {
	Task     string
	Vars     *ast.Vars
	Silent   bool
	Indirect bool // True if the task was called by another task
}

Call is the parameters to a task call

type Compiler

type Compiler struct {
	Dir            string
	Entrypoint     string
	UserWorkingDir string

	RitefileEnv  *ast.Vars
	RitefileVars *ast.Vars

	Logger *logger.Logger
}

func (*Compiler) FastGetVariables

func (c *Compiler) FastGetVariables(t *ast.Task, call *Call) (*ast.Vars, error)

func (*Compiler) GetRitefileVariables

func (c *Compiler) GetRitefileVariables() (*ast.Vars, error)

func (*Compiler) GetVariables

func (c *Compiler) GetVariables(t *ast.Task, call *Call) (*ast.Vars, error)

func (*Compiler) HandleDynamicVar

func (c *Compiler) HandleDynamicVar(v ast.Var, dir string, e []string, cache map[string]string) (string, error)

HandleDynamicVar resolves a `sh:` variable. The optional cache argument is the per-resolution dedupe map: within one getVariables / compiledTask invocation, an identical `sh:` string resolves once. Across invocations (different tasks, different environments) each call evaluates independently, which is what SPEC §Dynamic Variables mandates — the upstream muDynamicCache keyed globally by command string caused cross-task pollution. Pass nil to disable caching entirely.

type Executor

type Executor struct {
	// Flags
	Dir          string
	Entrypoint   string
	TempDir      TempDir
	Force        bool
	ForceAll     bool
	Watch        bool
	Verbose      bool
	Silent       bool
	DisableFuzzy bool
	AssumeYes    bool
	AssumeTerm   bool // Used for testing
	Interactive  bool
	Dry          bool
	Summary      bool
	Parallel     bool
	Color        bool
	Concurrency  int
	Interval     time.Duration
	Failfast     bool

	// Timestamps carries the CLI / env-var choice for the `--timestamps`
	// flag. Nil means "no CLI-level override"; the effective value for
	// each task is resolved at run time (CLI > task > top-level) via
	// resolveTimestamps().
	Timestamps *ast.Timestamps

	// I/O
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer

	// Internal
	Ritefile           *ast.Ritefile
	Logger             *logger.Logger
	Compiler           *Compiler
	Output             output.Output
	OutputStyle        ast.Output
	TaskSorter         sort.Sorter
	UserWorkingDir     string
	EnableVersionCheck bool
	// contains filtered or unexported fields
}

An Executor is used for processing Ritefile(s) and executing the task(s) within them.

func NewExecutor

func NewExecutor(opts ...ExecutorOption) *Executor

NewExecutor creates a new Executor and applies the given functional options to it.

func (*Executor) CompiledTask

func (e *Executor) CompiledTask(call *Call) (*ast.Task, error)

CompiledTask returns a copy of a task, but replacing variables in almost all properties using the Go template package.

func (*Executor) CompiledTaskForTaskList

func (e *Executor) CompiledTaskForTaskList(call *Call) (*ast.Task, error)

func (*Executor) FastCompiledTask

func (e *Executor) FastCompiledTask(call *Call) (*ast.Task, error)

FastCompiledTask is like CompiledTask, but it skippes dynamic variables.

func (*Executor) FindMatchingTasks

func (e *Executor) FindMatchingTasks(call *Call) ([]*MatchingTask, error)

FindMatchingTasks returns a list of tasks that match the given call. A task matches a call if its name is equal to the call's task name, or one of aliases, or if it matches a wildcard pattern. The function returns a list of MatchingTask structs, each containing a task and a list of wildcards that were matched. If multiple tasks match due to aliases, a TaskNameConflictError is returned.

func (*Executor) GetHash

func (e *Executor) GetHash(t *ast.Task) (string, error)

func (*Executor) GetTask

func (e *Executor) GetTask(call *Call) (*ast.Task, error)

GetTask will return the task with the name matching the given call from the taskfile. If no task is found, it will search for tasks with a matching alias. If multiple tasks contain the same alias or no matches are found an error is returned.

func (*Executor) GetTaskList

func (e *Executor) GetTaskList(filters ...FilterFunc) ([]*ast.Task, error)

func (*Executor) InterceptInterruptSignals

func (e *Executor) InterceptInterruptSignals(ctx context.Context) (context.Context, context.CancelFunc)

InterceptInterruptSignals installs a handler for SIGINT, SIGTERM, and SIGHUP and returns a child context that cancels on the first signal, plus a stop function that tears the handler down.

On the first signal the returned context is cancelled, which propagates through errgroup.WithContext and the mvdan.cc/sh interpreter inside execext.RunCommand so running subprocesses receive cooperative shutdown instead of being orphaned. Subsequent signals re-log; the third signal escalates to `os.Exit(1)` as a safety net in case a task hangs during cleanup.

Without this wiring, `signal.Notify` would hijack the default terminate behavior but never cancel anything — a programmatic `kill -TERM <pid>` (which, unlike interactive Ctrl-C, does not fan out to the process group) would leave child processes running after rite exited.

Callers should `defer stop()` to unregister the handler cleanly; stop also cancels the returned context.

func (*Executor) ListTaskNames

func (e *Executor) ListTaskNames(allTasks bool) error

ListTaskNames prints only the task names in a Ritefile. Only tasks with a non-empty description are printed if allTasks is false. Otherwise, all task names are printed.

func (*Executor) ListTasks

func (e *Executor) ListTasks(o ListOptions) (bool, error)

ListTasks prints a list of tasks. Tasks that match the given filters will be excluded from the list. The function returns a boolean indicating whether tasks were found and an error if one was encountered while preparing the output.

func (*Executor) Options

func (e *Executor) Options(opts ...ExecutorOption)

Options loops through the given ExecutorOption functions and applies them to the Executor.

func (*Executor) Run

func (e *Executor) Run(ctx context.Context, calls ...*Call) error

Run runs Task

func (*Executor) RunTask

func (e *Executor) RunTask(ctx context.Context, call *Call) error

RunTask runs a task by its name

func (*Executor) Setup

func (e *Executor) Setup() error

func (*Executor) Status

func (e *Executor) Status(ctx context.Context, calls ...*Call) error

Status returns an error if any the of given tasks is not up-to-date

func (*Executor) ToEditorOutput

func (e *Executor) ToEditorOutput(tasks []*ast.Task, noStatus bool, nested bool) (*editors.Namespace, error)

func (*Executor) Validate added in v1.0.2

func (e *Executor) Validate() error

Validate runs the parse + schema + version checks on the configured Ritefile without executing any tasks, evaluating any `sh:` dynamic vars, or reading dotenv files. It's the machinery behind `rite --validate` and is intended for editor extensions, pre-commit hooks, and CI lint stages.

The check chain is a strict subset of Setup():

  1. Discover the root Ritefile (respecting Entrypoint / Dir).
  2. Parse YAML, merge `includes:` (cycle detection happens here).
  3. Version check against the supported schema range.

On success, e.Ritefile is populated — callers can layer additional semantic checks on top. On failure, returns the same typed errors Setup() would, so exit codes route through the existing dispatcher (CodeRitefileDecode=102, CodeRitefileInvalid=104, CodeRitefileCycle=105, CodeRitefileVersionCheckError=103, CodeRitefileNotFound=100).

type ExecutorOption

type ExecutorOption interface {
	ApplyToExecutor(*Executor)
}

An ExecutorOption is any type that can apply a configuration to an Executor.

func WithAssumeTerm

func WithAssumeTerm(assumeTerm bool) ExecutorOption

WithAssumeTerm is used for testing purposes to simulate a terminal.

func WithAssumeYes

func WithAssumeYes(assumeYes bool) ExecutorOption

WithAssumeYes tells the Executor to assume "yes" for all prompts.

func WithColor

func WithColor(color bool) ExecutorOption

WithColor tells the Executor whether or not to output using colorized strings.

func WithConcurrency

func WithConcurrency(concurrency int) ExecutorOption

WithConcurrency sets the maximum number of tasks that the Executor can run in parallel.

func WithDir

func WithDir(dir string) ExecutorOption

WithDir sets the working directory of the Executor. By default, the directory is set to the user's current working directory.

func WithDisableFuzzy

func WithDisableFuzzy(disableFuzzy bool) ExecutorOption

WithDisableFuzzy tells the Executor to disable fuzzy matching for task names.

func WithDry

func WithDry(dry bool) ExecutorOption

WithDry tells the Executor to output the commands that would be run without actually running them.

func WithEntrypoint

func WithEntrypoint(entrypoint string) ExecutorOption

WithEntrypoint sets the entrypoint (main Ritefile) of the Executor. By default, Task will search for one of the default Taskfiles in the given directory.

func WithFailfast

func WithFailfast(failfast bool) ExecutorOption

WithFailfast tells the Executor whether or not to check the version of

func WithForce

func WithForce(force bool) ExecutorOption

WithForce ensures that the Executor always runs a task, even when fingerprinting or prompts would normally stop it.

func WithForceAll

func WithForceAll(forceAll bool) ExecutorOption

WithForceAll ensures that the Executor always runs all tasks (including subtasks), even when fingerprinting or prompts would normally stop them.

func WithIO

func WithIO(rw io.ReadWriter) ExecutorOption

WithIO sets the Executor's standard input, output, and error to the same io.ReadWriter.

func WithInteractive

func WithInteractive(interactive bool) ExecutorOption

WithInteractive tells the Executor to prompt for missing required variables.

func WithInterval

func WithInterval(interval time.Duration) ExecutorOption

WithInterval sets the interval at which the Executor will wait for duplicated events before running a task.

func WithOutputStyle

func WithOutputStyle(outputStyle ast.Output) ExecutorOption

WithOutputStyle sets the output style of the Executor. By default, the output style is set to the style defined in the Ritefile.

func WithParallel

func WithParallel(parallel bool) ExecutorOption

WithParallel tells the Executor to run tasks given in the same call in parallel.

func WithSilent

func WithSilent(silent bool) ExecutorOption

WithSilent tells the Executor to suppress all output except for the output of the tasks that are run.

func WithStderr

func WithStderr(stderr io.Writer) ExecutorOption

WithStderr sets the Executor's standard error io.Writer.

func WithStdin

func WithStdin(stdin io.Reader) ExecutorOption

WithStdin sets the Executor's standard input io.Reader.

func WithStdout

func WithStdout(stdout io.Writer) ExecutorOption

WithStdout sets the Executor's standard output io.Writer.

func WithSummary

func WithSummary(summary bool) ExecutorOption

WithSummary tells the Executor to output a summary of the given tasks instead of running them.

func WithTaskSorter

func WithTaskSorter(sorter sort.Sorter) ExecutorOption

WithTaskSorter sets the sorter that the Executor will use to sort tasks. By default, the sorter is set to sort tasks alphabetically, but with tasks with no namespace (in the root Ritefile) first.

func WithTempDir

func WithTempDir(tempDir TempDir) ExecutorOption

WithTempDir sets the temporary directory that will be used by Executor for storing temporary files like checksums and cached remote files. By default, the temporary directory is set to the user's temporary directory.

func WithTimestamps added in v1.0.4

func WithTimestamps(ts *ast.Timestamps) ExecutorOption

WithTimestamps carries the CLI / env-var value for the `--timestamps` flag. A nil value means "no CLI-level override"; a non-nil tri-state overrides both the task-level and top-level `timestamps:` settings for every task in this run.

func WithVerbose

func WithVerbose(verbose bool) ExecutorOption

WithVerbose tells the Executor to output more information about the tasks that are run.

func WithVersionCheck

func WithVersionCheck(enableVersionCheck bool) ExecutorOption

WithVersionCheck tells the Executor whether or not to check the version of

func WithWatch

func WithWatch(watch bool) ExecutorOption

WithWatch tells the Executor to keep running in the background and watch for changes to the fingerprint of the tasks that are run. When changes are detected, a new task run is triggered.

type FilterFunc

type FilterFunc func(task *ast.Task) bool

type ListOptions

type ListOptions struct {
	ListOnlyTasksWithDescriptions bool
	ListAllTasks                  bool
	FormatTaskListAsJSON          bool
	NoStatus                      bool
	Nested                        bool
}

ListOptions collects list-related options

func NewListOptions

func NewListOptions(list, listAll, listAsJson, noStatus, nested bool) ListOptions

NewListOptions creates a new ListOptions instance

func (ListOptions) Filters

func (o ListOptions) Filters() []FilterFunc

Filters returns the slice of FilterFunc which filters a list of ast.Task according to the given ListOptions

func (ListOptions) ShouldListTasks

func (o ListOptions) ShouldListTasks() bool

ShouldListTasks returns true if one of the options to list tasks has been set to true

type MatchingTask

type MatchingTask struct {
	Task      *ast.Task
	Wildcards []string
}

MatchingTask represents a task that matches a given call. It includes the task itself and a list of wildcards that were matched.

type MigrateOption

type MigrateOption func(*migrateOptions)

MigrateOption configures Migrate. Functional-options keep the two-arg signature callers rely on while leaving room for future knobs.

func WithDryRun

func WithDryRun(enabled bool) MigrateOption

WithDryRun returns a MigrateOption that, when true, parses and emits warnings but writes no files. Intended for `rite --migrate --dry-run`.

func WithKeepGoTemplates added in v1.0.1

func WithKeepGoTemplates(enabled bool) MigrateOption

WithKeepGoTemplates returns a MigrateOption that, when true, suppresses the Go-template → `${VAR}` modernization pass. Intended for `rite migrate --keep-go-templates` when a user deliberately wants the old template surface preserved verbatim.

type TempDir

type TempDir struct {
	Fingerprint string
}

Jump to

Keyboard shortcuts

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