Documentation
¶
Overview ¶
Package dockerfile provides a parser and builder for converting Dockerfiles into cc.InstanceSource objects. It enables building VM images directly from Dockerfiles without external Docker tooling.
The package supports a subset of Dockerfile syntax:
- FROM image[:tag] [AS name]
- RUN command (shell form) or RUN ["executable", "arg1", ...] (exec form)
- COPY [--chown=user:group] src... dst
- ADD src... dst (local files only, no URL or archive extraction)
- ENV key=value ...
- WORKDIR /path
- ARG name[=default]
- USER user[:group]
- EXPOSE port[/protocol] ...
- LABEL key=value ...
- CMD command or CMD ["executable", "arg1", ...]
- ENTRYPOINT command or ENTRYPOINT ["executable", "arg1", ...]
- SHELL ["executable", "arg1", ...]
- STOPSIGNAL signal
- Heredoc syntax in RUN commands (e.g., RUN cat > /file <<'EOF')
Unsupported features (v1):
- Multi-stage builds (COPY --from=stage)
- ADD with URLs or archive extraction
- Docker BuildKit heredoc for COPY/ADD (COPY <<EOF /path)
- HEALTHCHECK
- ONBUILD
- VOLUME
Example usage:
dockerfile := []byte(`
FROM alpine:3.19
RUN apk add --no-cache curl
COPY app /usr/local/bin/
CMD ["app"]
`)
source, err := cc.BuildDockerfileSource(ctx, dockerfile,
cc.WithBuildContext(dirContext),
cc.WithDockerfileCacheDir(cacheDir),
)
if err != nil {
log.Fatal(err)
}
inst, err := cc.New(source)
Index ¶
- Constants
- Variables
- func DefaultShell() []string
- func ExpandVariables(s string, vars map[string]string) (string, error)
- func ExpandVariablesPreserve(s string, vars map[string]string) (string, error)
- func SanitizeErrorMessage(msg string) string
- func ValidateDestPath(path string) error
- func ValidateDockerfileSize(data []byte) error
- func ValidatePath(contextRoot, path string) error
- type BuildContext
- type BuildError
- type BuildResult
- type Builder
- type Cmd
- type DirBuildContext
- type Dockerfile
- type FSLayerOp
- type FromInstruction
- type Instance
- type Instruction
- type InstructionKind
- type KeyValue
- type ParseError
- type PathTraversalError
- type RuntimeConfig
- type Stage
- type UnsupportedError
Constants ¶
const ( MaxDockerfileSize = 1 << 20 // 1MB MaxLineLength = 1 << 20 // 1MB MaxInstructionCount = 1000 MaxVariableCount = 100 MaxVariableExpansion = 10 // Maximum recursion depth for variable expansion )
Security limit constants.
Variables ¶
var ( ErrDockerfileTooLarge = errors.New("dockerfile exceeds maximum size") ErrTooManyInstructions = errors.New("dockerfile exceeds maximum instruction count") ErrTooManyVariables = errors.New("dockerfile exceeds maximum variable count") ErrVariableExpansionLoop = errors.New("variable expansion loop or depth exceeded") ErrPathTraversal = errors.New("path escapes build context") ErrInvalidPath = errors.New("invalid path") ErrMissingFrom = errors.New("dockerfile must start with FROM instruction") ErrUnsupportedInstruction = errors.New("unsupported instruction") )
Sentinel errors for security violations.
Functions ¶
func DefaultShell ¶
func DefaultShell() []string
DefaultShell returns the default shell used for shell-form RUN commands.
func ExpandVariables ¶
ExpandVariables expands variables in a string using the provided map. Undefined variables are expanded to empty string (Docker behavior for ENV, COPY, etc). This is the public entry point.
func ExpandVariablesPreserve ¶
ExpandVariablesPreserve expands variables in a string, but leaves undefined variables as-is. This is used for RUN commands where shell variables should be passed through to the shell for expansion.
func SanitizeErrorMessage ¶
SanitizeErrorMessage removes potentially sensitive information from error messages.
func ValidateDestPath ¶
ValidateDestPath validates a destination path inside the container.
func ValidateDockerfileSize ¶
ValidateDockerfileSize checks that the input doesn't exceed the maximum size.
func ValidatePath ¶
ValidatePath ensures a path stays within the context root. It prevents path traversal attacks via ".." components.
Types ¶
type BuildContext ¶
type BuildContext interface {
// Open opens a file for reading.
Open(path string) (io.ReadCloser, error)
// Stat returns file info for a path.
Stat(path string) (os.FileInfo, error)
// Root returns the context root path (for validation).
Root() string
}
BuildContext provides access to files during COPY/ADD operations.
type BuildError ¶
type BuildError struct {
Op string // Operation that failed (e.g., "COPY", "RUN")
Line int // Line number
Message string // Error description
Err error // Underlying error
}
BuildError represents an error during Dockerfile building (after parsing).
func (*BuildError) Error ¶
func (e *BuildError) Error() string
func (*BuildError) Unwrap ¶
func (e *BuildError) Unwrap() error
type BuildResult ¶
type BuildResult struct {
// Ops contains the filesystem layer operations to execute.
Ops []FSLayerOp
// ImageRef is the base image reference from FROM.
ImageRef string
// RuntimeConfig contains CMD, ENTRYPOINT, USER, etc.
RuntimeConfig RuntimeConfig
// Env contains accumulated environment variables.
Env []string
// WorkDir contains the final working directory.
WorkDir string
}
BuildResult contains the result of building a Dockerfile.
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder converts a parsed Dockerfile into filesystem layer operations.
func NewBuilder ¶
func NewBuilder(df *Dockerfile) *Builder
NewBuilder creates a new Builder for the given Dockerfile.
func (*Builder) Build ¶
func (b *Builder) Build() (*BuildResult, error)
Build converts the Dockerfile into filesystem layer operations.
func (*Builder) ResolveImageRef ¶
ResolveImageRef resolves the FROM image reference using build args. This can be called before Build() to determine which image to pull, so the caller can extract the base image's environment.
func (*Builder) WithBaseImageEnv ¶
WithBaseImageEnv sets the environment from the base image. This allows ENV instructions to reference variables from the base image (e.g., ENV PATH="$PATH:/opt/bin").
func (*Builder) WithBuildArg ¶
WithBuildArg sets a build argument value.
func (*Builder) WithContext ¶
func (b *Builder) WithContext(ctx BuildContext) *Builder
WithContext sets the build context for COPY/ADD operations.
type Cmd ¶
type Cmd interface {
Run() error
SetEnv(env []string) Cmd
SetDir(dir string) Cmd
SetUser(user string) Cmd
}
Cmd is a minimal interface for command execution.
type DirBuildContext ¶
type DirBuildContext struct {
// contains filtered or unexported fields
}
DirBuildContext implements BuildContext using a directory.
func NewDirBuildContext ¶
func NewDirBuildContext(root string) (*DirBuildContext, error)
NewDirBuildContext creates a BuildContext from a directory path.
func (*DirBuildContext) Open ¶
func (c *DirBuildContext) Open(path string) (io.ReadCloser, error)
func (*DirBuildContext) Root ¶
func (c *DirBuildContext) Root() string
type Dockerfile ¶
type Dockerfile struct {
Stages []Stage // Build stages (at least one)
Args []KeyValue // Global ARGs declared before first FROM
}
Dockerfile represents a complete parsed Dockerfile.
func Parse ¶
func Parse(data []byte) (*Dockerfile, error)
Parse parses a Dockerfile from its byte content.
type FSLayerOp ¶
FSLayerOp represents an operation in the filesystem snapshot factory. This mirrors api.FSLayerOp to avoid circular imports.
type FromInstruction ¶
type FromInstruction struct {
Image string // Image reference after variable expansion
ImageTemplate string // Original image reference before expansion (may contain $VAR)
Tag string // Tag portion if separated (empty if included in Image)
Alias string // Stage alias from "AS name"
Platform string // Platform from --platform flag
}
FromInstruction holds parsed FROM instruction details.
type Instance ¶
type Instance interface {
CommandContext(ctx context.Context, name string, args ...string) Cmd
WriteFile(name string, data []byte, perm fs.FileMode) error
Stat(name string) (fs.FileInfo, error)
}
Instance is a minimal interface for executing commands and writing files. This mirrors the api.Instance interface to avoid circular imports.
type Instruction ¶
type Instruction struct {
Kind InstructionKind
Line int // Source line number (1-indexed)
Original string // Original instruction text
Args []string // Parsed arguments
Flags map[string]string // Flags like --from, --chown, etc.
}
Instruction represents a single parsed Dockerfile instruction.
type InstructionKind ¶
type InstructionKind int
InstructionKind identifies the type of Dockerfile instruction.
const ( InstructionFrom InstructionKind = iota InstructionRun InstructionCopy InstructionAdd InstructionEnv InstructionWorkDir InstructionArg InstructionLabel InstructionUser InstructionExpose InstructionCmd InstructionEntrypoint InstructionShell InstructionStopSignal )
func (InstructionKind) String ¶
func (k InstructionKind) String() string
type ParseError ¶
type ParseError struct {
Line int // Line number (1-indexed, 0 if not applicable)
Message string // Error description
Hint string // Optional hint for fixing the error
}
ParseError represents an error during Dockerfile parsing.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
type PathTraversalError ¶
PathTraversalError indicates a path that escapes the build context.
func (*PathTraversalError) Error ¶
func (e *PathTraversalError) Error() string
func (*PathTraversalError) Is ¶
func (e *PathTraversalError) Is(target error) bool
type RuntimeConfig ¶
type RuntimeConfig struct {
Cmd []string // CMD instruction
Entrypoint []string // ENTRYPOINT instruction
User string // USER instruction
ExposePorts []string // EXPOSE instructions (e.g., "80/tcp")
Labels map[string]string // LABEL instructions
Shell []string // SHELL instruction (default: ["/bin/sh", "-c"])
StopSignal string // STOPSIGNAL instruction (e.g., "SIGTERM")
}
RuntimeConfig holds metadata from CMD, ENTRYPOINT, USER, EXPOSE, LABEL, SHELL, STOPSIGNAL. This metadata does not affect the filesystem but may be used by the runtime.
type Stage ¶
type Stage struct {
Name string // Stage name from "AS name" (empty if unnamed)
From FromInstruction
Instructions []Instruction
}
Stage represents a build stage in a Dockerfile.
type UnsupportedError ¶
type UnsupportedError struct {
Feature string // Description of the unsupported feature
Line int // Line number where it was encountered
}
UnsupportedError indicates an unsupported Dockerfile feature.
func (*UnsupportedError) Error ¶
func (e *UnsupportedError) Error() string
func (*UnsupportedError) Is ¶
func (e *UnsupportedError) Is(target error) bool