Documentation
¶
Index ¶
- Constants
- func All() []string
- func AllV2() []string
- func BuildOrder(builds []config.BuildConfig) ([]config.BuildConfig, error)
- func ChecksumFile(path string) (string, error)
- func DefaultTestCommand(builder, fromDir, rootDir string) (args []string, workdir string, err error)
- func DetectProvider(registryURL string) string
- func DetectVersion(rootDir string, cfg *config.Config) (*gitver.VersionInfo, error)
- func DetectVersionLenient(rootDir string, cfg *config.Config) (*gitver.VersionInfo, error)
- func EnsureCrucibleAllowed(rootDir string) error
- func EnvFingerprint() string
- func ExtractPredicate(statementPath string) (predPath, statementSHA string, ok bool)
- func FindBuildProvenance(rootDir string) ([]string, error)
- func FormatLayerInstruction(e LayerEvent) string
- func FormatLayerTiming(e LayerEvent) string
- func GenerateCrucibleRunID() string
- func HasVersionScheme(cfg *config.Config) bool
- func HashBuildContext(dockerfile, contextDir string) string
- func InjectLabels(plan *BuildPlan, labels map[string]string)
- func IsCrucibleChild() bool
- func NormalizeBuildPlan(plan *BuildPlan) string
- func PlanToOutputs(plan *BuildPlan, opts PlanToOutputsOpts) (artifact.OutputsManifest, error)
- func Register(name string, constructor func() Engine)
- func RegisterV2(name string, constructor func() EngineV2)
- func ResolveImageStamp(rootDir string, cfg *config.Config) (imageVersion, commit string)
- func ResolveTags(templates []string, v *gitver.VersionInfo) []string
- func ResolveTemplate(tmpl string, v *gitver.VersionInfo) string
- func ScribeRenderSlots(order []PerformNode) (first []string, after map[string][]string)
- func SlugifyBuildID(id string) string
- func StandardLabels(planHash, sfVersion, commit, mode, createdRFC3339 string) map[string]string
- func StepIDForTarget(buildID string, t Target) string
- func TruncHash(s string) string
- func TrustLevelLabel(level string) string
- func ValidateBuildGraph(steps []UniversalStep) error
- func WithDescription(labels map[string]string, description string) map[string]string
- func WriteChecksums(outputDir string, archives []*ArchiveResult) (string, error)
- func WriteDSSEProvenance(path string, stmt ProvenanceStatement) error
- func WriteProvenance(path string, stmt ProvenanceStatement) error
- type ArchiveArtifactPlan
- type ArchiveOpts
- type ArchiveResult
- type ArtifactRef
- type BinaryArtifactPlan
- type BuildConfig
- type BuildPlan
- type BuildResult
- type BuildStep
- type CacheRef
- type Capabilities
- type CargoBuild
- type CargoBuildOpts
- type CargoBuildResult
- type DSSEEnvelope
- type DSSESignature
- type Detection
- type DockerfileInfo
- type Engine
- type EngineV2
- type ExtractRule
- type GitInfo
- type GoBuild
- type GoBuildOpts
- type GoBuildResult
- type ImagePlanInput
- type LayerEvent
- type OutputMode
- type PerformNode
- type PlanToOutputsOpts
- type ProducedArtifact
- type ProvenanceBuilder
- type ProvenanceInvocation
- type ProvenanceMaterial
- type ProvenanceMetadata
- type ProvenancePredicate
- type ProvenanceStatement
- type ProvenanceSubject
- type PushObservation
- type RegistryTarget
- type ResultsBuilder
- type Stage
- type StepMeta
- type StepMetrics
- type StepResult
- type Target
- type TargetSkip
- type UniversalStep
- type UniversalStepResult
- type VersionInfo
Constants ¶
const ( // CrucibleEnvVar is set to "1" inside the pass-2 container to prevent recursion. CrucibleEnvVar = "STAGEFREIGHT_CRUCIBLE" // CrucibleRunIDEnvVar correlates pass-1 and pass-2 in logs/artifacts. CrucibleRunIDEnvVar = "STAGEFREIGHT_CRUCIBLE_RUN_ID" // CrucibleAllowEnvVar overrides the repo guard for non-StageFreight repos. CrucibleAllowEnvVar = "STAGEFREIGHT_ALLOW_CRUCIBLE" // StageFreightModule is the canonical Go module path used by the repo guard. StageFreightModule = "github.com/PrPlanIT/StageFreight" )
Crucible environment variables.
const ( TrustViable = "viable" // pass 2 succeeded TrustConsistent = "consistent" // version + build graph match TrustDeterministic = "deterministic" // binary hash identical TrustReproducible = "reproducible" // image digest identical (stretch goal) )
Trust levels, ordered from weakest to strongest.
const ( LabelCreated = "org.opencontainers.image.created" LabelRevision = "org.opencontainers.image.revision" LabelVersion = "org.opencontainers.image.version" LabelDescription = "org.opencontainers.image.description" LabelBuildMode = "org.stagefreight.build.mode" LabelPlanHash = "org.stagefreight.plan.sha256" )
Standard OCI label keys emitted by StageFreight on every build.
const DistDir = paths.Root + "/dist"
DistDir is the StageFreight-managed output root for binary builds and their archives, relative to the repo root. It lives under .stagefreight/ on purpose: CI forwards only .stagefreight/ across the perform→publish job boundary, and the publish phase must be able to open the archive files its manifest references. Binaries, archives, and SHA256SUMS all live beneath this single root — splitting them (e.g. a bare top-level dist/) reopens the seam where publish receives metadata for files it does not possess.
const ProvenanceDir = paths.Root + "/provenance"
ProvenanceDir is where build provenance statements are written, relative to root.
Variables ¶
This section is empty.
Functions ¶
func AllV2 ¶ added in v0.4.0
func AllV2() []string
AllV2 returns sorted names of all registered v2 engines.
func BuildOrder ¶ added in v0.4.0
func BuildOrder(builds []config.BuildConfig) ([]config.BuildConfig, error)
BuildOrder computes the topological execution order for a set of builds. Uses Kahn's algorithm. Returns an error on cycles or missing references.
func ChecksumFile ¶ added in v0.4.0
ChecksumFile computes the SHA-256 hex digest of a file and writes a .sha256 sidecar.
func DefaultTestCommand ¶ added in v0.7.0
func DefaultTestCommand(builder, fromDir, rootDir string) (args []string, workdir string, err error)
DefaultTestCommand returns the native test invocation for a builder plus the working directory it must run in. It owns "what does testing a Go/Rust project mean" so the test subsystem never duplicates toolchain knowledge.
go → go test ./... (from the module root — the dir holding go.mod)
rust → cargo test (single crate)
cargo test --workspace (when the crate root's Cargo.toml is a [workspace])
fromDir is the build's `From` (the main-package / crate dir), which may sit BELOW the module/crate root — stagefreight builds `./src/cli` but its go.mod is at the repo root; dd-ui's go.mod is in `api/`. So the working dir is resolved by walking up from fromDir to the nearest manifest, bounded by rootDir.
Only the BASE command is returned; suite flags (-race, -tags, --features, …) and the synthesized-default policy are layered by the caller.
func DetectProvider ¶
DetectProvider determines the registry vendor from the URL. Well-known domains are matched directly. For unknown domains, returns "generic" (future: probe the registry API to identify the vendor).
func DetectVersion ¶
DetectVersion resolves version info using versioning config from the given Config. Config is REQUIRED — nil is rejected. Every caller must thread a valid *config.Config through to version detection. There is no legacy "just guess from git" path.
func DetectVersionLenient ¶ added in v0.8.0
DetectVersionLenient is DetectVersion for AUDIENCE-TEXT rendering (scribe bodies, narrate cards, notifications): an unversioned repo yields a minimal run identity (SHA/branch) with no error, so the template leaf-pass still runs and {version} simply elides — no "version detection failed" noise for a repo that never claimed to have a version. Build/publish/release paths keep the strict DetectVersion: THEY require a scheme, and its absence stays loud.
func EnsureCrucibleAllowed ¶
EnsureCrucibleAllowed checks that the repo is the StageFreight repo itself, or that STAGEFREIGHT_ALLOW_CRUCIBLE=1 is set.
func EnvFingerprint ¶
func EnvFingerprint() string
EnvFingerprint returns an informational hash of the build environment. Non-authoritative — useful for debugging but never a primary signal.
func ExtractPredicate ¶ added in v0.7.0
ExtractPredicate reads an in-toto Statement and writes its predicate BODY to a sibling `.predicate.json` for cosign attest (cosign frames the predicate with the attested image as subject — so the whole statement must NOT be passed as the predicate, or it would be double-wrapped). It returns the predicate path, the sha256 of the CANONICAL statement (the provenance's recorded identity), and ok=false when the statement is absent, unreadable, or carries no predicate — "no usable provenance", so an enabled attestation can fail loud rather than attaching nothing. Shared by the unattended build path and `stagefreight sign`.
func FindBuildProvenance ¶ added in v0.7.0
FindBuildProvenance returns the build-provenance statement files under rootDir's provenance dir (the `.predicate.json` bodies ExtractPredicate writes are excluded). Sorted for determinism. `stagefreight sign` uses this to locate the provenance to attest; a build normally emits exactly one, so >1 is the caller's signal to refuse rather than guess which predicate belongs to which image.
func FormatLayerInstruction ¶
func FormatLayerInstruction(e LayerEvent) string
FormatLayerInstruction formats a layer event into a display string. For FROM instructions, shows the base image name. For other instructions, shows the instruction and truncated detail.
func FormatLayerTiming ¶
func FormatLayerTiming(e LayerEvent) string
FormatLayerTiming formats a layer's timing for display. Returns "cached" for cache hits, or the duration string for completed layers.
func GenerateCrucibleRunID ¶
func GenerateCrucibleRunID() string
GenerateCrucibleRunID returns a cryptographically random hex string for correlating crucible passes. Uses crypto/rand to avoid collisions in CI where multiple pipelines may start at the same nanosecond.
func HasVersionScheme ¶ added in v0.8.0
HasVersionScheme reports whether the config declares a version derivation scheme (git.versioning.branch_builds). Absence is a VALID state — an unversioned repo (a gitops config repo, say) has commits and tags but no version to derive — not a configuration error.
func HashBuildContext ¶ added in v0.8.0
HashBuildContext returns a content hash of the inputs that actually determine the built bytes: the Dockerfile plus every file in the build context. Any source-byte change yields a different hash — the property NormalizeBuildPlan's path-only identity was missing. Best-effort and deterministic: files are hashed in sorted order; an unreadable path contributes a stable "unreadable" marker (so identity degrades to "unknown content" rather than silently colliding); noise dirs that never affect the image (.git, .stagefreight, node_modules, vendored git) are skipped so the hash reflects source, not build detritus.
func InjectLabels ¶
InjectLabels merges labels into every step of a plan. Existing labels on a step are preserved; new labels do not overwrite.
func IsCrucibleChild ¶
func IsCrucibleChild() bool
IsCrucibleChild returns true when running inside a crucible pass-2 container.
func NormalizeBuildPlan ¶
NormalizeBuildPlan produces a deterministic fingerprint of a BuildPlan, excluding ephemeral/runtime-derived fields. Used globally for provenance, and by crucible for build graph verification between passes.
Included fields (build-affecting):
- BuildStep.Name, Dockerfile, Context, Target (build identity)
- BuildStep.Platforms (affects output binary)
- BuildStep.BuildArgs (minus BUILD_DATE — ephemeral timestamp)
Excluded fields (ephemeral or derived at runtime):
- BuildStep.Tags (output naming, not build-affecting)
- BuildStep.Registries (output destinations, not build-affecting)
- BuildStep.Output (always "image" for docker)
- BuildStep.Load, Push (runtime strategy decisions)
- BuildStep.Labels (metadata, not build-affecting)
- BuildStep.Extract (artifact mode only)
- RegistryTarget.Credentials (auth, not build-affecting)
- RegistryTarget.Provider (inferred, not build-affecting)
- RegistryTarget.Retention, TagPatterns (post-build operations)
- BuildArgs["BUILD_DATE"] (timestamp, always differs between runs)
- Map iteration order (all maps sorted by key)
- Empty/zero-value fields (omitted, not hashed)
- Builder-generated metadata (layer IDs, cache keys, etc.)
func PlanToOutputs ¶ added in v0.6.0
func PlanToOutputs(plan *BuildPlan, opts PlanToOutputsOpts) (artifact.OutputsManifest, error)
PlanToOutputs is a pure function from BuildPlan + plan-time options to OutputsManifest. Allocation-only: it must not inspect execution state, must not infer runtime outcomes, must not fall back on partial build metadata. If a field is not plan-derivable, it does not belong in the returned manifest.
The returned manifest is fully finalized — schema version, generated_at, artifact ids, sort order, and embedded checksum are all populated. It is suitable to either pass directly to WriteOutputsManifest for persistence or to ResultsBuilder.Build as the in-memory intent snapshot. No disk round-trip is required between the two uses.
func Register ¶
Register adds an engine constructor to the global registry. Called from init() in each engine package.
func RegisterV2 ¶ added in v0.4.0
RegisterV2 adds an EngineV2 constructor to the global registry.
func ResolveImageStamp ¶ added in v0.9.0
ResolveImageStamp returns the version and short commit that identify the SOURCE being built — the same VersionInfo (Version/SHA) that autoInjectBuildArgs feeds the compiled binary's ldflags. It is the single source of truth for build provenance: OCI labels (org.opencontainers.image.version/.revision) and the identity banner MUST resolve through here, never through the version.* globals. Those globals are the ldflags stamp of the RUNNING orchestrator binary, which describes StageFreight itself, not the repo under build — so in self-hosted CI (and, silently, on every foreign build) they stamped a stale ancestor as the artifact's revision. Falls back to the orchestrator stamp only when the working tree yields no version (a detached CI build container with no repo, or a repo with no versioning scheme), so an unversioned build is never left blank.
func ResolveTags ¶
func ResolveTags(templates []string, v *gitver.VersionInfo) []string
ResolveTags delegates to the gitver package.
func ResolveTemplate ¶
func ResolveTemplate(tmpl string, v *gitver.VersionInfo) string
ResolveTemplate delegates to the gitver package.
func ScribeRenderSlots ¶ added in v0.8.0
func ScribeRenderSlots(order []PerformNode) (first []string, after map[string][]string)
ScribeRenderSlots splits a PerformOrder into the render slots the perform executor uses: `first` composes before any build runs; `after[buildID]` composes right after that build's steps finish (so its output can be materialized and the pages the NEXT build bakes are written first). Each scribe node is assigned to the build immediately preceding it in the order — which, by construction of PerformOrder, is on the path between the item's upstream build and its consuming build.
func SlugifyBuildID ¶ added in v0.3.2
SlugifyBuildID sanitizes a build ID for use as a filename. Lowercase, [a-z0-9-] only, spaces/underscores → hyphens, slashes forbidden.
func StandardLabels ¶
StandardLabels returns the set of OCI labels that should be applied to every image built by StageFreight, regardless of build mode.
func StepIDForTarget ¶ added in v0.7.0
StepIDForTarget builds a deterministic step ID. Format: {buildID}--{os}-{arch}[-{libc}] (variant slot reserved by the "--").
func TrustLevelLabel ¶
TrustLevelLabel returns human text for the trust level with context when the level is below deterministic.
func ValidateBuildGraph ¶ added in v0.4.0
func ValidateBuildGraph(steps []UniversalStep) error
ValidateBuildGraph performs pre-execution validation on a set of universal steps. Checks: no duplicate step IDs, no duplicate output paths, all input refs satisfied.
func WithDescription ¶ added in v0.9.1
WithDescription stamps org.opencontainers.image.description from the project's declared description (project-metadata.description) into the label set. StageFreight OWNS this label whenever the project declares a description: it is written every build (so it stays current, not first-build-only) and — because a build --label overrides a Dockerfile LABEL of the same key — it is authoritative over any baked-in value, giving one dependable source. When no description is configured, the label is left untouched (a Dockerfile's own value, if any, stands) — SF never invents one, so there is no surprise clobber.
func WriteChecksums ¶ added in v0.4.0
func WriteChecksums(outputDir string, archives []*ArchiveResult) (string, error)
WriteChecksums creates a SHA256SUMS file from a set of archive results.
func WriteDSSEProvenance ¶
func WriteDSSEProvenance(path string, stmt ProvenanceStatement) error
WriteDSSEProvenance writes a DSSE-wrapped provenance statement as indented JSON.
func WriteProvenance ¶
func WriteProvenance(path string, stmt ProvenanceStatement) error
WriteProvenance writes a provenance statement as indented JSON.
Types ¶
type ArchiveArtifactPlan ¶ added in v0.6.0
ArchiveArtifactPlan is the plan-time description of one archive output. Same un-targeted invariant as BinaryArtifactPlan; Sources references the binary artifacts the archive wraps (sibling-artifact relationship, not embedding), and lives on the ArchiveOutcome side rather than the plan.
type ArchiveOpts ¶ added in v0.4.0
type ArchiveOpts struct {
// Format is "tar.gz", "zip", or "auto" (zip for windows, tar.gz otherwise).
Format string
// OutputDir is where archives are written.
OutputDir string
// NameTemplate is the archive filename template (without extension).
// Supports: {id}, {version}, {os}, {arch}
NameTemplate string
// BinaryPath is the path to the compiled binary to include.
BinaryPath string
// BinaryName is the filename inside the archive (may differ from physical path basename).
BinaryName string
// IncludeFiles lists extra files to bundle (relative to repo root).
IncludeFiles []string
// RepoRoot is the root directory for resolving include files.
RepoRoot string
// Target is the build target this archive packages.
Target Target
// BuildID is used for template resolution.
BuildID string
// Version info for template resolution.
Version *VersionInfo
}
ArchiveOpts holds configuration for archive creation.
type ArchiveResult ¶ added in v0.4.0
type ArchiveResult struct {
Path string // archive file path
Format string // actual format used
Size int64
SHA256 string
Contents []string // files inside the archive
}
ArchiveResult holds the output of an archive operation.
func CreateArchive ¶ added in v0.4.0
func CreateArchive(opts ArchiveOpts) (*ArchiveResult, error)
CreateArchive builds an archive containing a binary and optional extra files. CreateArchive produces a deterministic archive file from the supplied binary + optional include files. Determinism rule (load-bearing for ArchiveOutcome.SHA256 stability across runs):
Archive identity MUST be deterministic over: - sorted file set (canonical archive-name order, not caller order) - normalized tar/zip headers (zero ModTime, zero Uid/Gid, fixed mode) - single-pass SHA256 over the final stream Any deviation introduces cross-run instability in ArchiveOutcome.SHA256. Caller-supplied include order is intentionally ignored; sorting happens here once, at the determinism boundary, not at every consumer.
type ArtifactRef ¶ added in v0.4.0
type ArtifactRef struct {
Path string `json:"path"`
Type string `json:"type"` // "binary", "image", "archive", "metadata"
}
ArtifactRef is a declared artifact reference (expected input or output).
type BinaryArtifactPlan ¶ added in v0.6.0
type BinaryArtifactPlan struct {
Name string
OS string
Arch string
Path string
Toolchain string
Version string
}
BinaryArtifactPlan is the plan-time description of one binary output. Path is the intended output location relative to the workspace; SHA256 and any post-build identity belong in the corresponding Outcome.
Binary artifacts are un-targeted by design (Q2, Phase 4): the build artifact IS the truth, and distribution destinations are decided at a later layer (release_create), not at build time. There is no Targets field on the plan because there are no targets in the intent.
type BuildConfig ¶ added in v0.4.0
type BuildConfig struct {
ID string
Kind string
Platforms []Target
BuildMode string
SelectTags []string
// Version info for template resolution
Version *VersionInfo
// RootDir is the repo root, for filesystem-derived facts in arg templates
// (e.g. {project.module} reads the build manifest — go.mod / Cargo.toml / …).
RootDir string
// kind: docker fields
Dockerfile string
Context string
Target string
BuildArgs map[string]string
Tags []string
Registries []RegistryTarget
// kind: binary fields
Builder string
Command string
From string
Output string
Args []string
Env map[string]string
Compress bool
// kind: binary, builder: node — containerized build. The build Command runs
// INSIDE Image (repo mounted); Output is the produced-artifact glob. Lets SF
// ship things it can't compile natively (e.g. an Electron .exe via wine).
Image string
}
BuildConfig is the normalized input to EngineV2.Plan(). Core synthesizes this from config + detection; engines don't develop their own auto-config policy brains.
type BuildPlan ¶
type BuildPlan struct {
Steps []BuildStep
}
BuildPlan is the resolved execution plan for a build.
type BuildResult ¶
type BuildResult struct {
Steps []StepResult
Duration time.Duration
}
BuildResult captures the outcome of a full build plan execution.
type BuildStep ¶
type BuildStep struct {
Name string
Dockerfile string
Context string
ContextDigest string // content hash of the Dockerfile + build context (see HashBuildContext); folds source content into the build identity so a code change is not invisible to NormalizeBuildPlan
Target string
Platforms []string
BuildArgs map[string]string
// Secrets are id → in-repo path, mounted for a RUN and left out of the image.
Secrets map[string]string
Labels map[string]string // OCI labels injected via --label
Tags []string
Output OutputMode
Extract []ExtractRule // artifact mode only
Registries []RegistryTarget // image mode only
Load bool // --load into daemon
Push bool // --push to registries
MetadataFile string // temp file for buildx --metadata-file (digest capture)
OCILayoutDir string // --output type=oci,dest=<dir> for content-store persistence; additive to Load/Push
CacheFrom []CacheRef // --cache-from references
CacheTo []CacheRef // --cache-to references
SkippedTargets []TargetSkip // registry targets excluded by when:, with the matcher's reason (narrated)
}
BuildStep is a single build invocation.
type CacheRef ¶ added in v0.5.0
type CacheRef struct {
Type string // "registry", "local"
Ref string // registry ref or local path
Mode string // "max", "min" (export only)
Direction string // "import" or "export" — determines local key (src vs dest)
}
CacheRef is a structured build cache reference.
type Capabilities ¶ added in v0.4.0
type Capabilities struct {
SupportsCrossCompile bool `json:"supports_cross_compile"`
SupportsCrucible bool `json:"supports_crucible"`
ProducesArchives bool `json:"produces_archives"`
ProducesOCI bool `json:"produces_oci"`
}
Capabilities declares what a build engine can do. Core queries behavior, never engine names.
type CargoBuild ¶ added in v0.7.0
CargoBuild wraps Cargo compilation — the Rust analog of GoBuild. It runs `cargo build` and copies the produced binary to the canonical output path, so a Rust binary lands in the SAME artifact lifecycle (DistDir layout, SHA256, archive, signing) as a Go binary. The build's "how" differs (cargo vs go); the artifact contract is identical.
func NewCargoBuild ¶ added in v0.7.0
func NewCargoBuild(verbose bool) *CargoBuild
func (*CargoBuild) Build ¶ added in v0.7.0
func (c *CargoBuild) Build(ctx context.Context, opts CargoBuildOpts) (*CargoBuildResult, error)
Build compiles a Rust binary and copies it to OutputPath.
type CargoBuildOpts ¶ added in v0.7.0
type CargoBuildOpts struct {
ManifestDir string // dir containing Cargo.toml (cmd.Dir)
BinName string // the [[bin]]/package name → target/<profile>/<BinName>
OutputPath string // canonical output (DistDir/<slug>/<name>) — the binary is copied here
Release bool // --release (release profile)
TargetDir string // CARGO_TARGET_DIR (where target/ lives); "" = ManifestDir/target
Args []string // raw args before nothing (e.g. ["--features", "x"])
Env map[string]string // additional env (e.g. CARGO_HOME)
CargoBin string // resolved cargo binary; "" falls back to "cargo" on $PATH (dev only)
}
CargoBuildOpts holds the parameters for a single cargo compilation.
type CargoBuildResult ¶ added in v0.7.0
CargoBuildResult holds the output of a cargo compilation.
type DSSEEnvelope ¶
type DSSEEnvelope struct {
PayloadType string `json:"payloadType"`
Payload string `json:"payload"` // base64-encoded ProvenanceStatement
Signatures []DSSESignature `json:"signatures"`
}
DSSEEnvelope is a Dead Simple Signing Envelope for wrapping provenance statements.
func WrapDSSE ¶
func WrapDSSE(stmt ProvenanceStatement) (DSSEEnvelope, error)
WrapDSSE wraps a ProvenanceStatement in a DSSE envelope (unsigned). The caller can sign the payload externally (cosign) and attach the signature.
type DSSESignature ¶
DSSESignature is a single signature within a DSSE envelope.
type Detection ¶
type Detection struct {
RootDir string // absolute path to repo root
Dockerfiles []DockerfileInfo
Language string // "go", "rust", "node", "python", ""
Lockfiles []string // relative paths: go.mod, Cargo.toml, etc.
MainPackages []string // detected main package paths (Go: cmd/foo, bar, .)
GitInfo *GitInfo
}
Detection holds everything discovered about a repo's build capabilities.
func DetectRepo ¶
DetectRepo inspects a directory and returns build-relevant information.
type DockerfileInfo ¶
type DockerfileInfo struct {
Path string // relative path from repo root
Stages []Stage // parsed multistage stages
Args []string
Expose []string
Healthcheck *string
}
DockerfileInfo describes a discovered Dockerfile.
func ParseDockerfile ¶
func ParseDockerfile(path string) (*DockerfileInfo, error)
ParseDockerfile extracts stage, arg, expose, and healthcheck info from a Dockerfile. This is a regex-based parser — not a full AST. Sufficient for detection and planning.
type Engine ¶
type Engine interface {
Name() string
Detect(ctx context.Context, rootDir string) (*Detection, error)
Plan(ctx context.Context, cfg interface{}, det *Detection) (*BuildPlan, error)
}
Engine is the interface every build engine implements.
type EngineV2 ¶ added in v0.4.0
type EngineV2 interface {
// Name returns the engine's identifier (e.g., "binary", "image").
Name() string
// Capabilities declares what this engine supports.
Capabilities() Capabilities
// Detect inspects a repo and returns build-relevant information.
Detect(ctx context.Context, rootDir string) (*Detection, error)
// Plan converts a build config into a list of universal steps.
// Core owns config synthesis — Plan receives normalized config, not detection guesses.
Plan(ctx context.Context, cfg BuildConfig) ([]UniversalStep, error)
// ExecuteStep runs a single step and returns its result.
// The engine must not: write publish manifests, attach release assets,
// manage concurrency, resolve dependencies, or print logs directly.
ExecuteStep(ctx context.Context, step UniversalStep) (*UniversalStepResult, error)
}
EngineV2 is the universal engine interface for all build types. Engines are declarative planners — they convert config to steps and execute individual steps. All orchestration (ordering, concurrency, retries, logging, artifact recording, checksums, publish manifest) lives in core.
type ExtractRule ¶
type ExtractRule struct {
From string // path inside the container
To string // local destination path
}
ExtractRule defines a file to extract from a build container.
type GitInfo ¶
type GitInfo struct {
Remote string // origin URL
Branch string // current branch
LatestTag string
SHA string
}
GitInfo holds git repository metadata.
type GoBuild ¶ added in v0.4.0
GoBuild wraps Go compilation commands.
func NewGoBuild ¶ added in v0.4.0
NewGoBuild creates a GoBuild runner with default output writers.
func (*GoBuild) Build ¶ added in v0.4.0
func (g *GoBuild) Build(ctx context.Context, opts GoBuildOpts) (*GoBuildResult, error)
Build compiles a Go binary with the given options.
func (*GoBuild) DetectMainPackages ¶ added in v0.4.0
DetectMainPackages scans a Go project for main packages. Looks in: cmd/*/main.go, */main.go, main.go
type GoBuildOpts ¶ added in v0.4.0
type GoBuildOpts struct {
Entry string // main package path (e.g., "cmd/planedc/main.go" or "./cmd/planedc")
OutputPath string // output binary path
GOOS string
GOARCH string
Args []string // raw args passed before entry (e.g., ["-tags", "banner_art", "-ldflags", "..."])
Env map[string]string // additional env vars (e.g., CGO_ENABLED=0)
GoBin string // resolved go binary (from the toolchain subsystem); "" falls back to "go" on $PATH
}
GoBuildOpts holds the parameters for a single Go compilation.
type GoBuildResult ¶ added in v0.4.0
GoBuildResult holds the output of a Go compilation.
type ImagePlanInput ¶ added in v0.4.0
type ImagePlanInput struct {
Cfg *config.Config // full config
BuildID string // optional: build specific entry by ID (empty = all)
}
ImagePlanInput bundles the config needed for image build planning.
type LayerEvent ¶
type LayerEvent struct {
Stage string // "builder", "stage-1", "" (for internal steps)
StageStep string // "1/7", "2/7", etc.
Instruction string // "FROM", "COPY", "RUN", "WORKDIR", "ENV", "ARG", "EXPOSE", "ADD"
Detail string // instruction arguments (truncated)
Cached bool // true if layer was a cache hit
Duration time.Duration // layer execution time (0 for cached layers)
Image string // for FROM: the base image name (without digest)
}
LayerEvent represents a completed build layer parsed from buildx output.
type OutputMode ¶
type OutputMode string
OutputMode describes what the build produces.
const ( OutputImage OutputMode = "image" // container image (push to registry or load to daemon) OutputLocal OutputMode = "local" // extract files to local filesystem OutputTar OutputMode = "tar" // export as tarball )
type PerformNode ¶ added in v0.8.0
type PerformNode struct {
Build *config.BuildConfig // non-nil → run this build
ScribeID string // non-empty → render this scribe content item
}
PerformNode is one node in the perform execution order: either a build to run or a build-fed scribe item to render. Exactly one of Build / ScribeID is set.
func PerformOrder ¶ added in v0.8.0
func PerformOrder(builds []config.BuildConfig, stencils config.OrderedStencils) ([]PerformNode, error)
PerformOrder topologically orders the builds together with the scribe items that builds CONSUME (build-fed), so each consumed item renders AFTER its upstream build (contents/include `build:`) and BEFORE the build that bakes it (`depends_on: scribe:<id>`). Scribe items no build consumes are omitted here — they render late, in publish. Deterministic; errors on a cycle or a dep on an absent build.
This is the "render → consumer ordering" of #39: the graph decides when a scribe item renders (before its consumer), and late items fall through to publish.
func (PerformNode) IsScribe ¶ added in v0.8.0
func (n PerformNode) IsScribe() bool
IsScribe reports whether this node is a scribe render (vs a build).
type PlanToOutputsOpts ¶ added in v0.6.0
type PlanToOutputsOpts struct {
GeneratedAt string // RFC3339; if empty, Finalize defaults to UTC now
Commit string
Pipeline *artifact.Pipeline
BinaryPlans []BinaryArtifactPlan // plan-time binary descriptors
ArchivePlans []ArchiveArtifactPlan // plan-time archive descriptors
}
PlanToOutputsOpts carries non-plan inputs needed to fully construct the intent manifest. Everything here is either plan-time configuration or pipeline metadata — never execution state. GeneratedAt is supplied by the caller so PlanToOutputs is fully pure (no wall-clock read).
type ProducedArtifact ¶ added in v0.4.0
type ProducedArtifact struct {
Path string `json:"path"`
Type string `json:"type"` // "binary", "image", "archive", "metadata"
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
}
ProducedArtifact is an observed output from a step execution.
type ProvenanceBuilder ¶
type ProvenanceBuilder struct {
ID string `json:"id"`
}
ProvenanceBuilder identifies the build system.
type ProvenanceInvocation ¶
type ProvenanceInvocation struct {
ConfigSource map[string]any `json:"configSource,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
Environment map[string]any `json:"environment,omitempty"`
}
ProvenanceInvocation captures the build parameters and environment.
type ProvenanceMaterial ¶
type ProvenanceMaterial struct {
URI string `json:"uri"`
Digest map[string]string `json:"digest,omitempty"`
}
ProvenanceMaterial represents an input to the build.
type ProvenanceMetadata ¶
type ProvenanceMetadata struct {
BuildStartedOn string `json:"buildStartedOn,omitempty"`
BuildFinishedOn string `json:"buildFinishedOn,omitempty"`
Completeness map[string]bool `json:"completeness,omitempty"`
Reproducible bool `json:"reproducible"`
}
ProvenanceMetadata captures timing and completeness.
type ProvenancePredicate ¶
type ProvenancePredicate struct {
BuildType string `json:"buildType"`
Builder ProvenanceBuilder `json:"builder"`
Invocation ProvenanceInvocation `json:"invocation"`
Metadata ProvenanceMetadata `json:"metadata"`
Materials []ProvenanceMaterial `json:"materials,omitempty"`
StageFreight map[string]any `json:"stagefreight,omitempty"`
}
ProvenancePredicate describes how it was built.
type ProvenanceStatement ¶
type ProvenanceStatement struct {
Type string `json:"_type"`
PredicateType string `json:"predicateType"`
Subject []ProvenanceSubject `json:"subject"`
Predicate ProvenancePredicate `json:"predicate"`
}
ProvenanceStatement follows the in-toto Statement v1 / SLSA Provenance v1 structure. Not full SLSA compliance, but a useful provenance document that can evolve into DSSE envelopes, cosign attestations, or OCI referrer artifacts.
type ProvenanceSubject ¶
type ProvenanceSubject struct {
Name string `json:"name"`
Digest map[string]string `json:"digest,omitempty"`
}
ProvenanceSubject identifies what was built.
type PushObservation ¶ added in v0.6.0
PushObservation is buildx's record of one push: registry coordinates plus the observed digest. Scoped to docker push observation — consumers convert to v2 Outcome by calling rb.Record with these fields. Does NOT carry credentials, provider, or any value used as a join key; ArtifactID lives with the consumer that knows which step produced this observation.
type RegistryTarget ¶
type RegistryTarget struct {
URL string
Path string
Tags []string
Credentials string // env var prefix for auth (e.g., "DOCKERHUB" → DOCKERHUB_USER/DOCKERHUB_PASS)
Provider string // registry vendor: dockerhub, ghcr, gitlab, jfrog, harbor, quay, gitea, generic
Retention config.RetentionPolicy // restic-style retention policy
TagPatterns []string // original unresolved tag templates for pattern matching during retention
NativeScan bool // trigger registry's own built-in scan after push (Harbor: built-in Trivy)
// SigningProfile is the resolved trust profile published images are signed
// under — the synthesized `legacy` default (implicit COSIGN_KEY signing) when
// the target names no signing_profile. Resolved at lowering, consumed by the
// publish-phase image signer.
SigningProfile *config.ResolvedSigningProfile
}
RegistryTarget is a resolved registry push destination.
type ResultsBuilder ¶ added in v0.6.0
type ResultsBuilder struct {
// contains filtered or unexported fields
}
ResultsBuilder accumulates Outcomes during execution and produces a ResultsManifest at the end. Single-writer (per-process); not concurrent- safe — execution is sequential.
Intentionally minimal API: Record appends, Build finalizes. No dedup, no reordering policy, no validation beyond the intent ↔ result join. "Anything smarter becomes a hidden policy engine."
Cross-domain coupling is restricted to ArtifactID. Names and kinds are resolved at Build time from the OutputsManifest — the builder itself does not track them. This keeps ResultsBuilder ignorant of intent structure and prevents drift via metadata duplication.
func NewResultsBuilder ¶ added in v0.6.0
func NewResultsBuilder() *ResultsBuilder
NewResultsBuilder returns an empty builder. The intent_checksum is bound at Build() time from the OutputsManifest, not at construction — this ensures results always reference the actual approved intent rather than a checksum cached at construction.
func ResultsBuilderFromManifest ¶ added in v0.7.0
func ResultsBuilderFromManifest(m *artifact.ResultsManifest) *ResultsBuilder
ResultsBuilderFromManifest returns a builder pre-seeded with an existing manifest's outcomes, so a later phase EXTENDS recorded history rather than replacing it. published.json is cumulative observed truth (build outcomes recorded by perform, push outcomes by publish) — a phase that re-records its own outcomes into a fresh builder would clobber the earlier facts (e.g. drop archive build outcomes that release-asset discovery depends on). Outcomes are re-recorded in manifest order; the caller then Records this phase's new outcomes on top before Build(). A nil manifest yields an empty builder.
func (*ResultsBuilder) Build ¶ added in v0.6.0
func (b *ResultsBuilder) Build(outputs *artifact.OutputsManifest) (artifact.ResultsManifest, error)
Build finalizes the results manifest. Deterministic ordering: artifacts in first-recorded order; outcomes within each artifact in append order.
Returns an error if any recorded outcome references an ArtifactID absent from outputs.Artifacts. This is the only cross-domain validation the builder performs — it enforces the join key without owning any other invariant about intent structure.
outputs must be the in-memory intent snapshot returned by PlanToOutputs (or another already-finalized OutputsManifest). Do NOT round-trip through disk to obtain it — the architecture deliberately removed cross-phase file reads, and reintroducing one here would couple results finalization to I/O ordering.
func (*ResultsBuilder) Record ¶ added in v0.6.0
func (b *ResultsBuilder) Record(artifactID artifact.ArtifactID, o artifact.Outcome)
Record appends an outcome for an artifact. Append-only. Caller is responsible for calling Record exactly once per (artifact, target) tuple with the final outcome already fully populated (digest, attestation, requirements_met). No post-Record mutation is supported — the outcome must be a complete fact at the moment of recording.
artifactID is typed (artifact.ArtifactID, not bare string) to make the "ArtifactID is the only join key" invariant compile-enforced. Callers supply IDs obtained from artifact.NewArtifactID or from view/manifest reads — never assembled from fields inline.
type Stage ¶
type Stage struct {
Name string // alias from "AS name", empty if unnamed
BaseImage string // the FROM image reference
Line int // line number of the FROM instruction
}
Stage describes a single FROM stage in a Dockerfile.
type StepMeta ¶ added in v0.4.0
type StepMeta interface {
StepMetaKind() string
}
StepMeta is implemented by typed metadata structs attached to build steps. Every Meta type must be JSON-marshalable and return a stable kind string.
type StepMetrics ¶ added in v0.4.0
StepMetrics captures timing and cache information for a step execution.
type StepResult ¶
type StepResult struct {
Name string
Status string // "success", "failed", "cached"
Images []string // pushed image references (raw refs for display)
Publications []PushObservation // structured publish records — v2 wire to ResultsBuilder
Artifacts []string // extracted file paths
Layers []LayerEvent // parsed build layer events (from --progress=plain)
Duration time.Duration
Error error
}
StepResult captures the outcome of a single build step.
type Target ¶ added in v0.7.0
type Target struct {
OS string `json:"os"`
Arch string `json:"arch"`
Libc string `json:"libc,omitempty"` // "", "gnu", "musl"
ABI string `json:"abi,omitempty"` // optional/future (e.g. "eabihf")
}
Target is the canonical semantic identity of a build target: OS, architecture, and (when it matters) the C library and ABI. This is the ONE target abstraction shared by every language engine — Go reads OS/Arch (and ignores Libc/ABI), Rust PROJECTS the same fields into a target triple. The triple is therefore a derivation of this identity, never stored here and never the primary key, so the abstraction stays language-neutral rather than quietly becoming Rust-centric.
Libc is "" for targets where it is irrelevant or default (every Go target today); it becomes load-bearing the moment musl enters ("linux/amd64" stops being a unique identity once both gnu and musl exist). The derived names (String, step ID, output path, archive name) append Libc only when set, so libc-less targets — i.e. all current Go builds — render byte-identically to before.
func ParseTarget ¶ added in v0.7.0
ParseTarget splits "os/arch" or "os/arch/libc" into a Target.
func ParseTargets ¶ added in v0.7.0
ParseTargets parses a slice of "os/arch[/libc]" strings.
type TargetSkip ¶ added in v0.7.0
TargetSkip records a registry target excluded at plan time and the matcher's reason. It is narrated so a "built but not distributed" outcome explains itself rather than looking like a bug. The Reason comes from the eligibility decision (config.MatchResult), never re-derived by a caller.
type UniversalStep ¶ added in v0.4.0
type UniversalStep struct {
BuildID string `json:"build_id"` // which build config this belongs to
StepID string `json:"step_id"` // unique: {build_id}-{variant}-{os}-{arch}
Engine string `json:"engine"` // "image" | "binary-go" | "binary-rust" — the dispatch key
Target Target `json:"target"`
Inputs []ArtifactRef `json:"inputs,omitempty"`
Outputs []ArtifactRef `json:"outputs,omitempty"`
Meta StepMeta `json:"-"` // engine-specific typed metadata
}
UniversalStep is a single unit of work in a build plan. Both image and binary engines produce steps in this shape.
func (UniversalStep) MarshalJSON ¶ added in v0.4.0
func (s UniversalStep) MarshalJSON() ([]byte, error)
MarshalJSON encodes UniversalStep with Meta as a typed JSON object.
type UniversalStepResult ¶ added in v0.4.0
type UniversalStepResult struct {
Artifacts []ProducedArtifact `json:"artifacts"`
Metadata map[string]string `json:"metadata,omitempty"` // e.g., {"toolchain": "go1.24.1"}
Metrics StepMetrics `json:"metrics"`
}
UniversalStepResult is what an engine returns after executing a single step.
type VersionInfo ¶
type VersionInfo = gitver.VersionInfo
VersionInfo is an alias for backward compatibility.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package contributors holds the build-strategy contributors that supply rows into a perform run's domains.
|
Package contributors holds the build-strategy contributors that supply rows into a perform run's domains. |
|
Package domains makes a perform run a single domain-ordered narrative.
|
Package domains makes a perform run a single domain-ordered narrative. |
|
Package engines contains all built-in build engines.
|
Package engines contains all built-in build engines. |