builder

package
v0.51.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const ConfigFileName = "unikernel.toml"
View Source
const UnignoreFile = ".unignore"

Variables

View Source
var DefaultIgnorePatterns = []string{
	".git",
	".jerboa-build",
	"node_modules",
	"__pycache__",
	".tox",
	"venv",
	".venv",
	"dist",
	".next",
	"target",
}

DefaultIgnorePatterns are the patterns always excluded from the build context.

Functions

func CacheKey

func CacheKey(dir string, lang Lang, entrypoint string, extraFiles []string) (string, error)

CacheKey computes a deterministic hash from the source directory and options. It walks the directory, hashes every non-ignored file, and combines with the language and entrypoint.

Types

type BuildCache

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

BuildCache stores source hashes to skip redundant builds. Cache entries live in <storeDir>/<cacheKey>.json.

func NewBuildCache

func NewBuildCache(dir string) (*BuildCache, error)

NewBuildCache creates a BuildCache rooted at dir.

func (*BuildCache) Get

func (bc *BuildCache) Get(key string) (*CacheEntry, error)

Get reads a cache entry. Returns nil if not found.

func (*BuildCache) Has

func (bc *BuildCache) Has(key string) bool

Has checks whether a cache entry exists for the given key.

func (*BuildCache) Store

func (bc *BuildCache) Store(entry CacheEntry) error

Store writes a cache entry.

type BuildConfig

type BuildConfig struct {
	Lang       string   `toml:"lang"`
	Entrypoint string   `toml:"entrypoint"`
	Args       []string `toml:"args"`
	// Run lists shell commands to execute before the language driver packages the project.
	// Equivalent to RUN instructions in a Dockerfile — use for build steps like
	// "npm run build", "nuxt build", "python manage.py collectstatic", etc.
	Run []string `toml:"run"`
	// DiskSize sets the minimum image file size passed to mkfs (e.g. "512M", "1G").
	// Use when the default content-based image size leaves insufficient free space
	// for runtime writes (e.g. database temp tablespaces, log files).
	DiskSize string `toml:"disk_size"`
	// Dirs lists absolute directories to create (empty) inside the image —
	// analogous to a Dockerfile's mkdir/VOLUME. Use for volume mount points (a
	// TFS volume can only be mounted onto a directory that already exists in the
	// root image) and for scratch paths the program writes to at runtime.
	Dirs []string `toml:"dirs"`
}

type BuildResult

type BuildResult struct {
	// BinaryPath is the path to the compiled ELF binary.
	// For interpreted languages (Node, Python), this may be empty and
	// SourceDir should be used instead.
	BinaryPath string
	// SourceDir is the directory containing the application source files
	// to include in the image (used for interpreted languages).
	SourceDir string
	// Entrypoint is the command or script that should be used as the program entrypoint.
	Entrypoint string
	// Packages lists language runtime packages that should be included in the image
	// (e.g. "node:20" for Node.js projects).
	Packages []string
	// Env holds runtime environment variables required by this build (e.g. PYTHONPATH
	// when pip installed packages into a non-default directory).
	Env map[string]string
}

BuildResult holds the output of a successful language build.

type CacheEntry

type CacheEntry struct {
	Key         string `json:"key"`
	ImageDigest string `json:"image_digest"`
	SourceDir   string `json:"source_dir"`
	Lang        string `json:"lang"`
}

CacheEntry records the result of a previous build.

type Config

type Config struct {
	Build   BuildConfig   `toml:"build"`
	Run     RunConfig     `toml:"run"`
	Env     EnvConfig     `toml:"env"`
	Program ProgramConfig `toml:"program"`
	Stages  []StageConfig `toml:"stages"`
}

func LoadConfig

func LoadConfig(dir string) (*Config, error)

func LoadConfigFile added in v0.51.0

func LoadConfigFile(path string) (*Config, error)

LoadConfigFile loads a config from an explicit file path (the -f/--file flag). Unlike LoadConfig, a missing file is an error: the user named a specific file.

func (*Config) HasStages

func (c *Config) HasStages() bool

HasStages returns true if the config defines multi-stage build stages.

func (*Config) LangHint

func (c *Config) LangHint() Lang

type CopyFromConfig

type CopyFromConfig struct {
	// Stage is the name of the source stage.
	Stage string `toml:"stage"`
	// Src is the file path within the source stage's build output.
	Src string `toml:"src"`
	// Dst is the destination path in the current stage (defaults to Src basename).
	Dst string `toml:"dst"`
}

CopyFromConfig describes a file to copy from a previous build stage.

type Driver

type Driver interface {
	// Detect checks whether the given directory contains a project of this language.
	// Returns true if the language markers are found.
	Detect(dir string) bool

	// Build compiles the project in dir and returns the path to the resulting binary.
	Build(ctx context.Context, dir string, opts Options) (BuildResult, error)

	// Lang returns the language this driver builds.
	Lang() Lang
}

Driver is the interface that each language builder must implement.

func AvailableDrivers

func AvailableDrivers() []Driver

AvailableDrivers returns all registered build drivers.

func GetDriver

func GetDriver(lang Lang) (Driver, error)

GetDriver returns the Driver for the given language, or an error if unavailable.

type EnvConfig

type EnvConfig map[string]string

type GoDriver

type GoDriver struct{}

GoDriver builds Go projects into static ELF binaries.

func (*GoDriver) Build

func (g *GoDriver) Build(ctx context.Context, dir string, opts Options) (BuildResult, error)

Build compiles a Go project with CGO_ENABLED=0 and returns the binary path.

func (*GoDriver) Detect

func (g *GoDriver) Detect(dir string) bool

Detect checks for go.mod in dir.

func (*GoDriver) Lang

func (g *GoDriver) Lang() Lang

Lang returns LangGo.

type IgnoreMatcher

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

IgnoreMatcher determines whether a file should be excluded from the build context.

func LoadIgnoreFile

func LoadIgnoreFile(dir string) (*IgnoreMatcher, error)

LoadIgnoreFile reads a .unignore file and returns a matcher. If the file does not exist, returns a matcher with default patterns only.

func NewIgnoreMatcher

func NewIgnoreMatcher(patterns []string) *IgnoreMatcher

NewIgnoreMatcher creates a matcher from the given patterns. Patterns follow .gitignore syntax: lines starting with ! negate, lines starting with # are comments, trailing / matches directories only.

func (*IgnoreMatcher) Match

func (m *IgnoreMatcher) Match(relPath string, isDir bool) bool

Match returns true if relPath should be excluded from the build context. relPath should be a forward-slash-separated path relative to the project root. Patterns are evaluated in order; a later "!pattern" re-includes a path excluded by an earlier pattern (gitignore-style negation).

type Lang

type Lang int

Lang represents a programming language supported by the build system.

const (
	// LangUnknown indicates the language could not be determined.
	LangUnknown Lang = iota
	// LangGo indicates a Go project.
	LangGo
	// LangNode indicates a Node.js project.
	LangNode
	// LangPython indicates a Python project.
	LangPython
	// LangRust indicates a Rust project.
	LangRust
	// LangRaw indicates a generic, driver-agnostic build (see RawDriver).
	LangRaw
)

func DetectLanguage

func DetectLanguage(dir string, langHint Lang) (Lang, error)

DetectLanguage inspects dir and returns the language detected. If multiple markers exist and langHint is non-zero, langHint takes precedence. Returns LangUnknown and an error if detection is ambiguous and no hint is given.

func ParseLang

func ParseLang(s string) (Lang, error)

ParseLang parses a language string (case-insensitive) into a Lang.

func (Lang) String

func (l Lang) String() string

String returns the human-readable name of the language.

type NodeDriver

type NodeDriver struct{}

NodeDriver builds Node.js projects into unikernel images.

func (*NodeDriver) Build

func (n *NodeDriver) Build(ctx context.Context, dir string, opts Options) (BuildResult, error)

Build runs npm install and returns the source directory with node entrypoint. The result includes Packages=["node:20"] so the caller can resolve the Node runtime.

func (*NodeDriver) Detect

func (n *NodeDriver) Detect(dir string) bool

Detect checks for package.json in dir.

func (*NodeDriver) Lang

func (n *NodeDriver) Lang() Lang

Lang returns LangNode.

type Options

type Options struct {
	// Entrypoint overrides the default entrypoint for the language (e.g. "cmd/server/main.go" for Go).
	Entrypoint string
	// BuildArgs are extra arguments passed to the language build tool.
	BuildArgs []string
	// Env is additional environment variables for the build process.
	Env []string
	// PkgFiles are pre-resolved package file paths to include in the image.
	PkgFiles []string
	// Platform is the target platform for cross-compilation. Defaults to the current platform.
	Platform Platform
	// Output is where subprocess output (compiler, package manager, etc.) is written.
	// If nil, defaults to os.Stderr.
	Output io.Writer
}

Options contains language-independent build options passed to every driver.

type Platform

type Platform struct {
	OS   string
	Arch string
}

Platform represents a target OS/architecture for building.

func DefaultPlatform

func DefaultPlatform() Platform

DefaultPlatform returns the current runtime platform.

func KnownPlatforms

func KnownPlatforms() []Platform

KnownPlatforms returns all supported platforms.

func ParsePlatform

func ParsePlatform(s string) (Platform, error)

ParsePlatform parses a string in "os/arch" format into a Platform.

func (Platform) GoCrossCompileEnv

func (p Platform) GoCrossCompileEnv() []string

GoCrossCompileEnv returns environment variables for cross-compiling Go binaries to this platform. CGO_ENABLED=0 is always set for static builds.

func (Platform) GoEnv

func (p Platform) GoEnv() (goos, goarch string)

GoEnv returns the GOOS and GOARCH values for the platform.

func (Platform) IsNative

func (p Platform) IsNative() bool

IsNative returns true if the platform matches the current runtime.

func (Platform) RustTarget

func (p Platform) RustTarget() string

RustTarget returns the Rust target triple for the platform.

func (Platform) String

func (p Platform) String() string

String returns the platform in os/arch format (e.g. "linux/amd64").

type ProgramConfig

type ProgramConfig struct {
	Path string   `toml:"path"`
	Args []string `toml:"args"`
}

ProgramConfig declares the runtime entrypoint for lang = "raw" builds — analogous to Docker's ENTRYPOINT (Path) + CMD (Args). Path is resolved against the package files supplied via --pkg; Args are passed through literally as the program's argv[1..].

type PythonDriver

type PythonDriver struct{}

PythonDriver builds Python projects into unikernel images.

func (*PythonDriver) Build

func (p *PythonDriver) Build(ctx context.Context, dir string, opts Options) (BuildResult, error)

Build installs Python dependencies and returns the source directory with the python runtime package. The result includes Packages=["python:3.12"] so the caller can resolve the Python runtime.

func (*PythonDriver) Detect

func (p *PythonDriver) Detect(dir string) bool

Detect checks for pyproject.toml or requirements.txt in dir.

func (*PythonDriver) Lang

func (p *PythonDriver) Lang() Lang

Lang returns LangPython.

type RawDriver

type RawDriver struct{}

RawDriver is a language-agnostic build mode for runtimes without a dedicated driver (Java, .NET, Ruby, PHP, ...). It performs no compilation itself — [build] run handles build steps, and [program] in unikernel.toml names the runtime binary (resolved from --pkg files) and its arguments. Never auto-detected; opt-in via lang = "raw".

func (*RawDriver) Build

func (r *RawDriver) Build(ctx context.Context, dir string, opts Options) (BuildResult, error)

Build returns dir as the source directory, deferring all program/argument resolution to the caller's [program] handling.

func (*RawDriver) Detect

func (r *RawDriver) Detect(dir string) bool

Detect always returns false — raw mode is opt-in only.

func (*RawDriver) Lang

func (r *RawDriver) Lang() Lang

Lang returns LangRaw.

type RunConfig

type RunConfig struct {
	Memory string   `toml:"memory"`
	CPUs   int      `toml:"cpus"`
	Ports  []string `toml:"ports"`
}

type RustDriver

type RustDriver struct{}

RustDriver builds Rust projects into static ELF binaries via cross-compilation.

func (*RustDriver) Build

func (r *RustDriver) Build(ctx context.Context, dir string, opts Options) (BuildResult, error)

Build compiles a Rust project into a static ELF binary using `cargo build --release --target x86_64-unknown-linux-musl`. Requires the musl target to be installed: `rustup target add x86_64-unknown-linux-musl`.

func (*RustDriver) Detect

func (r *RustDriver) Detect(dir string) bool

Detect checks for Cargo.toml in dir.

func (*RustDriver) Lang

func (r *RustDriver) Lang() Lang

Lang returns LangRust.

type StageConfig

type StageConfig struct {
	// Name is the stage identifier (required). Referenced by CopyFrom.
	Name string `toml:"name"`
	// Lang is the build language for this stage (e.g. "go", "node").
	Lang string `toml:"lang"`
	// Entrypoint overrides the default entrypoint for the language.
	Entrypoint string `toml:"entrypoint"`
	// Args are extra arguments passed to the build tool.
	Args []string `toml:"args"`
	// CopyFrom lists artifacts to copy from other stages.
	CopyFrom []CopyFromConfig `toml:"copy_from"`
}

StageConfig defines a build stage in a multi-stage unikernel.toml. Each stage can use a different language and copy artifacts from a previous stage into the final image.

Jump to

Keyboard shortcuts

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