### Get Metadata String Representation Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Returns a formatted string containing process and buildpack information. ```go func (m Metadata) String() string ``` -------------------------------- ### Get string representation of version in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Returns the version formatted as a major.minor string. ```go v := api.MustParse("0.12") fmt.Println(v.String()) // Output: 0.12 ``` -------------------------------- ### Log Contextual Information Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/log.md Example of including dynamic context in log messages using formatted strings. ```go logger.Infof("Restoring layer %s from cache", layerID) ``` -------------------------------- ### Get Default Action Type Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/env.md Retrieves the default action for environment files lacking a suffix. ```go action := env.DefaultActionType(api.MustParse("0.12")) // Returns ActionTypeOverride ``` -------------------------------- ### Get Cache Name Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/cache.md Retrieve the reference string for the cache image. ```go fmt.Println(cache.Name()) // Output: gcr.io/my-project/cache ``` -------------------------------- ### Digest Format Example Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/layers.md Standard format for digest strings returned by the lifecycle functions. ```text sha256:hexadecimal... ``` -------------------------------- ### Get Metadata File Path in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Constructs the absolute path to the metadata.toml file based on the provided layers directory. ```go metaPath := launch.GetMetadataFilePath("/workspace/layers") // Output: /workspace/layers/config/metadata.toml ``` -------------------------------- ### Environment Configuration Workflow Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/env.md Demonstrates initializing environment variables, adding directory paths, and applying overrides. ```go import ( "github.com/buildpacks/lifecycle/env" ) // Create environment from initial vars initialEnv := map[string]string{ "PATH": "/usr/bin", "LANG": "en_US.UTF-8", } envVars := env.NewVars(initialEnv, false) buildEnv := &env.Env{ RootDirMap: map[string][]string{ "bin": {"PATH"}, "lib": {"LD_LIBRARY_PATH", "LIBRARY_PATH"}, }, Vars: envVars, } // Add app directory paths buildEnv.AddRootDir("/app") // Add buildpack environment files buildEnv.AddEnvDir("/cnb/buildpack/env", env.DefaultActionType(apiVersion)) // Apply platform and build config overrides finalEnv, err := buildEnv.WithOverrides("/platform", "/cnb/build-config") if err != nil { log.Fatal(err) } // Use final environment for buildpack execution for _, varAssignment := range finalEnv { fmt.Println(varAssignment) } ``` -------------------------------- ### Initialize Image Handlers in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Demonstrates how to initialize different types of image handlers based on the provided configuration parameters. ```go // Remote registry with auth handler := image.NewHandler(nil, keychain, "", false, []string{}) img, err := handler.InitImage("gcr.io/my-project/app") // Docker daemon handler := image.NewHandler(dockerClient, nil, "", false, []string{}) img, err := handler.InitImage("localhost:5000/app") // OCI layout handler := image.NewHandler(nil, nil, "/tmp/image-layout", true, []string{}) img, err := handler.InitImage("ubuntu:latest") // If no configuration matches handler := image.NewHandler(nil, nil, "", false, []string{}) // handler is nil ``` -------------------------------- ### Structured Logging with apex/log Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/log.md Demonstrates how to create a log entry with fields and handle it using the logger interface. ```go import "github.com/apex/log" // Log entry with fields entry := &log.Entry{ Message: "Processing buildpack", Fields: log.Fields{ "buildpack_id": "org.buildpack/nodejs", "version": "1.0.0", }, } if handler, ok := logger.(log.LoggerHandlerWithLevel); ok { handler.HandleLog(entry) } ``` -------------------------------- ### Build All Lifecycle Components Source: https://github.com/buildpacks/lifecycle/blob/main/DEVELOPMENT.md Run this command to test, build, and package all lifecycle binaries. Archives will be created in the `out/` directory. ```bash $ make all ``` -------------------------------- ### Get Process Path in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Retrieves the absolute path for a specific process type symlink. ```go path := launch.ProcessPath("web") // Returns path like "/layers/config/procmgr/web" ``` -------------------------------- ### Create Tar Archive with Lifecycle Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/archive.md Demonstrates the standard pattern for initializing a tar writer and adding directories to an archive using the lifecycle archive package. ```go import ( "archive/tar" "os" "github.com/buildpacks/lifecycle/archive" ) func createArchive(outputPath string, sourceDirs ...string) error { // Create output tar file tarFile, err := os.Create(outputPath) if err != nil { return err } defer tarFile.Close() // Create tar writer tw := tar.NewWriter(tarFile) defer tw.Close() // Add directories for _, dir := range sourceDirs { if err := archive.AddDirToArchive(tw, dir); err != nil { return err } } return tw.Close() } // Usage if err := createArchive("output.tar", "/app", "/config"); err != nil { log.Fatal(err) } ``` -------------------------------- ### Create a new Platform instance Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Initializes a Platform instance for a specific API version. ```go platform := platform.NewPlatformFor("0.15") inputs := platform.Inputs() ``` -------------------------------- ### Basic Logging in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/log.md Demonstrates standard logging methods for different severity levels using the lifecycle logger. ```go import "github.com/buildpacks/lifecycle/log" // Create or receive a logger var logger log.Logger // Log at different levels logger.Debug("Detailed information for debugging") logger.Info("General informational message") logger.Warn("Warning that something may be wrong") logger.Error("Error occurred during execution") ``` -------------------------------- ### Perform typical cache workflow Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/cache.md Demonstrates the lifecycle of cache operations: initializing the cache, retrieving metadata, reusing existing layers, adding new layers, and committing changes. ```go // Create cache from image reference cacheImg, err := cache.NewImageCacheFromName( "gcr.io/my-project/cache", keychain, logger, imageDeleter, ) if err != nil { log.Fatal(err) } // Retrieve previous cache metadata metadata, err := cacheImg.RetrieveMetadata() if err != nil { log.Fatal(err) } // For unchanged layers, reuse from cache for _, layer := range metadata.Layers { err := cacheImg.ReuseLayer(layer.SHA) if err != nil { // Layer not available or corrupted, rebuild it } } // Add newly built layers err = cacheImg.AddLayerFile("/tmp/layer.tar", "sha256:newlayer...") if err != nil { log.Fatal(err) } // Save updated cache err = cacheImg.Commit() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Run All Tests Source: https://github.com/buildpacks/lifecycle/blob/main/DEVELOPMENT.md Execute this command to format, vet, and test the code. This is a comprehensive test suite for the project. ```bash $ make test ``` -------------------------------- ### Initialize Image from OCI Layout Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Initializes an image from a specified OCI image layout directory. ```go handler := &image.LayoutHandler{layoutDir: "/tmp/layout"} img, err := handler.InitImage("myapp") ``` -------------------------------- ### Initialize VolumeCache from directory Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/cache.md Creates a VolumeCache instance pointing to a specific absolute directory path. ```go volCache := cache.NewVolumeCache("/var/cache/buildpacks") ``` -------------------------------- ### Initialize OCI Layout Image Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Configures the handler to target an OCI layout directory. ```go handler := image.NewHandler(nil, nil, "/tmp/oci-layout", true, []string{}) img, err := handler.InitImage("myapp:latest") ``` -------------------------------- ### Configure a launch process in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Defines a process type and associates it with a platform API version for metadata serialization. ```go // Create a process proc := launch.Process{ Type: "web", Command: launch.NewRawCommand([]string{"npm", "start"}), Direct: false, Default: true, BuildpackID: "org.buildpack/nodejs", } // Set platform API version (required for serialization) platformAPI := api.MustParse("0.15") proc = proc.WithPlatformAPI(platformAPI) // Use in metadata metadata := launch.Metadata{ Processes: []launch.Process{proc}, } ``` -------------------------------- ### Initialize Image from Docker Daemon Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Initializes an image from the local Docker daemon using a provided client. ```go handler := &image.LocalHandler{docker: dockerClient} img, err := handler.InitImage("gcr.io/my-project/app") ``` -------------------------------- ### Initialize Remote Registry Image with Auth Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Uses the default keychain for authentication when interacting with a remote registry. ```go keychain := authn.DefaultKeychain handler := image.NewHandler(nil, keychain, "", false, []string{}) img, err := handler.InitImage("gcr.io/my-project/app:latest") if err != nil { log.Fatal(err) } defer img.Save() ``` -------------------------------- ### Initialize Docker Daemon Image Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Configures the handler to use a local Docker daemon client. ```go dockerClient, err := client.NewClientWithOpts(client.FromEnv) if err != nil { log.Fatal(err) } handler := image.NewHandler(dockerClient, nil, "", false, []string{}) img, err := handler.InitImage("my-app:latest") ``` -------------------------------- ### Create a RawCommand in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Initializes a RawCommand instance using a slice of command strings. ```go cmd := launch.NewRawCommand([]string{"/bin/bash", "-c", "npm start"}) ``` -------------------------------- ### Define Metadata structure Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Contains the collection of processes and contributing buildpacks for the launch context. ```go type Metadata struct { Processes []Process `toml:"processes" json:"processes"` Buildpacks []Buildpack `toml:"buildpacks" json:"buildpacks"` } ``` -------------------------------- ### LocalHandler.InitImage Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Initializes an image from the local Docker daemon. ```APIDOC ## LocalHandler.InitImage ### Description Initializes an image from Docker daemon. ### Signature `func (h *LocalHandler) InitImage(imageRef string) (imgutil.Image, error)` ### Returns - `imgutil.Image`: Initialized image - `error`: Error if initialization fails ### Example ```go handler := &image.LocalHandler{docker: dockerClient} img, err := handler.InitImage("gcr.io/my-project/app") ``` ``` -------------------------------- ### Build Lifecycle Binaries Source: https://github.com/buildpacks/lifecycle/blob/main/DEVELOPMENT.md This command builds the lifecycle binaries and places them in `out/linux/lifecycle/` and `out/windows/lifecycle/` directories. ```bash $ make build ``` -------------------------------- ### Build with pack CLI Source: https://github.com/buildpacks/lifecycle/blob/main/IMAGE.md Build an application using the pack CLI, specifying the lifecycle image. Replace and accordingly. ```bash pack build --lifecycle-image buildpacksio/lifecycle: ``` -------------------------------- ### Execute Creator Command Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/architecture.md Runs the full build pipeline by executing all phases in order. ```bash /cnb/lifecycle/creator [flags] ``` -------------------------------- ### Construct Lifecycle Inputs Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Creates inputs from environment variables and defaults. Call UpdatePlaceholderPaths() after initialization if using PlaceholderLayers. ```go platformAPI := api.MustParse("0.15") inputs := platform.NewLifecycleInputs(platformAPI) fmt.Println(inputs.AppDir) // Returns default or env value ``` -------------------------------- ### Format Version List as String Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Converts a list of versions into a string representation. ```go list := apis.Supported fmt.Println(list.String()) // Output: ["0.7", "0.8", "0.9"] ``` -------------------------------- ### Create a new layer with NewLayer Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/buildpack.md Initializes a new layer instance within the layers directory. ```go layersDir, _ := buildpack.ReadLayersDir("/workspace/layers", bp, logger) layer := layersDir.NewLayer("mydata", "0.12", logger) ``` -------------------------------- ### Build Lifecycle with Custom Version Source: https://github.com/buildpacks/lifecycle/blob/main/DEVELOPMENT.md Prepend `LIFECYCLE_VERSION=` to the `make all` command to specify a custom version for the build archives. ```bash $ LIFECYCLE_VERSION=1.2.3 make all ``` -------------------------------- ### Initialize ImageCache from image name Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/cache.md Creates an ImageCache instance from a registry reference, requiring authentication and registry configuration. ```go cache, err := cache.NewImageCacheFromName( "gcr.io/my-project/cache", keychain, logger, imageDeleter, "localhost:5000", ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Initialize Insecure Registry Image Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Allows communication with specified insecure registries by passing them in the insecure registries slice. ```go handler := image.NewHandler(nil, keychain, "", false, []string{"localhost:5000", "private.registry"}) img, err := handler.InitImage("localhost:5000/my-app:latest") ``` -------------------------------- ### Initialize Image from Remote Registry Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Initializes an image from a remote registry using configured keychain and insecure registry settings. ```go handler := &image.RemoteHandler{ keychain: keychain, insecureRegistries: []string{}, } img, err := handler.InitImage("gcr.io/my-project/app") ``` -------------------------------- ### NewPlatformFor Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Creates a new Platform instance for a specified Platform API version. ```APIDOC ## func NewPlatformFor(platformAPI string) *Platform ### Description Creates a Platform instance for a given Platform API version. ### Parameters - **platformAPI** (string) - Required - Platform API version (e.g., "0.15") ### Returns - ***Platform** - Platform with default lifecycle inputs and exiter ``` -------------------------------- ### Configure Lifecycle via Environment Variables Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/configuration.md Sets environment variables for operator configuration, build inputs, image locations, and caching before executing the creator binary. ```bash #!/bin/bash # Operator configuration export CNB_LOG_LEVEL=info export CNB_NO_COLOR=0 export CNB_USE_DAEMON=1 # Build inputs export CNB_APP_DIR=/workspace export CNB_LAYERS_DIR=/layers export CNB_PLATFORM_DIR=/platform export CNB_BUILD_CONFIG_DIR=/cnb/build-config export CNB_BUILDPACKS_DIR=/cnb/buildpacks # Images export CNB_BUILD_IMAGE=cnbs/sample-base/build:alpine export CNB_RUN_IMAGE=cnbs/sample-base/run:alpine export CNB_OUTPUT_IMAGE=localhost:5000/myapp:latest # Caching export CNB_CACHE_IMAGE=localhost:5000/myapp-cache:latest export CNB_PARALLEL_EXPORT=1 # Run the lifecycle /cnb/lifecycle/creator \ -app /workspace \ -cache-image localhost:5000/myapp-cache:latest \ -layers /layers \ -platform /platform \ localhost:5000/myapp:latest ``` -------------------------------- ### Configure Insecure Registry Options Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Generates remote options for image constructors to allow access to specified insecure registry hostnames. ```go opts := image.GetInsecureOptions([]string{"localhost:5000"}) img, err := remote.NewImage("localhost:5000/app", keychain, opts...) ``` -------------------------------- ### Initialize ImageCache with existing images Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/cache.md Creates an ImageCache instance using pre-initialized image objects. ```go origImg, _ := imageHandler.InitImage("gcr.io/my-project/cache") newImg, _ := imageHandler.InitImage("gcr.io/my-project/cache") cache := cache.NewImageCache(origImg, newImg, logger, deleter) ``` -------------------------------- ### RemoteHandler.InitImage Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Initializes an image from a remote registry. ```APIDOC ## RemoteHandler.InitImage ### Description Initializes an image from a remote registry using the handler's keychain and insecureRegistries configuration. ### Signature `func (h *RemoteHandler) InitImage(imageRef string) (imgutil.Image, error)` ### Returns - `imgutil.Image`: Initialized image - `error`: Error if initialization fails ### Error Conditions - Registry is not accessible - Registry is in insecureRegistries but TLS is not disabled - Authentication fails ### Example ```go handler := &image.RemoteHandler{ keychain: keychain, insecureRegistries: []string{}, } img, err := handler.InitImage("gcr.io/my-project/app") ``` ``` -------------------------------- ### LayoutHandler.InitImage Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Initializes an image from an OCI image layout. ```APIDOC ## LayoutHandler.InitImage ### Description Initializes an image from an OCI image layout. ### Signature `func (h *LayoutHandler) InitImage(imageRef string) (imgutil.Image, error)` ### Returns - `imgutil.Image`: Initialized image - `error`: Error if initialization fails ### Example ```go handler := &image.LayoutHandler{layoutDir: "/tmp/layout"} img, err := handler.InitImage("myapp") ``` ``` -------------------------------- ### Define Metadata type Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/types.md Contains launch-time metadata including processes and buildpack information. ```go type Metadata struct { Processes []Process Buildpacks []Buildpack } ``` -------------------------------- ### Process Environment Directory Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/env.md Reads environment files from a directory and applies them using a specified default action for files without suffixes. ```go // Directory structure: // env/ // PATH.prepend → "/app/bin" // LANG.override → "en_US.UTF-8" // DEBUG → "false" (uses defaultAction) err := env.AddEnvDir("/cnb/buildpack/env", env.ActionTypeDefault) // PATH is prepended with /app/bin // LANG is set to en_US.UTF-8 (overrides) // DEBUG is set to "false" (uses default action) ``` -------------------------------- ### WithBuildpack Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/buildpack.md Adds buildpack information to BOM entries. ```APIDOC ## func WithBuildpack(bp GroupElement, bom []BOMEntry) []BOMEntry ### Description Adds buildpack information to BOM entries. ### Parameters - **bp** (GroupElement) - Required - Buildpack information - **bom** ([]BOMEntry) - Required - BOM entries to annotate ### Returns - **[]BOMEntry** - BOM entries with buildpack info added ### Example ```go entries := []buildpack.BOMEntry{ {Name: "nodejs", Metadata: map[string]interface{}{"version": "18.0.0"}}, } annotated := buildpack.WithBuildpack(bp, entries) ``` ``` -------------------------------- ### Define Process structure Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Represents a single executable process available at runtime with configuration for command, arguments, and environment. ```go type Process struct { Type string `toml:"type" json:"type"` Command RawCommand `toml:"command" json:"command"` Args []string `toml:"args" json:"args"` Direct bool `toml:"direct" json:"direct"` Default bool `toml:"default,omitempty" json:"default,omitempty"` BuildpackID string `toml:"buildpack-id" json:"buildpackID"` WorkingDirectory string `toml:"working-dir,omitempty" json:"working-dir,omitempty"` ExecEnv []string `toml:"exec-env,omitempty" json:"exec-env,omitempty"` PlatformAPI *api.Version `toml:"-" json:"-"` } ``` -------------------------------- ### Package Lifecycle Binaries Source: https://github.com/buildpacks/lifecycle/blob/main/DEVELOPMENT.md Creates archives for the lifecycle binaries using the contents of the `out/linux/lifecycle/` directory for the specified or default `LIFECYCLE_VERSION`. ```bash $ make package ``` -------------------------------- ### String() string Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Returns a string representation of the metadata, including processes and buildpacks. ```APIDOC ## String() ### Description Returns a string representation of the metadata. ### Signature `func (m Metadata) String() string` ### Returns - **string** - Formatted string with processes and buildpacks ``` -------------------------------- ### Define buildpack order in order.toml Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/architecture.md Specifies the sequence of buildpacks to be executed during the lifecycle. ```toml [[order]] group = [ {id = "org.buildpack/nodejs", version = "1.0"}, {id = "org.buildpack/npm", version = "1.0"}, ] ``` -------------------------------- ### Prepend Root Directory to Environment Variables Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/env.md Injects root directories into path-like environment variables based on the RootDirMap configuration. ```go env := &Env{ RootDirMap: map[string][]string{ "bin": {"PATH"}, "lib": {"LD_LIBRARY_PATH"}, }, Vars: env.NewVars(map[string]string{}, false), } env.AddRootDir("/app") // Now PATH=/app/bin:/usr/bin:... // Now LD_LIBRARY_PATH=/app/lib:/usr/lib:... ``` -------------------------------- ### Retrieve All Lifecycle Images Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Returns a list of all unique image references, including output, tags, previous, build, run, and cache images. ```go inputs := platform.NewLifecycleInputs(api.MustParse("0.15")) inputs.OutputImageRef = "gcr.io/my-project/app" inputs.BuildImageRef = "gcr.io/buildpack/build" allImages := inputs.Images() ``` -------------------------------- ### Configure environment variables in build-config/env/ Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/architecture.md Defines environment variable modifications using prepend, append, override, or default strategies. ```text KEY.prepend=value KEY.append=value KEY.override=value KEY.default=value ``` -------------------------------- ### Clean Build Output Source: https://github.com/buildpacks/lifecycle/blob/main/DEVELOPMENT.md Run this command to clean the `out/` directory, removing all previously built artifacts. ```bash make clean ``` -------------------------------- ### RawCommand.WithPlatformAPI Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Sets the Platform API version on the command. ```APIDOC ## func (c RawCommand) WithPlatformAPI(api *api.Version) RawCommand ### Description Sets the Platform API version on the command. ### Returns - **RawCommand** - Modified copy ``` -------------------------------- ### LaunchEnv Interface Definition Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/env.md Interface for accessing runtime launch environment variables. ```go type LaunchEnv interface { Get(string) string List() []string } ``` -------------------------------- ### Annotate BOM entries with WithBuildpack Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/buildpack.md Adds buildpack metadata to existing BOM entries. ```go entries := []buildpack.BOMEntry{ {Name: "nodejs", Metadata: map[string]interface{}{"version": "18.0.0"}}, } annotated := buildpack.WithBuildpack(bp, entries) ``` -------------------------------- ### Initialize Lifecycle Inputs Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/configuration.md Initializes lifecycle inputs with default values based on the provided API version. ```go inputs := platform.NewLifecycleInputs(api.MustParse("0.15")) // AppDir = "/workspace" (if CNB_APP_DIR not set) // LayersDir = "/layers" (if CNB_LAYERS_DIR not set) // LogLevel = "info" (if CNB_LOG_LEVEL not set) // etc. ``` -------------------------------- ### Define Buildpack type Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/types.md Stores buildpack identification and API versioning in the launch context. ```go type Buildpack struct { API string ID string } ``` -------------------------------- ### Platform.Inputs Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Retrieves a copy of the platform's lifecycle inputs. ```APIDOC ## func (p *Platform) Inputs() LifecycleInputs ### Description Returns a copy of the platform's lifecycle inputs. ### Returns - **LifecycleInputs** - Copy of the platform's inputs ``` -------------------------------- ### Configure List Environment Variables Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/configuration.md List variables are defined as comma-separated strings. ```bash export CNB_INSECURE_REGISTRIES=localhost:5000,192.168.1.100:5000,internal-registry # Parsed as: ["localhost:5000", "192.168.1.100:5000", "internal-registry"] export CNB_ADDITIONAL_TAGS=latest,v1.0.0,stable # Parsed as: ["latest", "v1.0.0", "stable"] ``` -------------------------------- ### Define BaseInfo Struct Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/types.md Shared metadata structure for buildpacks and extensions. ```go type BaseInfo struct { ClearEnv bool Homepage string ID string Name string Version string ExecEnv []string } ``` -------------------------------- ### Retrieve Lifecycle Inputs Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Accesses a copy of the platform's lifecycle inputs. ```go platform := platform.NewPlatformFor("0.15") inputs := platform.Inputs() fmt.Println(inputs.AppDir) ``` -------------------------------- ### Process.NoDefault Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Returns a copy of the process with the Default field set to false. ```APIDOC ## func (p Process) NoDefault() Process ### Description Returns a copy of the process with Default set to false. ### Returns - **Process** - Modified copy ``` -------------------------------- ### List.String Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Returns the string representation of the versions list. ```APIDOC ## func (l List) String() string ### Description Returns string representation of the versions list. ### Returns - **string** - Formatted list of versions. ``` -------------------------------- ### Lifecycle Phase Pipeline Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/architecture.md Visual representation of the sequential build phases in the lifecycle. ```text ┌─────────────┐ │ Analyze │ Read previous image metadata └──────┬──────┘ ↓ ┌─────────────┐ │ Detect │ Select applicable buildpacks └──────┬──────┘ ↓ ┌─────────────┐ │ Restore │ Restore cached layers └──────┬──────┘ ↓ ┌─────────────┐ │ Extend │ (Optional) Extend base image └──────┬──────┘ ↓ ┌─────────────┐ │ Build │ Run buildpack build scripts └──────┬──────┘ ↓ ┌─────────────┐ │ Export │ Create output image └──────┬──────┘ ↓ ┌─────────────┐ │ Created │ Output image ready for launch └─────────────┘ ``` -------------------------------- ### Construct APIs instance Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Creates an APIs struct from lists of supported and deprecated version strings, validating that deprecated versions are a subset of supported ones. ```go func NewAPIs(supported []string, deprecated []string) (APIs, error) ``` ```go apis, err := api.NewAPIs( []string{"0.7", "0.8", "0.9"}, []string{}, ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Configuration Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/log.md Environment variables used to configure the logging behavior. ```APIDOC ## Configuration Variables ### CNB_LOG_LEVEL - **Default**: "info" - **Description**: Sets the logging level. Supported values: debug, info, warn, error. ### CNB_NO_COLOR - **Default**: false - **Description**: If set to true, disables colored output in the logs. ``` -------------------------------- ### Define Version struct Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Represents a semantic version with major and minor components. ```go type Version struct { Major uint64 Minor uint64 } ``` -------------------------------- ### WithOverrides Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/env.md Computes the final environment list after applying platform and build configuration overrides. ```APIDOC ## func (p *Env) WithOverrides(platformDir string, baseConfigDir string) (output []string, err error) ### Description Computes final environment after applying platform and build config overrides. It processes environment files from the provided directories and returns the final list of NAME=value strings. ### Parameters - **platformDir** (string) - Optional - Platform directory with /env subdirectory - **baseConfigDir** (string) - Optional - Build config directory with /env subdirectory ### Returns - **output** ([]string) - List of "NAME=value" strings - **err** (error) - Error if processing fails ``` -------------------------------- ### Process.WithPlatformAPI Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Sets the Platform API version on the process and its command, handling format conversion based on the API version. ```APIDOC ## func (p Process) WithPlatformAPI(platformAPI *api.Version) Process ### Description Sets the Platform API version on the process and its command. For API < 0.10, it converts multi-entry commands to a single string; for API >= 0.10, it preserves the array command format. ### Parameters - **platformAPI** (*api.Version) - Required - Platform API version ### Returns - **Process** - Modified copy ``` -------------------------------- ### Define LifecycleInputs configuration struct Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Container for all command-line flags and environment variables passed from the platform. ```go type LifecycleInputs struct { PlatformAPI *api.Version AnalyzedPath string AppDir string BuildConfigDir string BuildImageRef string BuildpacksDir string CacheDir string CacheImageRef string DefaultProcessType string DeprecatedRunImageRef string ExecEnv string ExtendKind string ExtendedDir string ExtensionsDir string GeneratedDir string GroupPath string KanikoDir string LaunchCacheDir string LauncherPath string LauncherSBOMDir string LayersDir string LayoutDir string LogLevel string OrderPath string OutputImageRef string PlanPath string PlatformDir string PreviousImageRef string ProjectMetadataPath string ReportPath string RunImageRef string RunPath string StackPath string SystemPath string UID int GID int ForceRebase bool NoColor bool ParallelExport bool SkipLayers bool UseDaemon bool UseLayout bool AdditionalTags str.Slice KanikoCacheTTL time.Duration InsecureRegistries str.Slice } ``` -------------------------------- ### Retrieve Destination Images Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Returns a list of all destination image references including output and additional tags. ```go inputs := platform.NewLifecycleInputs(api.MustParse("0.15")) inputs.OutputImageRef = "gcr.io/my-project/app" inputs.AdditionalTags = []string{"latest", "v1.0"} dests := inputs.DestinationImages() // Returns: ["gcr.io/my-project/app", "latest", "v1.0"] ``` -------------------------------- ### Access Platform API Variable Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Accesses the predefined instance containing supported Platform API versions. ```go var Platform = newApisMustParse( []string{"0.7", "0.8", "0.9", "0.10", "0.11", "0.12", "0.13", "0.14", "0.15"}, []string{}, ) ``` -------------------------------- ### Set Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/env.md Sets a single environment variable in the Env instance. ```APIDOC ## func (p *Env) Set(name, v string) ### Description Sets a single environment variable. ### Parameters - **name** (string) - Required - Variable name - **v** (string) - Required - Variable value ``` -------------------------------- ### Check API Support Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Determines if a specific version is included in the supported list. ```go apis, _ := api.NewAPIs([]string{"0.7", "0.8"}, []string{}) target := api.MustParse("0.7") fmt.Println(apis.IsSupported(target)) // Output: true ``` -------------------------------- ### Parse version string with panic Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Parses a version string and panics if the input is invalid. ```go func MustParse(v string) *Version ``` ```go version := api.MustParse("0.12") fmt.Println(version.String()) // Output: 0.12 ``` -------------------------------- ### Define RawCommand structure Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Adapts command representation based on the Platform API version for serialization. ```go type RawCommand struct { Entries []string PlatformAPI *api.Version } ``` -------------------------------- ### Creator Phase Execution Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/architecture.md Sequential execution order of lifecycle phases invoked by the creator command. ```go analyzer() detector() restorer() extender() builder() exporter() ``` -------------------------------- ### Formatted Logging in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/log.md Uses printf-style formatting for dynamic log messages. ```go logger.Infof("Processing buildpack %s version %s", bpID, bpVersion) logger.Debugf("Found %d layers in cache", layerCount) logger.Warnf("Layer cache expired at %v", time.Now().Add(-time.Hour)) logger.Errorf("Failed to retrieve layer: %v", err) ``` -------------------------------- ### Generate Mocks and Format Code Source: https://github.com/buildpacks/lifecycle/blob/main/DEVELOPMENT.md Use these commands to generate new mocks for testing and then format and lint the code. The mock generator creates large diffs that the formatter will fix. ```bash $ make generate $ make format lint ``` -------------------------------- ### Define Process type Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/types.md Represents an executable process available at runtime. ```go type Process struct { Type string Command RawCommand Args []string Direct bool Default bool BuildpackID string WorkingDirectory string ExecEnv []string PlatformAPI *api.Version } ``` -------------------------------- ### NewHandler Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Creates an appropriate Handler based on available configuration, returning a handler instance or nil if no valid configuration is provided. ```APIDOC ## NewHandler ### Description Creates an appropriate Handler based on available configuration. The selection logic prioritizes OCI layout, then Docker daemon, then remote registry. ### Signature `func NewHandler(docker client.APIClient, keychain authn.Keychain, layoutDir string, useLayout bool, insecureRegistries []string) Handler` ### Parameters - **docker** (client.APIClient) - No - Docker daemon client - **keychain** (authn.Keychain) - No - Auth credentials - **layoutDir** (string) - No - OCI layout directory path - **useLayout** (bool) - Yes - Whether to use layout if layoutDir provided - **insecureRegistries** ([]string) - No - List of insecure registries ### Returns - **Handler** - Appropriate handler or nil if no valid configuration ### Example ```go // Remote registry with auth handler := image.NewHandler(nil, keychain, "", false, []string{}) img, err := handler.InitImage("gcr.io/my-project/app") ``` ``` -------------------------------- ### MadeLaunch Layer Predicate Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/buildpack.md Checks if a layer is marked for launch. Used as a filter in layer discovery. ```go func MadeLaunch(l Layer) bool ``` ```go launchLayers := layersDir.FindLayers(buildpack.MadeLaunch) ``` -------------------------------- ### Parse version string Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Parses a version string into a Version struct, returning an error if the format is invalid. ```go func NewVersion(v string) (*Version, error) ``` ```go version, err := api.NewVersion("0.12") if err != nil { log.Fatal(err) } fmt.Println(version.String()) // Output: 0.12 ``` -------------------------------- ### Add multiple files to archive Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/archive.md Writes a slice of PathInfo objects to a tar archive. ```go tarFile, _ := os.Create("layers.tar") defer tarFile.Close() tw := tar.NewWriter(tarFile) defer tw.Close() files := []archive.PathInfo{ {Path: "app/file1.txt", Info: fileInfo1}, {Path: "app/dir/", Info: dirInfo}, } err := archive.AddFilesToArchive(tw, files) ``` -------------------------------- ### Parse API Version in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/errors.md Demonstrates the error returned when attempting to parse an invalid version string using api.NewVersion. ```go v, err := api.NewVersion("invalid") // Error: could not parse 'invalid' as version ``` -------------------------------- ### Retrieve Platform API version Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Returns the version of the Platform API currently in use. ```go platform := platform.NewPlatformFor("0.15") apiVersion := platform.API() fmt.Println(apiVersion.String()) // Output: 0.15 ``` -------------------------------- ### Add Layer File Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/cache.md Add a new layer to the cache from a tar file. Fails if the cache is already committed. ```go err := cache.AddLayerFile("/tmp/layer.tar", "sha256:abc123def456...") ``` -------------------------------- ### GetInsecureOptions Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Creates imgutil options for insecure registries to be used with image constructors. ```APIDOC ## func GetInsecureOptions ### Description Creates imgutil options for insecure registries. ### Signature `func GetInsecureOptions(insecureRegistries []string) []remote.Option` ### Parameters - **insecureRegistries** ([]string) - Required - List of registry hostnames/domains to allow insecure access ### Returns - `[]remote.Option` - imgutil remote options to pass to image constructors ### Example ```go opts := image.GetInsecureOptions([]string{"localhost:5000"}) img, err := remote.NewImage("localhost:5000/app", keychain, opts...) ``` ``` -------------------------------- ### Error Handling with Logging Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/log.md Standard pattern for logging errors before returning them to the caller. ```go if err := cache.Commit(); err != nil { logger.Errorf("failed to commit cache: %w", err) return fmt.Errorf("cache commit failed: %w", err) } ``` -------------------------------- ### Define DetectInputs Struct Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/types.md Configuration parameters for executing buildpack detection. ```go type DetectInputs struct { AppDir string BuildConfigDir string PlatformDir string Env BuildEnv TargetEnv []string ExecEnv string } ``` -------------------------------- ### Compute Layer Digest Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/layers.md Demonstrates calculating a file digest using the layers package for layer reference. ```go import ( "io" "github.com/buildpacks/lifecycle/layers" ) // Compute digest of layer file layerPath := "/tmp/layer-data.tar" digest, err := layers.DigestFile(layerPath) if err != nil { log.Fatal(err) } // Use digest for layer reference fmt.Printf("Layer SHA: %s\n", digest) // Later, when reusing cached layer reusableDigest := "sha256:abc123..." // Check if layer with this digest exists in cache ``` -------------------------------- ### Check if version is less than another in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Compares the current version against a string representation of another version. ```go v := api.MustParse("0.8") fmt.Println(v.LessThan("0.9")) // Output: true ``` -------------------------------- ### Handler Interface Definition Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Defines the interface for initializing container images from various storage backends. ```go type Handler interface { InitImage(imageRef string) (imgutil.Image, error) Kind() string } ``` -------------------------------- ### String Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Returns the string representation of the version. ```APIDOC ## func (v *Version) String() string ### Description Returns the string representation of the version formatted as "major.minor". ### Signature `func (v *Version) String() string` ### Returns `string` - Version formatted as "major.minor" ### Example ```go v := api.MustParse("0.12") fmt.Println(v.String()) // Output: 0.12 ``` ``` -------------------------------- ### Verify Image Signature Source: https://github.com/buildpacks/lifecycle/blob/main/IMAGE.md Verify the signature of the buildpacks/lifecycle image. Ensure cosign version is at least 2.0.0. Replace with the desired image tag. ```bash cosign version # must be at least 2.0.0 cosign verify \ --certificate-identity-regexp "https://github.com/buildpacks/lifecycle/.github/workflows/post-release.yml" \ --certificate-oidc-issuer https://token.actions.githubusercontent.com \ buildpacksio/lifecycle: ``` -------------------------------- ### Define PlaceholderLayers constant Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/types.md Placeholder string for the layers directory path that requires updating. ```go const PlaceholderLayers = "" ``` -------------------------------- ### Configure Duration Environment Variables Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/configuration.md Duration variables follow the Go duration format with supported units: ns, us, ms, s, m, h. ```bash export CNB_KANIKO_CACHE_TTL=1h30m # 1 hour 30 minutes export CNB_KANIKO_CACHE_TTL=3600s # 3600 seconds export CNB_KANIKO_CACHE_TTL=1.5h # 1.5 hours ``` -------------------------------- ### Define Descriptor Interface Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/types.md Interface for buildpack or extension metadata. ```go type Descriptor interface { API() string Homepage() string TargetsList() []TargetMetadata } ``` -------------------------------- ### Compare Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Compares the current version with another version object. ```APIDOC ## func (v *Version) Compare(o *Version) int ### Description Compares two versions and returns an integer indicating their relative order. ### Signature `func (v *Version) Compare(o *Version) int` ### Returns `int` - -1 if less than, 0 if equal, 1 if greater than ### Example ```go v1 := api.MustParse("0.8") v2 := api.MustParse("0.9") result := v1.Compare(v2) // Returns -1 ``` ``` -------------------------------- ### imgutil.Image Interface Methods Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/image.md Methods available on the imgutil.Image interface for managing container images. ```APIDOC ## imgutil.Image Interface ### Methods - **Save()** (error) - Writes image to backend - **Name()** (string) - Returns image reference - **Found()** (bool) - Returns true if image exists in backend - **Valid()** (bool) - Returns true if image is not corrupted - **AddLayer(tarPath string)** (error) - Adds a layer from tar file - **AddLayerWithDiffID(tarPath string, diffID string)** (error) - Adds layer with specific diff ID - **ReuseLayer(diffID string)** (error) - Reuses an existing layer by diff ID - **GetLayer(diffID string)** (io.ReadCloser, error) - Retrieves a layer by diff ID - **SetLabel(key string, value string)** (error) - Sets image label - **GetLabel(key string)** (string, error) - Gets image label - **SetEnv(key string, value string)** (error) - Sets environment variable ``` -------------------------------- ### Define PathInfo struct Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/archive.md Represents a filesystem path associated with its file metadata. ```go type PathInfo struct { Path string Info os.FileInfo } ``` -------------------------------- ### Serialize RawCommand to TOML in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Serializes a command to TOML format, using array or string format depending on the configured Platform API version. ```go cmd := launch.NewRawCommand([]string{"/bin/bash", "-c", "npm start"}) cmd = cmd.WithPlatformAPI(api.MustParse("0.15")) bytes, _ := cmd.MarshalTOML() // Output: ["bash", "-c", "npm start"] (for API >= 0.10) ``` -------------------------------- ### Compare two versions in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Compares two Version objects and returns -1 if less than, 0 if equal, or 1 if greater than. ```go v1 := api.MustParse("0.8") v2 := api.MustParse("0.9") result := v1.Compare(v2) // Returns -1 ``` -------------------------------- ### Check version superset in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Verifies if a version is a superset of another based on major and minor version rules. ```go v := api.MustParse("0.11") other := api.MustParse("0.10") fmt.Println(v.IsSupersetOf(other)) // Output: false (0.0 comparison semantics) ``` -------------------------------- ### NewLifecycleInputs Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/platform.md Constructs lifecycle inputs using environment variables and default values. ```APIDOC ## func NewLifecycleInputs(platformAPI *api.Version) *LifecycleInputs ### Description Constructs lifecycle inputs with values from environment variables and defaults. Note: UpdatePlaceholderPaths() must be called after initialization once the final layers directory is known. ### Parameters - **platformAPI** (*api.Version) - Required - The Platform API version to use ### Returns - ***LifecycleInputs** - Lifecycle inputs with environment and default values ``` -------------------------------- ### Check version equality in Go Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Determines if two Version objects are identical. ```go v1 := api.MustParse("0.8") v2 := api.MustParse("0.8") fmt.Println(v1.Equal(v2)) // Output: true ``` -------------------------------- ### NewRawCommand Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Creates a new RawCommand instance from a slice of command entries. ```APIDOC ## func NewRawCommand(entries []string) RawCommand ### Description Creates a RawCommand from command entries. ### Parameters - **entries** ([]string) - Required - Command and arguments (e.g., ["/bin/bash", "-c"]) ### Returns - **RawCommand** - New RawCommand instance ### Example ```go cmd := launch.NewRawCommand([]string{"/bin/bash", "-c", "npm start"}) ``` ``` -------------------------------- ### Compare Metadata Objects Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Compares two metadata objects for testing purposes, specifically ignoring the PlatformAPI field. ```go func (m Metadata) Matches(x any) bool ``` -------------------------------- ### Check Cache Existence Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/cache.md Verify if the original cache image exists before attempting to retrieve metadata. ```go if cache.Exists() { metadata, _ := cache.RetrieveMetadata() } ``` -------------------------------- ### Matches(x any) bool Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Compares two metadata objects for testing purposes, ignoring the PlatformAPI field. ```APIDOC ## Matches(x any) ### Description Compares two metadata objects for testing (used by testify/mock). Note: Ignores PlatformAPI field when comparing. ### Signature `func (m Metadata) Matches(x any) bool` ``` -------------------------------- ### Initialize BOM validator with NewBOMValidator Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/buildpack.md Creates a validator instance for legacy unstructured BOM formats. ```go validator := buildpack.NewBOMValidator("0.12", "/workspace/layers", logger) ``` -------------------------------- ### Add directory to archive Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/archive.md Recursively adds a directory and its contents to a tar archive. ```go tarFile, _ := os.Create("app.tar") defer tarFile.Close() tw := tar.NewWriter(tarFile) defer tw.Close() err := archive.AddDirToArchive(tw, "/workspace/app") if err != nil { log.Fatal(err) } tw.Close() ``` -------------------------------- ### Compute Environment Overrides Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/env.md Generates the final environment variable list by applying platform and build configuration overrides. ```go env := buildEnv // Initial environment finalEnv, err := env.WithOverrides("/platform", "/cnb/build-config") if err != nil { log.Fatal(err) } for _, varAssignment := range finalEnv { fmt.Println(varAssignment) // "PATH=/app/bin:/usr/bin:..." } ``` -------------------------------- ### func NewVersion(v string) (*Version, error) Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/api-version.md Parses a version string into a Version struct. Supports formats 'major.minor' or 'vX.Y'. ```APIDOC ## func NewVersion(v string) (*Version, error) ### Description Parses a version string into a Version struct. Returns an error if the format is invalid or components are non-numeric. ### Parameters - **v** (string) - Required - Version string in format "major.minor" or "vX.Y" ### Returns - **(*Version, error)** - Parsed version or error if parsing fails ``` -------------------------------- ### Define Buildpack structure Source: https://github.com/buildpacks/lifecycle/blob/main/_autodocs/api-reference/launch.md Stores metadata for a buildpack, including its ID and API version. ```go type Buildpack struct { API string `toml:"api"` ID string `toml:"id"` } ```