hooks

package
v1.220.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OnFailureWarn   = "warn"
	OnFailureFail   = "fail"
	OnFailureIgnore = "ignore"
)

On-failure modes for the command engine.

View Source
const (
	FormatMarkdown = "markdown"
)

Format constants understood by the engine for inline rendering.

Variables

This section is empty.

Functions

func ClearKinds

func ClearKinds()

ClearKinds removes all registered kinds. For testing only.

func ListKinds

func ListKinds() []string

ListKinds returns all registered kind names, sorted.

func RegisterKind

func RegisterKind(k *Kind) error

RegisterKind registers a hook kind. Kinds self-register from pkg/hooks/kinds/*/kind.go via init() — this is the only registration path (there is no YAML-defined kind registry; reuse uses stack imports).

func RunCIHooks added in v1.210.0

func RunCIHooks(opts *RunCIHooksOptions) error

RunCIHooks executes CI actions based on provider bindings. This is called automatically during command execution if CI is enabled.

Types

type Artifact

type Artifact struct {
	// Name is the filename inside the upload bundle (e.g. "breakdown.json").
	Name string
	// Body is the artifact content.
	Body []byte
	// Format is the optional generic-renderer hint ("markdown" or "").
	// For named kinds, Pro derives rendering from the kind name, so this
	// remains empty.
	Format string
	// Metadata is arbitrary tags attached to the artifact.
	Metadata map[string]string
}

Artifact is the opaque blob produced by a hook. Subsequent commits extend this with backend-routing metadata.

type Command

type Command interface {
	GetName() string
	RunE(hook *Hook, event HookEvent, cmd *cobra.Command, args []string) error
}

Command is the interface for all commands that can be run by hooks

type CommandEngine

type CommandEngine struct{}

CommandEngine runs a binary (resolved via PATH — set up by the toolchain or any other install mechanism) against the component being orchestrated. It exposes standard ATMOS_* env vars to the subprocess and captures structured output via ATMOS_OUTPUT_FILE.

Tool stdout/stderr stream straight through to the user's terminal so progress and warnings appear in real time (same UX as Terraform output). Structured output goes through the side-channel file, read by the kind's ResultHandler (if any) and packaged as an Artifact.

func (*CommandEngine) Run

func (e *CommandEngine) Run(ctx *ExecContext) (*Output, error)

Run satisfies Engine. It's an orchestrator — the actual work lives in named helpers (validateCtx / prepareSubprocess / runSubprocess / captureOutput / renderTerminal) so each step has a single responsibility and the orchestrator stays a flat linear pipeline.

type Engine

type Engine interface {
	// Run executes the hook with the given context.
	// Implementations that produce no structured output return (nil, err).
	Run(ctx *ExecContext) (*Output, error)
}

Engine runs a hook of a given kind. Different kinds may implement different engines: StoreEngine reads terraform outputs into a store; CommandEngine (added in a later commit) executes a binary and captures its structured output.

type ExecContext

type ExecContext struct {
	// Hook is the resolved hook (kind defaults applied; user overrides preserved).
	Hook *Hook
	// Kind is the registered kind handling this hook.
	Kind *Kind
	// Event is the lifecycle event triggering the hook.
	Event HookEvent
	// AtmosConfig is the global Atmos configuration.
	AtmosConfig *schema.AtmosConfiguration
	// Info carries component and stack information.
	Info *schema.ConfigAndStacksInfo
	// Cmd is the cobra command currently executing.
	Cmd *cobra.Command
	// Args are the command-line args passed to Cmd.
	Args []string

	// ToolchainPATH is the PATH fragment containing directories for any
	// dependencies.tools that were auto-installed for this component's
	// hooks. Populated by Hooks.preflight; consumed by CommandEngine
	// so the installed pinned versions take precedence over the operator's
	// PATH. Empty when the component declares no hook dependencies.
	ToolchainPATH string

	// OutputFile is the temp file path the tool wrote structured output to.
	// Populated by CommandEngine before calling ResultHandler.
	OutputFile string
	// OutputDir is the temp directory containing OutputFile. Exposed for
	// directory-output tools (e.g., KICS writes results.sarif into a dir).
	OutputDir string
	// ExitCode is the subprocess exit code (0 = success).
	ExitCode int
	// CommandError is the subprocess error, if any.
	CommandError error
}

ExecContext is everything an engine needs at run time. Built per hook invocation by RunAll after kind defaults have been applied. Some fields (OutputFile, OutputDir, ExitCode, CommandError) are populated by the engine before calling a kind's ResultHandler.

type Hook

type Hook struct {
	// Kind selects the engine that runs this hook. Built-in kinds:
	// "store" (existing semantics), "command" (generic binary execution),
	// plus named tool kinds like "infracost", "checkov", "trivy", "kics".
	//
	// For back-compat, the legacy `command:` YAML key is accepted as an
	// alias when `kind:` is absent. See UnmarshalYAML.
	Kind string `yaml:"kind,omitempty"`

	Events []string `yaml:"events,omitempty"`

	// Generic command-kind fields. Used by the command engine and by named
	// tool kinds via their defaults.
	//
	// Command is the binary to execute (resolved via the toolchain). For
	// named kinds it defaults to the kind's binary; users may override.
	Command string            `yaml:"command,omitempty"`
	Args    []string          `yaml:"args,omitempty"`
	Env     map[string]string `yaml:"env,omitempty"`
	// Format is the inline rendering hint for generic kinds. v1 accepts
	// "markdown" or empty (= downloadable artifact, no inline render).
	Format string `yaml:"format,omitempty"`

	// OnFailure is the failure mode. "warn" (default for tool kinds),
	// "fail" (propagate non-zero exit), or "ignore" (swallow).
	OnFailure string `yaml:"on_failure,omitempty"`

	// Store-kind specific (existing, unchanged semantics).
	Name    string            `yaml:"name,omitempty"`
	Outputs map[string]string `yaml:"outputs,omitempty"`
}

Hook is the structure for a hook configured in stack YAML. Each hook has a Kind that determines what engine runs it.

func (Hook) MatchesEvent added in v1.216.0

func (h Hook) MatchesEvent(event HookEvent) bool

MatchesEvent reports whether this hook should run for the given event. It normalises the yaml event format (hyphens, e.g. "after-terraform-apply") to the canonical Go format (dots, e.g. "after.terraform.apply") before comparing, so both styles are accepted in stack configuration.

If the hook has no events configured, it matches all events to preserve backward compatibility with configs written before event filtering existed.

func (*Hook) UnmarshalYAML

func (h *Hook) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML decodes a Hook, accepting the legacy `command:` key as an alias for `kind:` when `kind:` is absent. Pre-existing stack manifests with `command: store` continue to parse identically post-rename.

type HookEvent added in v1.159.0

type HookEvent string
const (
	BeforeTerraformInit   HookEvent = "before.terraform.init"
	AfterTerraformApply   HookEvent = "after.terraform.apply"
	BeforeTerraformApply  HookEvent = "before.terraform.apply"
	AfterTerraformPlan    HookEvent = "after.terraform.plan"
	BeforeTerraformPlan   HookEvent = "before.terraform.plan"
	BeforeTerraformDeploy HookEvent = "before.terraform.deploy"
	AfterTerraformDeploy  HookEvent = "after.terraform.deploy"
)

func (HookEvent) IsPostExecution added in v1.216.0

func (e HookEvent) IsPostExecution() bool

IsPostExecution reports whether the event fires after terraform has already run (and therefore after terraform init has already completed). Store hooks use this to decide whether to skip terraform init when reading outputs: after-events can safely skip init because the workdir is already initialized; before-events must run init because the workdir may not be initialized yet.

func (HookEvent) Normalize added in v1.216.0

func (e HookEvent) Normalize() HookEvent

Normalize returns the canonical form of a HookEvent, collapsing deploy aliases to their apply equivalents. deploy and apply are semantically equivalent — deploy is apply with -auto-approve — so hooks configured for either should fire regardless of which command the user runs.

type Hooks

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

func GetHooks added in v1.159.0

func GetHooks(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) (*Hooks, error)

func (Hooks) HasHooks added in v1.159.0

func (h Hooks) HasHooks() bool

func (*Hooks) RunAll added in v1.159.0

func (h *Hooks) RunAll(event HookEvent, atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo, cmd *cobra.Command, args []string) error

type Kind

type Kind struct {
	// Name is the kind discriminator (e.g. "store", "command", "infracost").
	Name string

	// Defaults for the generic command engine. Named kinds set these;
	// user Hook fields override.
	Command     string
	DefaultArgs []string
	DefaultEnv  map[string]string

	// OnFailure is the default failure mode if the hook doesn't override.
	OnFailure string

	// Engine runs hooks of this kind.
	Engine Engine

	// ResultHandler parses structured output into a Summary. Optional.
	ResultHandler ResultHandler
}

Kind is a registered hook type. Built-ins self-register from pkg/hooks/kinds/*/kind.go via init().

func GetKind

func GetKind(name string) (*Kind, bool)

GetKind returns a registered kind by name.

func (*Kind) ResolveDefaults

func (k *Kind) ResolveDefaults(hook *Hook) *Hook

ResolveDefaults returns a copy of hook with kind defaults filled in for any fields the hook didn't set explicitly. The original hook is not modified.

type Output

type Output struct {
	// Artifact is the opaque blob produced by the hook (tool output file,
	// rendered report, etc.). May be nil.
	Artifact *Artifact
	// Summary is the typed envelope used for run pages, PR comments, and
	// terminal rendering. May be nil.
	Summary *Summary
}

Output is what one hook invocation produces. Engines that don't emit structured output (e.g. store) return nil.

type ResultHandler

type ResultHandler func(ctx *ExecContext) (*Summary, error)

ResultHandler parses the kind's structured output and produces a Summary. Returning (nil, nil) is valid for kinds with no structured summary.

type RunCIHooksOptions added in v1.217.0

type RunCIHooksOptions struct {
	// Event is the hook event (e.g., "after.terraform.deploy").
	Event HookEvent

	// AtmosConfig is the Atmos configuration.
	AtmosConfig *schema.AtmosConfiguration

	// Info contains component and stack information.
	Info *schema.ConfigAndStacksInfo

	// Output is the captured command output to process.
	Output string

	// ForceCIMode forces CI mode even when environment detection fails (--ci flag).
	ForceCIMode bool

	// CommandError is the error from the command execution, if any (nil on success).
	CommandError error

	// ExitCode is the exit code from the command execution. This is the
	// authoritative signal plugins use to determine success/failure and (for
	// `terraform plan` with -detailed-exitcode) change detection. Pass 0 on success.
	ExitCode int
}

RunCIHooksOptions configures a RunCIHooks invocation.

type StoreCommand added in v1.159.0

type StoreCommand struct {
	Name string
	// contains filtered or unexported fields
}

func NewStoreCommand added in v1.159.0

func NewStoreCommand(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) (*StoreCommand, error)

func (*StoreCommand) GetName added in v1.159.0

func (c *StoreCommand) GetName() string

func (*StoreCommand) RunE added in v1.159.0

func (c *StoreCommand) RunE(hook *Hook, event HookEvent, cmd *cobra.Command, args []string) error

RunE is the entrypoint for the store command. It selects the appropriate terraform output getter based on the event: after-events (e.g. after-terraform-apply) skip terraform init because the workdir is already initialized; before-events run init normally since the workdir may not exist yet.

type Summary

type Summary struct {
	// Kind is the registered kind name (Pro selects its renderer from this).
	Kind string
	// Status is success | warning | failure.
	Status SummaryStatus
	// Title is the short headline (e.g. "+$47.20/mo" or "2 HIGH, 5 MED").
	Title string
	// Counts is an optional grouped breakdown (e.g. {"high": 2, "medium": 5}).
	Counts map[string]int
	// Body is the single markdown rendering used in every surface that
	// renders markdown: terminal, Pro run page, PR comments, step summaries.
	Body string
}

Summary is the typed envelope every hook kind fills the same way.

type SummaryStatus

type SummaryStatus string

SummaryStatus is the run status reported by a hook for the Pro/PR/terminal summary card.

const (
	StatusSuccess SummaryStatus = "success"
	StatusWarning SummaryStatus = "warning"
	StatusFailure SummaryStatus = "failure"
)

Summary statuses understood by Pro and the terminal renderer.

type TerraformOutputGetter added in v1.194.0

type TerraformOutputGetter func(
	atmosConfig *schema.AtmosConfiguration,
	stack string,
	component string,
	output string,
	skipCache bool,
	authContext *schema.AuthContext,
	authManager any,
) (any, bool, error)

TerraformOutputGetter retrieves terraform outputs. This enables dependency injection for testing. Returns:

  • value: The output value (may be nil if the output exists but has a null value)
  • exists: Whether the output key exists in the terraform outputs
  • error: Any error that occurred during retrieval (SDK errors, network issues, etc.)

Directories

Path Synopsis
kinds
checkov
Package checkov registers the built-in `checkov` hook kind.
Package checkov registers the built-in `checkov` hook kind.
infracost
Package infracost registers the built-in `infracost` hook kind.
Package infracost registers the built-in `infracost` hook kind.
kics
Package kics registers the built-in `kics` hook kind.
Package kics registers the built-in `kics` hook kind.
trivy
Package trivy registers the built-in `trivy` hook kind.
Package trivy registers the built-in `trivy` hook kind.
Package sarif parses SARIF 2.1.0 documents into a normalized Findings representation usable by hook ResultHandlers.
Package sarif parses SARIF 2.1.0 documents into a normalized Findings representation usable by hook ResultHandlers.

Jump to

Keyboard shortcuts

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