Documentation
¶
Index ¶
- Constants
- func All() []string
- func AllV2() []string
- func BuildOrder(builds []config.BuildConfig) ([]config.BuildConfig, error)
- func ChecksumFile(path string) (string, error)
- func DetectProvider(registryURL string) string
- func DetectVersion(rootDir string) (*gitver.VersionInfo, error)
- func EnsureCrucibleAllowed(rootDir string) error
- func EnvFingerprint() string
- func FormatLayerInstruction(e LayerEvent) string
- func FormatLayerTiming(e LayerEvent) string
- func GenerateCrucibleRunID() string
- func InjectLabels(plan *BuildPlan, labels map[string]string)
- func IsCrucibleChild() bool
- func NormalizeBuildPlan(plan *BuildPlan) string
- func Register(name string, constructor func() Engine)
- func RegisterV2(name string, constructor func() EngineV2)
- func ResolveTags(templates []string, v *gitver.VersionInfo) []string
- func ResolveTemplate(tmpl string, v *gitver.VersionInfo) string
- func SlugifyBuildID(id string) string
- func StandardLabels(planHash, sfVersion, commit, mode, createdRFC3339 string) map[string]string
- func StepIDForPlatform(buildID string, p Platform) string
- func TruncHash(s string) string
- func TrustLevelLabel(level string) string
- func ValidateBuildGraph(steps []UniversalStep) error
- func WriteChecksums(outputDir string, archives []*ArchiveResult) (string, error)
- func WriteDSSEProvenance(path string, stmt ProvenanceStatement) error
- func WriteProvenance(path string, stmt ProvenanceStatement) error
- type ArchiveOpts
- type ArchiveResult
- type ArtifactRef
- type BuildConfig
- type BuildPlan
- type BuildResult
- type BuildStep
- type Capabilities
- 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 Platform
- type ProducedArtifact
- type ProvenanceBuilder
- type ProvenanceInvocation
- type ProvenanceMaterial
- type ProvenanceMetadata
- type ProvenancePredicate
- type ProvenanceStatement
- type ProvenanceSubject
- type RegistryTarget
- type Stage
- type StepMeta
- type StepMetrics
- type StepResult
- 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" LabelBuildMode = "org.stagefreight.build.mode" LabelPlanHash = "org.stagefreight.plan.sha256" )
Standard OCI label keys emitted by StageFreight on every build.
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 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 ¶
func DetectVersion(rootDir string) (*gitver.VersionInfo, error)
DetectVersion delegates to the gitver package.
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 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 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, SavePath (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 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 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 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 StepIDForPlatform ¶ added in v0.4.0
StepIDForPlatform builds a deterministic step ID. Format: {buildID}-{variant}-{os}-{arch} (variant slot reserved, empty for now).
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 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 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
// Platform is the target platform for this archive.
Platform Platform
// 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.
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 BuildConfig ¶ added in v0.4.0
type BuildConfig struct {
ID string
Kind string
Platforms []Platform
BuildMode string
SelectTags []string
DependsOn string
// Version info for template resolution
Version *VersionInfo
// 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
}
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
Target string
Platforms []string
BuildArgs 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
SavePath string // save image tarball here after build (for security scanning)
MetadataFile string // temp file for buildx --metadata-file (digest capture)
}
BuildStep is a single build invocation.
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 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)
Execute(ctx context.Context, plan *BuildPlan) (*BuildResult, 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)
}
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 Platform ¶ added in v0.4.0
Platform is a normalized os/arch pair.
func ParsePlatform ¶ added in v0.4.0
ParsePlatform splits "os/arch" into a Platform.
func ParsePlatforms ¶ added in v0.4.0
ParsePlatforms parses a slice of "os/arch" strings.
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 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)
}
RegistryTarget is a resolved registry push destination.
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
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 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"
Platform Platform `json:"platform"`
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.