Documentation
¶
Index ¶
- Constants
- func ArchToAMD64(arch string) string
- func ArchToX64(arch string) string
- func ArchToX8664(arch string) string
- func BinaryName(name string) string
- func CWD(ctx context.Context) string
- func Command(ctx context.Context, name string, args ...string) *exec.Cmd
- func ConfigPath(ctx context.Context, toolName string, cfg ToolConfig) (string, error)
- func CopyFile(src, dst string) error
- func CreateSymlink(binaryPath string) (string, error)
- func DefaultArchiveFormat() string
- func DefaultArchiveFormatFor(os string) string
- func DetectByExtension(extensions ...string) []string
- func DetectByFile(filenames ...string) []string
- func Exec(ctx context.Context, name string, args ...string) error
- func ExecIn(ctx context.Context, dir, name string, args ...string) error
- func ExtractTar(src, destDir string, opts ...ExtractOpt) error
- func ExtractTarGz(src, destDir string, opts ...ExtractOpt) error
- func ExtractZip(src, destDir string, opts ...ExtractOpt) error
- func FromBinDir(elem ...string) string
- func FromGitRoot(elem ...string) string
- func FromPocketDir(elem ...string) string
- func FromToolsDir(elem ...string) string
- func GitRoot() string
- func GoVersionFromDir(dir string) (string, error)
- func HostArch() string
- func HostOS() string
- func OSToTitle(os string) string
- func OSToUpper(os string) string
- func Options[T any](ctx context.Context) T
- func Path(ctx context.Context) string
- func PrependPath(env []string, dir string) []string
- func Printf(ctx context.Context, format string, args ...any)
- func Println(ctx context.Context, args ...any)
- func RegisterGenerateAll(fn GenerateAllFunc)
- func RunConfig(cfg Config)
- func TestContext(out *Output) context.Context
- func Verbose(ctx context.Context) bool
- type Config
- type ConfigPlan
- type DownloadOpt
- type Engine
- type ExecutionPlan
- func (p *ExecutionPlan) ModuleDirectories() []string
- func (p *ExecutionPlan) PathMappings() map[string]*PathFilter
- func (p *ExecutionPlan) Print(ctx context.Context, showHidden, showDedup bool)
- func (p *ExecutionPlan) Steps() []*PlanStep
- func (p *ExecutionPlan) TaskDefs() []*TaskDef
- func (p *ExecutionPlan) Tasks() []TaskInfo
- type ExtractOpt
- type GenerateAllFunc
- type IntrospectPlan
- type Output
- type PathFilter
- type PathOpt
- type PlanStep
- type Runnable
- func Do(fn func(context.Context) error) Runnable
- func Download(url string, opts ...DownloadOpt) Runnable
- func FromLocal(path string, opts ...DownloadOpt) Runnable
- func InstallGo(pkg, version string) Runnable
- func Parallel(items ...any) Runnable
- func Run(name string, args ...string) Runnable
- func Serial(items ...any) Runnable
- type ShimConfig
- type TaskDef
- type TaskInfo
- type TaskOpt
- type ToolConfig
Constants ¶
const ( // DirName is the name of the pocket directory. DirName = ".pocket" // ToolsDirName is the name of the tools subdirectory. ToolsDirName = "tools" // BinDirName is the name of the bin subdirectory (for symlinks). BinDirName = "bin" )
const ( Darwin = "darwin" Linux = "linux" Windows = "windows" )
OS name constants matching runtime.GOOS values.
const ( // Go-style architecture names (matching runtime.GOARCH). AMD64 = "amd64" ARM64 = "arm64" // Alternative naming conventions used by various tools. X8664 = "x86_64" AARCH64 = "aarch64" X64 = "x64" )
Architecture constants in various naming conventions.
const WaitDelay = 5 * time.Second
WaitDelay is the grace period given to child processes to handle termination signals before being force-killed.
Variables ¶
This section is empty.
Functions ¶
func ArchToAMD64 ¶
ArchToAMD64 converts x86_64/aarch64 naming to Go-style architecture names.
x86_64 -> amd64 aarch64 -> arm64
Other values are returned unchanged.
func ArchToX64 ¶
ArchToX64 converts Go-style architecture names to x64/arm64 naming.
amd64 -> x64 arm64 -> arm64 (unchanged)
Other values are returned unchanged.
func ArchToX8664 ¶
ArchToX8664 converts Go-style architecture names to x86_64/aarch64 naming.
amd64 -> x86_64 arm64 -> aarch64
Other values are returned unchanged.
func BinaryName ¶
BinaryName returns the binary name with the correct extension for the current OS. On Windows, it appends ".exe" to the name.
func Command ¶
Command creates an exec.Cmd with PATH prepended with .pocket/bin, stdout/stderr connected to os.Stdout/os.Stderr, and graceful shutdown configured.
When the context is cancelled, the command receives SIGINT first (allowing graceful shutdown), then SIGKILL after WaitDelay.
If stdout is a TTY, color-forcing environment variables are added so that tools output ANSI colors even when their output is buffered (for parallel execution).
Note: For commands run from task actions, prefer TaskContext.Command() which automatically wires output to the task's output writers for proper parallel buffering.
To redirect output (e.g., for buffering in parallel execution), set cmd.Stdout and cmd.Stderr after creating the command.
func ConfigPath ¶
ConfigPath returns the path to a tool's config file.
For each path in UserFiles:
- Absolute paths are checked as-is (use FromGitRoot() for repo-root configs)
- Relative paths are checked in the task's current directory (from Path(ctx))
If no user config is found, writes DefaultData to .pocket/tools/<name>/<DefaultFile>. Returns empty string and no error if cfg is empty.
Example:
var golangciConfig = pocket.ToolConfig{
UserFiles: []string{".golangci.yml", ".golangci.yaml"},
DefaultFile: "golangci.yml",
DefaultData: defaultConfig,
}
func lint(ctx context.Context) error {
configPath, err := pocket.ConfigPath(ctx, "golangci-lint", golangciConfig)
if err != nil {
return err
}
return pocket.Exec(ctx, "golangci-lint", "run", "-c", configPath)
}
func CreateSymlink ¶
CreateSymlink creates a symlink in .pocket/bin/ pointing to the given binary. On Windows, it copies the file instead since symlinks require admin privileges. Returns the path to the symlink (or copy on Windows).
func DefaultArchiveFormat ¶
func DefaultArchiveFormat() string
DefaultArchiveFormat returns the typical archive format for the current OS. Returns "zip" on Windows, "tar.gz" on other platforms.
func DefaultArchiveFormatFor ¶
DefaultArchiveFormatFor returns the typical archive format for the given OS. Returns "zip" for Windows, "tar.gz" for other platforms.
func DetectByExtension ¶
DetectByExtension finds directories containing files with any of the specified extensions. Returns paths relative to git root, sorted alphabetically. Excludes .pocket directory and hidden directories. Each directory is returned only once, even if multiple matching files are found.
func DetectByFile ¶
DetectByFile finds directories containing any of the specified files (e.g., "go.mod"). Returns paths relative to git root, sorted alphabetically. Excludes .pocket directory and hidden directories. Each directory is returned only once, even if multiple marker files are found.
func Exec ¶
Exec runs an external command with output directed to the current context. The command runs in the current path directory.
func ExtractTar ¶
func ExtractTar(src, destDir string, opts ...ExtractOpt) error
ExtractTar extracts a .tar archive to destDir. If no options are provided, all files are extracted preserving directory structure. Use WithRenameFile or WithExtractFile to limit extraction to specific files.
func ExtractTarGz ¶
func ExtractTarGz(src, destDir string, opts ...ExtractOpt) error
ExtractTarGz extracts a .tar.gz archive to destDir. If no options are provided, all files are extracted preserving directory structure. Use WithRenameFile or WithExtractFile to limit extraction to specific files.
func ExtractZip ¶
func ExtractZip(src, destDir string, opts ...ExtractOpt) error
ExtractZip extracts a .zip archive to destDir. If no options are provided, all files are extracted preserving directory structure. Use WithRenameFile or WithExtractFile to limit extraction to specific files.
func FromBinDir ¶
FromBinDir returns a path relative to the .pocket/bin directory. If no elements are provided, returns the bin directory itself.
func FromGitRoot ¶
FromGitRoot returns a path relative to the git root.
func FromPocketDir ¶
FromPocketDir returns a path relative to the .pocket directory.
func FromToolsDir ¶
FromToolsDir returns a path relative to the .pocket/tools directory.
func GoVersionFromDir ¶
GoVersionFromDir reads the Go version from go.mod in the given directory. Returns the version string (e.g., "1.21") or an error if the file cannot be read or doesn't contain a go directive.
func OSToTitle ¶
OSToTitle converts an OS name to title case.
darwin -> Darwin linux -> Linux windows -> Windows
func Options ¶
Options retrieves typed options from the context. It handles both struct and pointer types for T, always looking up the base struct type.
func PrependPath ¶
PrependPath prepends a directory to the PATH in the given environment.
func RegisterGenerateAll ¶
func RegisterGenerateAll(fn GenerateAllFunc)
RegisterGenerateAll registers the scaffold.GenerateAll function. This is called by internal/scaffold.init() to avoid import cycles.
func RunConfig ¶
func RunConfig(cfg Config)
RunConfig is the main entry point for running a pocket configuration. It parses CLI flags, discovers functions, and runs the appropriate ones.
Example usage in .pocket/main.go:
func main() {
pocket.RunConfig(Config)
}
func TestContext ¶
TestContext creates a context suitable for testing.
Types ¶
type Config ¶
type Config struct {
// AutoRun defines the execution tree for ./pok (no arguments).
// Use Serial() and Parallel() to control execution order.
// All tasks in AutoRun execute when running ./pok without arguments.
//
// Example:
//
// AutoRun: pocket.Serial(
// pocket.RunIn(golang.Tasks(), pocket.Detect(golang.Detect())),
// pocket.RunIn(python.Tasks(), pocket.Detect(python.Detect())),
// ),
AutoRun Runnable
// ManualRun registers additional tasks that only run when explicitly
// invoked with ./pok <taskname>. These tasks appear in ./pok -h under
// "Manual Tasks" and support the same wrappers as AutoRun (RunIn, etc.).
//
// Example:
//
// ManualRun: []pocket.Runnable{
// deployTask,
// pocket.RunIn(benchmarkTask, pocket.Include("services/api")),
// },
ManualRun []Runnable
// Shim controls shim script generation.
// By default, only Posix (./pok) is generated with name "pok".
Shim *ShimConfig
// SkipGenerate disables running "generate" at the start of the "all" task.
// By default, "all" regenerates files before running tasks.
// Set to true to skip regeneration.
SkipGenerate bool
// SkipGitDiff disables the git diff check at the end of the "all" task.
// By default, "all" fails if there are uncommitted changes after running all tasks.
// Set to true to disable this check.
SkipGitDiff bool
}
Config defines the configuration for a project using pocket.
func (Config) WithDefaults ¶
WithDefaults returns a copy of the config with default values applied.
type ConfigPlan ¶
type ConfigPlan struct {
// Tasks collected from AutoRun and ManualRun trees
Tasks []*TaskDef
// AutoRunNames tracks which tasks are from AutoRun (vs ManualRun)
AutoRunNames map[string]bool
// PathMappings maps task names to their PathFilter for visibility
PathMappings map[string]*PathFilter
// AllTask is the hidden task that runs the full AutoRun tree
AllTask *TaskDef
// BuiltinTasks are always-available tasks (plan, clean, generate, etc.)
BuiltinTasks []*TaskDef
// ModuleDirectories are all directories where shims should be generated
ModuleDirectories []string
// Config is the original configuration (for builtin tasks that need it)
Config *Config
}
ConfigPlan holds all collected data from walking a Config's task trees. This is the result of the planning phase, before CLI execution.
func BuildConfigPlan ¶
func BuildConfigPlan(cfg Config) *ConfigPlan
BuildConfigPlan walks the Config's task trees and collects all data needed for CLI execution. This is the single point where tree walking happens.
func GetConfigPlan ¶
func GetConfigPlan(ctx context.Context) *ConfigPlan
GetConfigPlan returns the ConfigPlan from context. Returns nil if not set (e.g., in collect mode or testing).
func (*ConfigPlan) Validate ¶
func (p *ConfigPlan) Validate() error
Validate checks the ConfigPlan for errors (e.g., duplicate task names).
type DownloadOpt ¶
type DownloadOpt func(*downloadConfig)
DownloadOpt configures download and extraction behavior.
func WithDestDir ¶
func WithDestDir(dir string) DownloadOpt
WithDestDir sets the destination directory for extraction.
func WithExtract ¶
func WithExtract(opt ExtractOpt) DownloadOpt
WithExtract adds extraction options from the extract package. Use this to pass WithRenameFile, WithExtractFile, or WithFlatten options.
Example:
Download(ctx, url,
WithExtract(WithRenameFile("tool-1.0.0/tool", "tool")),
WithExtract(WithExtractFile("LICENSE")),
)
func WithFormat ¶
func WithFormat(format string) DownloadOpt
WithFormat sets the archive format. Supported formats: "tar.gz", "tar", "zip", or "" for raw copy.
func WithHTTPHeader ¶
func WithHTTPHeader(key, value string) DownloadOpt
WithHTTPHeader adds an HTTP header to the download request. Multiple calls accumulate headers.
func WithSkipIfExists ¶
func WithSkipIfExists(path string) DownloadOpt
WithSkipIfExists skips the download if the specified file exists.
func WithSymlink ¶
func WithSymlink() DownloadOpt
WithSymlink creates a symlink in .pocket/bin/ after extraction. The symlink points to the first extracted file.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine orchestrates plan collection and execution.
type ExecutionPlan ¶
type ExecutionPlan struct {
// contains filtered or unexported fields
}
ExecutionPlan holds the complete plan collected during modeCollect.
func (*ExecutionPlan) ModuleDirectories ¶
func (p *ExecutionPlan) ModuleDirectories() []string
ModuleDirectories returns all unique directories where tasks should run. This is derived from pathMappings and always includes "." (root). Used for shim generation.
func (*ExecutionPlan) PathMappings ¶
func (p *ExecutionPlan) PathMappings() map[string]*PathFilter
PathMappings returns the collected path mappings.
func (*ExecutionPlan) Print ¶
func (p *ExecutionPlan) Print(ctx context.Context, showHidden, showDedup bool)
Print outputs the execution plan tree.
func (*ExecutionPlan) Steps ¶
func (p *ExecutionPlan) Steps() []*PlanStep
Steps returns the top-level steps in the plan.
func (*ExecutionPlan) TaskDefs ¶
func (p *ExecutionPlan) TaskDefs() []*TaskDef
TaskDefs returns the collected TaskDefs (visible, non-hidden, deduplicated by name). This replaces the need to call funcs() separately.
func (*ExecutionPlan) Tasks ¶
func (p *ExecutionPlan) Tasks() []TaskInfo
Tasks flattens the execution plan into a list of TaskInfo. This extracts all func steps from the tree, combining with path information collected during the walk. Tasks without path mappings get ["."].
type ExtractOpt ¶
type ExtractOpt func(*extractConfig)
ExtractOpt configures extraction behavior.
func WithExtractFile ¶
func WithExtractFile(name string) ExtractOpt
WithExtractFile extracts only the specified file (by base name). The file is extracted with its original name. Multiple calls accumulate files to extract.
func WithFlatten ¶
func WithFlatten() ExtractOpt
WithFlatten flattens directory structure, extracting all files to destDir root. File names are preserved but directory paths are discarded.
func WithRenameFile ¶
func WithRenameFile(srcPath, destName string) ExtractOpt
WithRenameFile extracts a specific file and optionally renames it. srcPath can be a full path within the archive or just the base name. If destName is empty, the original base name is preserved. Multiple calls accumulate files to extract.
Example:
ExtractTarGz(src, dest,
WithRenameFile("golangci-lint-1.55.0-linux-amd64/golangci-lint", "golangci-lint"),
)
type GenerateAllFunc ¶
type GenerateAllFunc func(plan *ConfigPlan) ([]string, error)
GenerateAllFunc is the function signature for scaffold.GenerateAll. This is set by internal/scaffold at init time to avoid import cycles. Accepts ConfigPlan to reuse cached ModuleDirectories (avoids re-walking trees).
type IntrospectPlan ¶
type IntrospectPlan struct {
AutoRun []*PlanStep `json:"autoRun,omitempty"`
ManualRun []TaskInfo `json:"manualRun,omitempty"`
}
IntrospectPlan represents the full introspection structure. AutoRun shows the compositional tree structure (serial/parallel). ManualRun shows tasks as a flat list.
func BuildIntrospectPlan ¶
func BuildIntrospectPlan(cfg Config) (IntrospectPlan, error)
BuildIntrospectPlan builds the introspection plan structure from config. This captures the full tree structure for AutoRun and flat list for ManualRun. The caller is responsible for JSON marshaling.
type Output ¶
Output holds stdout and stderr writers for task output. This is passed through the Runnable chain to direct output appropriately.
func StdOutput ¶
func StdOutput() *Output
StdOutput returns an Output that writes to os.Stdout and os.Stderr.
type PathFilter ¶
type PathFilter struct {
// contains filtered or unexported fields
}
PathFilter wraps a Runnable with path filtering. It implements Runnable, so it can be used anywhere a Runnable is expected.
func RunIn ¶
func RunIn(r Runnable, opts ...PathOpt) *PathFilter
RunIn wraps a Runnable with path filtering. Use options to control where the Runnable executes.
Example:
pocket.RunIn(golang.Tasks(),
pocket.Detect(golang.Detect()),
pocket.Include("services/.*"),
pocket.Exclude("vendor"),
)
func (*PathFilter) Resolve ¶
func (p *PathFilter) Resolve() []string
Resolve returns all directories where this Runnable should run. It combines detection results with explicit includes, then filters by excludes. Results are sorted and deduplicated.
func (*PathFilter) ResolveFor ¶
func (p *PathFilter) ResolveFor(cwd string) []string
ResolveFor returns the resolved paths filtered for the given working directory. If cwd is ".", returns all resolved paths. Otherwise, returns only paths that match cwd.
func (*PathFilter) RunsIn ¶
func (p *PathFilter) RunsIn(dir string) bool
RunsIn returns true if this Runnable should run in the given directory. The directory should be relative to git root.
type PathOpt ¶
type PathOpt func(*PathFilter)
PathOpt configures path filtering behavior for RunIn.
func Detect ¶
Detect sets a detection function that returns directories where the Runnable should execute. The function should return directories relative to git root.
func Exclude ¶
Exclude adds patterns (regex) for directories to exclude. Directories matching any pattern are excluded from results.
func Include ¶
Include adds patterns (regex) for directories to include. Directories matching any pattern are included.
func Skip ¶
Skip configures a task to be skipped in specific paths. If no paths are specified, the task is skipped everywhere within this filter. Paths support regex patterns matched against the current execution path.
To make skipped tasks available for manual execution, add them to ManualRun with a different name using WithName():
AutoRun: pocket.RunIn(golang.Tasks(),
pocket.Detect(golang.Detect()),
pocket.Skip(golang.Test, "services/api", "services/worker"),
),
ManualRun: []pocket.Runnable{
pocket.RunIn(golang.Test.WithName("integration-test"),
pocket.Include("services/api", "services/worker"),
),
}
type PlanStep ¶
type PlanStep struct {
Type string `json:"type"` // "serial", "parallel", "func"
Name string `json:"name,omitempty"` // Function name
Usage string `json:"usage,omitempty"` // Function usage/description
Hidden bool `json:"hidden,omitempty"` // Whether this is a hidden function
Deduped bool `json:"deduped,omitempty"` // Would be skipped due to deduplication
Children []*PlanStep `json:"children,omitempty"` // Nested steps (for serial/parallel groups)
}
PlanStep represents a single step in the execution plan.
type Runnable ¶
type Runnable interface {
// contains filtered or unexported methods
}
Runnable is the interface for anything that can be executed. It uses unexported methods to prevent external implementation, ensuring only pocket types (TaskDef, serial, parallel, PathFilter) can satisfy it.
Users create Runnables via:
- pocket.Task() for individual functions
- pocket.Serial() for sequential execution
- pocket.Parallel() for concurrent execution
- pocket.RunIn() for path filtering
func Do ¶
Do creates a Runnable from a function. Use this for arbitrary Go code that doesn't fit the Run/RunWith model, such as file I/O, API calls, or conditional logic.
Example:
pocket.Do(func(ctx context.Context) error {
return os.WriteFile("output.txt", data, 0644)
})
func Download ¶
func Download(url string, opts ...DownloadOpt) Runnable
Download creates a Runnable that fetches a URL and optionally extracts it. Progress and status messages are written to the context's output.
Example:
var Install = pocket.Task("install:tool", "install tool",
pocket.Download(url,
pocket.WithDestDir(binDir),
pocket.WithFormat("tar.gz"),
pocket.WithExtract(pocket.WithRenameFile("tool-1.0.0/tool", "tool")),
pocket.WithSymlink(),
),
).Hidden()
func FromLocal ¶
func FromLocal(path string, opts ...DownloadOpt) Runnable
FromLocal creates a Runnable that processes a local file (extract/copy). Useful for processing pre-downloaded or bundled archives.
func InstallGo ¶
InstallGo creates a Runnable that installs a Go binary using 'go install'. The binary is installed to .pocket/tools/go/<pkg>/<version>/ and symlinked to .pocket/bin/.
Example:
var Install = pocket.Task("install:linter", "install linter",
pocket.InstallGo("github.com/golangci/golangci-lint/cmd/golangci-lint", version),
).Hidden()
func Parallel ¶
Parallel composes items to run concurrently.
Returns a Runnable that executes items in parallel. Use it to:
- Run independent tasks concurrently: Parallel(Lint, Test)
- Compose in Config: Parallel(task1, task2)
Items can be *TaskDef, Runnable, or func(context.Context) error.
Example:
var CI = pocket.Task("ci", "run CI", pocket.Parallel(
Lint,
Test,
))
func Run ¶
Run creates a Runnable that executes an external command. The command runs in the current path directory with .pocket/bin in PATH.
Example:
pocket.Run("go", "fmt", "./...")
pocket.Run("golangci-lint", "run", "--fix", "./...")
func Serial ¶
Serial composes items to run sequentially.
Returns a Runnable that executes items in order. Use it to:
- Define dependencies: Serial(Install, TaskImpl)
- Compose tasks in Config: Serial(Format, Lint, Test)
Items can be *TaskDef, Runnable, or func(context.Context) error.
Example:
var Lint = pocket.Task("lint", "run linter", pocket.Serial(
golangcilint.Install,
func(ctx context.Context) error {
return pocket.Exec(ctx, "golangci-lint", "run", "./...")
},
))
type ShimConfig ¶
type ShimConfig struct {
// Name is the base name of the generated shim scripts (without extension).
// Default: "pok"
Name string
// Posix generates a bash script (./pok).
// This is enabled by default if ShimConfig is nil.
Posix bool
// Windows generates a batch file (pok.cmd).
// The batch file requires Go to be installed and in PATH.
Windows bool
// PowerShell generates a PowerShell script (pok.ps1).
// The PowerShell script can auto-download Go if not found.
PowerShell bool
}
ShimConfig controls shim script generation.
type TaskDef ¶
type TaskDef struct {
// contains filtered or unexported fields
}
TaskDef represents a named function that can be executed. Create with pocket.Task() - this is the only way to create runnable functions.
The body can be:
- pocket.Run(name, args...) - static command
- pocket.Do(fn) - dynamic commands or arbitrary Go code
- pocket.Serial(...) or pocket.Parallel(...) - compositions
Example:
// Simple: static command
var Format = pocket.Task("go-format", "format Go code",
pocket.Run("go", "fmt", "./..."),
)
// Composed: install dependency then run
var Lint = pocket.Task("go-lint", "run linter", pocket.Serial(
InstallLinter,
pocket.Run("golangci-lint", "run", "./..."),
))
// Dynamic: args computed at runtime
var Test = pocket.Task("go-test", "run tests", testCmd())
func testCmd() pocket.Runnable {
return pocket.Do(func(ctx context.Context) error {
args := []string{"test"}
if pocket.Verbose(ctx) {
args = append(args, "-v")
}
return pocket.Exec(ctx, "go", append(args, "./...")...)
})
}
// Hidden: tool installers
var InstallLinter = pocket.Task("install:linter", "install linter",
pocket.InstallGo("github.com/org/linter", "v1.0.0"),
).Hidden()
func Clone ¶
Clone creates a copy of a task with modifications applied. This is useful for creating task variants at runtime, such as renaming a task to avoid duplicate names in ManualRun.
Example:
// Give a task a different name for ManualRun
pocket.Clone(golang.Test, pocket.Named("integration-test"))
// Clone with multiple modifications
pocket.Clone(myTask, pocket.Named("new-name"), pocket.AsHidden())
func Task ¶
Task creates a new named task. This is the primary way to create tasks that appear in the CLI.
The name is used for CLI commands (e.g., "go-format" becomes ./pok go-format). The usage is displayed in help output. The body can be:
- Runnable - from Run, Do, Serial, Parallel
- func(context.Context) error - legacy, wrapped automatically
Use options to configure the task:
var Lint = pocket.Task("lint", "run linter", lintCmd(),
pocket.Opts(LintOptions{}),
pocket.AsHidden(),
)
func WithOpts ¶
WithOpts creates a copy of a task with different options. This is useful for creating task variants at runtime, such as applying CLI-parsed options or package-level configuration.
Example:
// In a task package's Tasks() function:
lintTask := Lint
if cfg.lint != (LintOptions{}) {
lintTask = pocket.WithOpts(Lint, cfg.lint)
}
// In CLI option parsing:
taskWithOpts := pocket.WithOpts(task, parsedOpts)
type TaskInfo ¶
type TaskInfo struct {
Name string `json:"name"` // CLI command name
Usage string `json:"usage"` // Description/help text
Paths []string `json:"paths,omitempty"` // Directories this task runs in
Hidden bool `json:"hidden,omitempty"` // Whether task is hidden from help
}
TaskInfo represents a task for introspection. This is the public type used by the introspection API for CI/CD integration.
func CollectTasks ¶
CollectTasks extracts task information from a Runnable tree. This uses Engine.Plan() internally to collect tasks without executing them. Path mappings are collected during the same walk. Tasks without RunIn() wrappers get ["."] (root only).
type TaskOpt ¶
type TaskOpt func(*TaskDef)
TaskOpt configures a task created with Task().
func AsHidden ¶
func AsHidden() TaskOpt
AsHidden marks a task as hidden from CLI help. Hidden tasks can still be executed but don't appear in ./pok -h. Use this for internal tasks like tool installers.
Example:
var Install = pocket.Task("install:tool", "install tool",
pocket.InstallGo("github.com/org/tool", "v1.0.0"),
pocket.AsHidden(),
)
func AsSilent ¶
func AsSilent() TaskOpt
AsSilent suppresses the task header output (e.g., ":: task-name"). Use this for tasks that produce machine-readable output (JSON, etc.).
Example:
var Matrix = pocket.Task("gha-matrix", "output GHA matrix JSON",
matrixCmd(),
pocket.AsSilent(),
)
func Named ¶
Named sets a different CLI name for the task. Use this when the same task needs different names in different contexts.
Example:
pocket.Task("integration-test", "run integration tests", testImpl,
pocket.Named("integration-test"),
)
func Opts ¶
Opts attaches CLI options to a task. Options are accessible via pocket.Options[T](ctx) in the function.
Example:
type FormatOptions struct {
Config string `arg:"config" usage:"path to config file"`
}
var Format = pocket.Task("format", "format code", formatImpl,
pocket.Opts(FormatOptions{Config: ".golangci.yml"}),
)
type ToolConfig ¶
type ToolConfig struct {
// UserFiles are filenames to search for in the repo root.
// Checked in order; first match wins.
UserFiles []string
// DefaultFile is the filename for the bundled default config,
// written to .pocket/tools/<name>/ if no user config exists.
DefaultFile string
// DefaultData is the bundled default configuration content.
DefaultData []byte
}
ToolConfig describes how to find or create a tool's configuration file.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
pocket
command
|
|
|
internal
|
|
|
scaffold
Package scaffold provides generation of .pocket/ scaffold files.
|
Package scaffold provides generation of .pocket/ scaffold files. |
|
shim
Package shim provides generation of the ./pok wrapper scripts.
|
Package shim provides generation of the ./pok wrapper scripts. |
|
Package tasks provides the entry point for running pocket tasks.
|
Package tasks provides the entry point for running pocket tasks. |
|
github
Package github provides GitHub-related tasks.
|
Package github provides GitHub-related tasks. |
|
golang
Package golang provides Go development tasks.
|
Package golang provides Go development tasks. |
|
lua
Package lua provides Lua-related build tasks.
|
Package lua provides Lua-related build tasks. |
|
markdown
Package markdown provides Markdown formatting tasks.
|
Package markdown provides Markdown formatting tasks. |
|
python
Package python provides Python-related build tasks using ruff and mypy.
|
Package python provides Python-related build tasks using ruff and mypy. |
|
tools
|
|
|
bun
Package bun provides bun runtime integration.
|
Package bun provides bun runtime integration. |
|
golangcilint
Package golangcilint provides golangci-lint integration.
|
Package golangcilint provides golangci-lint integration. |
|
govulncheck
Package govulncheck provides govulncheck integration.
|
Package govulncheck provides govulncheck integration. |
|
mdformat
Package mdformat provides mdformat (Markdown formatter) tool integration.
|
Package mdformat provides mdformat (Markdown formatter) tool integration. |
|
nvim
Package nvim provides Neovim tool integration.
|
Package nvim provides Neovim tool integration. |
|
prettier
Package prettier provides prettier (code formatter) integration.
|
Package prettier provides prettier (code formatter) integration. |
|
stylua
Package stylua provides stylua tool integration.
|
Package stylua provides stylua tool integration. |
|
tsqueryls
Package tsqueryls provides ts_query_ls tool integration.
|
Package tsqueryls provides ts_query_ls tool integration. |
|
uv
Package uv provides uv (Python package manager) tool integration.
|
Package uv provides uv (Python package manager) tool integration. |