### Install the YAML package Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.yaml.in/yaml/v3/README.md Use the go get command to add the package to your project. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install Cobra Library Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/spf13/cobra/README.md Use the go get command to fetch the latest version of the Cobra library for your project. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs the pkgsite tool and runs a local Go documentation site. Ensure you have Go installed and your GOPATH is set. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Credential Helper Configuration Example Source: https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md Example configuration mapping multiple registries to the same credential helper. ```json { "credHelpers": { "gcr.io": "gcr", "eu.gcr.io": "gcr" } } ``` -------------------------------- ### Example output Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.yaml.in/yaml/v3/README.md The expected output generated by the provided Go example code. ```text --- t: {Easy! {2 [3 4]}} --- t dump: a: Easy! b: c: 2 d: [3, 4] --- m: map[a:Easy! b:map[c:2 d:[3 4]]] --- m dump: a: Easy! b: c: 2 d: - 3 - 4 ``` -------------------------------- ### Install blackfriday-tool Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/russross/blackfriday/v2/README.md Download and install the blackfriday-tool command-line utility. This tool provides a standalone way to process markdown files. ```bash go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Install gcrane Source: https://github.com/google/go-containerregistry/blob/main/cmd/gcrane/README.md Use the go install command to download and install the latest version of gcrane. ```bash go install github.com/google/go-containerregistry/cmd/gcrane@latest ``` -------------------------------- ### Install Crane Manually with Go Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/README.md Installs the crane binary using the Go toolchain. This is a straightforward method for users with Go installed. ```go go install github.com/google/go-containerregistry/cmd/crane@latest ``` -------------------------------- ### Setup Crane on GitHub Actions Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/README.md Uses the setup-crane action to install crane and configure authentication for GitHub Container Registry within a GitHub Actions workflow. ```yaml steps: - uses: imjasonh/setup-crane@v0.1 ``` -------------------------------- ### Dog and Bird Constructors Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Shows example constructors for `Dog` and `Bird` types, accepting specific variadic options for their respective configurations. ```go func NewDog(name string, o ...DogOption) Dog {…} func NewBird(name string, o ...BirdOption) Bird {…} ``` -------------------------------- ### Initialize Observability Explicitly Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Instrumentation setup should be explicit, side-effect free, and local to the relevant component. Encapsulate setup in constructor functions for clear ownership and scope, avoiding reliance on global or implicit side effects. ```go import ( "errors" semconv "go.opentelemetry.io/otel/semconv/v1.39.0" "go.opentelemetry.io/otel/semconv/v1.39.0/otelconv" ) type SDKComponent struct { inst *instrumentation } func NewSDKComponent(config Config) (*SDKComponent, error) { inst, err := newInstrumentation() if err != nil { return nil, err } return &SDKComponent{inst: inst}, nil } type instrumentation struct { inflight otelconv.SDKComponentInflight exported otelconv.SDKComponentExported } func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } meter := otel.GetMeterProvider().Meter( "", metric.WithInstrumentationVersion(sdk.Version()), metric.WithSchemaURL(semconv.SchemaURL), ) inst := &instrumentation{} var err, e error inst.inflight, e = otelconv.NewSDKComponentInflight(meter) err = errors.Join(err, e) inst.exported, e = otelconv.NewSDKComponentExported(meter) err = errors.Join(err, e) return inst, err } ``` -------------------------------- ### Logout from a registry example Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_auth_logout.md Example command to log out of a specific registry domain. ```bash # Log out of reg.example.com crane auth logout reg.example.com ``` -------------------------------- ### Tag an image example Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_tag.md Adds a v1 tag to the ubuntu image. ```bash # Add a v1 tag to ubuntu crane tag ubuntu v1 ``` -------------------------------- ### Install Compute Metadata Library Source: https://github.com/google/go-containerregistry/blob/main/vendor/cloud.google.com/go/compute/metadata/README.md Use this command to add the metadata package to your Go project. ```bash go get cloud.google.com/go/compute/metadata ``` -------------------------------- ### Example Dockerfile for Rebase Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/rebase.md A sample Dockerfile structure that can be targeted for a rebase operation. ```dockerfile FROM ubuntu RUN ./very-expensive-build-process.sh ENTRYPOINT ["/bin/myapp"] ``` -------------------------------- ### Install Blackfriday v2 Package Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/russross/blackfriday/v2/README.md Use this command to add the Blackfriday v2 package to your Go module. It will resolve and install the package. ```bash go get github.com/russross/blackfriday/v2 ``` -------------------------------- ### Get opentelemetry-go Project Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use `go get` to download the opentelemetry-go project, which places it in your GOPATH. This command may produce warnings that can be ignored. ```go go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Run tests with pflag Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/spf13/pflag/README.md Example command showing how pflag might ignore standard go test flags like -v. ```bash go test /your/tests -run ^YourTest -v --your-test-pflags ``` -------------------------------- ### NewConfig Function Example Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates a common pattern for creating a configured struct by applying options. This function is typically unexported and handles default value setting, option application, and validation. ```go // newConfig returns an appropriately configured config. func newConfig(options ...Option) config { // Set default values for config. config := config{/* […] */} for _, option := range options { config = option.apply(config) } // Perform any validation here. return config } ``` -------------------------------- ### List Tags for a Repository Source: https://github.com/google/go-containerregistry/blob/main/pkg/v1/remote/transport/README.md This example demonstrates how to list tags for a specific repository (e.g., gcr.io/google-containers/pause). It shows how to resolve authentication credentials, construct an HTTP client with appropriate scopes, make the request, and handle potential errors using `transport.CheckError`. The response body, containing the tags, is then written to standard output. ```go package main import ( "io" "net/http" "os" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote/transport" ) func main() { repo, err := name.NewRepository("gcr.io/google-containers/pause") if err != nil { panic(err) } // Fetch credentials based on your docker config file, which is $HOME/.docker/config.json or $DOCKER_CONFIG. auth, err := authn.DefaultKeychain.Resolve(repo.Registry) if err != nil { panic(err) } // Construct an http.Client that is authorized to pull from gcr.io/google-containers/pause. scopes := []string{repo.Scope(transport.PullScope)} t, err := transport.New(repo.Registry, auth, http.DefaultTransport, scopes) if err != nil { panic(err) } client := &http.Client{Transport: t} // Make the actual request. resp, err := client.Get("https://gcr.io/v2/google-containers/pause/tags/list") if err != nil { panic(err) } // Assert that we get a 200, otherwise attempt to parse body as a structured error. if err := transport.CheckError(resp, http.StatusOK); err != nil { panic(err) } // Write the response to stdout. if _, err := io.Copy(os.Stdout, resp.Body); err != nil { panic(err) } } ``` -------------------------------- ### Command options Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_auth_get.md Available flags for the get command. ```bash -h, --help help for get ``` -------------------------------- ### Start Pre-Release Branch Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/RELEASING.md Use the prerelease make target, specifying the module set, to create a branch containing all release changes. ```sh make prerelease MODSET= ``` -------------------------------- ### Download an image blob Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_blob.md Example of downloading a specific ubuntu image blob and saving it to a file. ```bash crane blob ubuntu@sha256:4c1d20cdee96111c8acf1858b62655a37ce81ae48648993542b7ac363ac5c0e5 > blob.tar.gz ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/spf13/cobra/README.md Install the cobra-cli tool to bootstrap application scaffolding and generate command files automatically. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Upload stdin as a layer to a local registry Source: https://github.com/google/go-containerregistry/blob/main/pkg/v1/stream/README.md This example demonstrates how to upload the contents of standard input as a layer to a local registry using the stream package. Ensure a local registry is accessible at localhost:5000. ```go package main import ( "os" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" "github.com/google/go-containerregistry/pkg/v1/stream" ) // upload the contents of stdin as a layer to a local registry func main() { repo, err := name.NewRepository("localhost:5000/stream") if err != nil { panic(err) } layer := stream.NewLayer(os.Stdin) if err := remote.WriteLayer(repo, layer); err != nil { panic(err) } } ``` -------------------------------- ### Get Image Config Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_config.md Use this command to fetch the configuration of a container image. Specify the image reference as an argument. ```bash crane config IMAGE [flags] ``` -------------------------------- ### Clone opentelemetry-go Repository Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Clone the opentelemetry-go repository to your local machine to start development. ```sh git clone https://github.com/open-telemetry/opentelemetry-go.git ``` -------------------------------- ### Convert klog.Infof to structured log Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/go-logr/logr/README.md Example of converting a Kubernetes klog.Infof call with format specifiers to a structured logger call using key-value pairs. ```go logger.Error(err, "client returned an error", "code", responseCode) ``` -------------------------------- ### crane export usage examples Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_export.md Common patterns for exporting images to files or standard output. ```bash # Write tarball to stdout crane export ubuntu - # Write tarball to file crane export ubuntu ubuntu.tar # Read image from stdin crane export - ubuntu.tar ``` -------------------------------- ### Structured Logging with Fields Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Promotes structured logging using fields instead of long error messages. This example shows how to log specific event details using `WithFields`. ```go logrus.WithFields(logrus.Fields{ "event": event, "topic": topic, "key": key, }).Fatal("Failed to send event") ``` -------------------------------- ### Configuring Logrus Logger Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Shows how to configure the Logrus logger for JSON output, set the output to stdout, and filter logs by severity. This example also demonstrates using fields and re-using logrus.Entry. ```go package main import ( "os" log "github.com/sirupsen/logrus" ) func init() { // Log as JSON instead of the default ASCII formatter. log.SetFormatter(&log.JSONFormatter{}) // Output to stdout instead of the default stderr // Can be any io.Writer, see below for File example log.SetOutput(os.Stdout) // Only log the warning severity or above. log.SetLevel(log.WarnLevel) } func main() { log.WithFields(log.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") log.WithFields(log.Fields{ "omg": true, "number": 122, }).Warn("The group's number increased tremendously!") log.WithFields(log.Fields{ "omg": true, "number": 100, }).Fatal("The ice breaks!") // A common pattern is to re-use fields between logging statements by re-using // the logrus.Entry returned from WithFields() contextLogger := log.WithFields(log.Fields{ "common": "this is a common field", "other": "I also should be logged always", }) contextLogger.Info("I'll be logged with common and other field") contextLogger.Info("Me too") } ``` -------------------------------- ### Mount Blob from Debian to Ubuntu Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_auth_token.md This example demonstrates how to use `crane auth token` with the `-H` and `--mount` flags to obtain headers for mounting a blob from a source repository (debian) to a target repository (ubuntu). This is useful for efficiently copying layers between registries. ```bash # If you wanted to mount a blob from debian to ubuntu. $ curl -H "$(crane auth token -H --push --mount debian ubuntu)" ... ``` -------------------------------- ### Sanitize Markdown Output with Bluemonday Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/russross/blackfriday/v2/README.md Combine Blackfriday with Bluemonday to sanitize user-generated markdown content. This example shows how to run Blackfriday and then sanitize its output. ```go import ( "github.com/microcosm-cc/bluemonday" "github.com/russross/blackfriday/v2" ) // ... unsafe := blackfriday.Run(input) html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) ``` -------------------------------- ### Instantiation with Options Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Shows the common pattern for instantiating a type using a variadic slice of Option parameters. Required parameters can precede the options. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Check if Started by Explorer Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/inconshreveable/mousetrap/README.md Use this function on Windows to detect if the process was invoked by double-clicking the executable in Explorer. No setup or imports are required beyond importing the mousetrap package. ```go func StartedByExplorer() (bool) ``` -------------------------------- ### Attribute and Option Allocation Management with sync.Pool Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md This code demonstrates pooling attribute slices and options using sync.Pool to minimize allocations in measurement calls with dynamic attributes. It shows how to get, use, and put pooled objects. ```go var ( attrPool = sync.Pool{ New: func() any { // Pre-allocate common capacity knownCap := 8 // Adjust based on expected usage s := make([]attribute.KeyValue, 0, knownCap) // Return a pointer to avoid extra allocation on Put(). return &s }, } addOptPool = &sync.Pool{ New: func() any { const n = 1 // WithAttributeSet o := make([]metric.AddOption, 0, n) // Return a pointer to avoid extra allocation on Put(). return &o }, } ) func (i *instrumentation) record(ctx context.Context, value int64, baseAttrs ...attribute.KeyValue) { attrs := attrPool.Get().(*[]attribute.KeyValue) defer func() { *attrs = (*attrs)[:0] // Reset. attrPool.Put(attrs) }() *attrs = append(*attrs, baseAttrs...) // Add any dynamic attributes. *attrs = append(*attrs, semconv.OTelComponentName("exporter-1")) addOpt := addOptPool.Get().(*[]metric.AddOption) defer func() { *addOpt = (*addOpt)[:0] addOptPool.Put(addOpt) }() set := attribute.NewSet(*attrs...) *addOpt = append(*addOpt, metric.WithAttributeSet(set)) i.counter.Add(ctx, value, *addOpt...) } ``` -------------------------------- ### Get Raw List Tags Response Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_auth_token.md This example shows how to retrieve the raw JSON response for listing tags of a repository (ubuntu) by using `crane auth token` to generate the necessary authentication headers for `curl`. ```bash # To get the raw list tags response $ curl -H "$(crane auth token -H ubuntu)" https://index.docker.io/v2/library/ubuntu/tags/list ``` -------------------------------- ### Command help options Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_manifest.md Displays help information for the manifest command. ```bash -h, --help help for manifest ``` -------------------------------- ### Build All Files (Old System) Source: https://github.com/google/go-containerregistry/blob/main/vendor/golang.org/x/sys/unix/README.md Use this script to generate Go files for your current OS and architecture with the old build system. Ensure GOOS and GOARCH are set correctly. ```bash mkall.sh ``` -------------------------------- ### Run Benchmarks Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md Commands to compare pure-Go and assembly implementations using benchstat. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Initialize Multiple Keychains Source: https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md Combines multiple Keychain implementations to be checked sequentially for credentials. ```go kc := authn.NewMultiKeychain( authn.DefaultKeychain, google.Keychain, authn.NewKeychainFromHelper(ecr.ECRHelper{ClientFactory: api.DefaultClientFactory{}}), authn.NewKeychainFromHelper(acr.ACRCredHelper{}), ) ``` -------------------------------- ### Install Crane via Homebrew Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/README.md Installs crane on macOS using the Homebrew package manager. This is a convenient option for macOS users. ```sh $ brew install crane ``` -------------------------------- ### Show Build Commands (Old System) Source: https://github.com/google/go-containerregistry/blob/main/vendor/golang.org/x/sys/unix/README.md This command shows the build commands that will be run by mkall.sh without actually executing them, useful for review. ```bash mkall.sh -n ``` -------------------------------- ### Install Crane on Arch Linux Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/README.md Installs crane on Arch Linux using the pacman package manager. This is the standard method for Arch Linux users. ```sh $ pacman -S crane ``` -------------------------------- ### Access Command-Line Arguments Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/spf13/pflag/README.md After parsing flags, access the remaining command-line arguments using flag.Args() to get a slice of strings, or flag.Arg(i) to get an individual argument by index. ```go flag.Args() ``` ```go flag.Arg(i) ``` -------------------------------- ### List All Docker Containers Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/moby/moby/client/README.md Creates a Docker client from environment variables, sets a custom User-Agent, and lists all containers (running and stopped) with their ID, status, and image. Requires the 'context', 'fmt', and 'github.com/moby/moby/client' packages. ```go package main import ( "context" "fmt" "github.com/moby/moby/client" ) func main() { // Create a new client with "client.FromEnv" (configuring the client // from commonly used environment variables such as DOCKER_HOST and // DOCKER_API_VERSION) and set a custom User-Agent. // // API-version negotiation is enabled by default to allow downgrading // the API version when connecting with an older daemon version. apiClient, err := client.New( client.FromEnv, client.WithUserAgent("my-application/1.0.0"), ) if err != nil { panic(err) } defer apiClient.Close() // List all containers (both stopped and running). result, err := apiClient.ContainerList(context.Background(), client.ContainerListOptions{ All: true, }) if err != nil { panic(err) } // Print each container's ID, status and the image it was created from. fmt.Printf("%s %-22s %s\n", "ID", "STATUS", "IMAGE") for _, ctr := range result.Items { fmt.Printf("%s %-22s %s\n", ctr.ID, ctr.Status, ctr.Image) } } ``` -------------------------------- ### GET /catalog Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_catalog.md Lists the repositories present in a container registry. ```APIDOC ## GET /catalog ### Description List the repositories in a registry. ### Method GET ### Endpoint crane catalog REGISTRY [flags] ### Parameters #### Path Parameters - **REGISTRY** (string) - Required - The registry URL to list repositories from. #### Query Parameters - **--full-ref** (boolean) - Optional - If true, print the full image reference. - **--insecure** (boolean) - Optional - Allow image references to be fetched without TLS. - **--platform** (string) - Optional - Specifies the platform in the form os/arch[/variant][:osversion]. - **-v, --verbose** (boolean) - Optional - Enable debug logs. ``` -------------------------------- ### GET /crane/digest Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_digest.md Retrieves the digest of a specified container image. ```APIDOC ## GET crane digest ### Description Get the digest of an image. ### Method GET ### Endpoint crane digest IMAGE [flags] ### Parameters #### Path Parameters - **IMAGE** (string) - Required - The image reference to digest. #### Query Parameters - **--full-ref** (boolean) - Optional - If true, print the full image reference by digest. - **--tarball** (string) - Optional - Path to tarball containing the image. - **--allow-nondistributable-artifacts** (boolean) - Optional - Allow pushing non-distributable (foreign) layers. - **--insecure** (boolean) - Optional - Allow image references to be fetched without TLS. - **--platform** (string) - Optional - Specifies the platform in the form os/arch[/variant][:osversion]. - **--verbose** (boolean) - Optional - Enable debug logs. ``` -------------------------------- ### Compressing small blocks with zstd Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/klauspost/compress/zstd/README.md Demonstrates how to initialize a zstd writer and use EncodeAll to compress a byte slice. Reusing the encoder is recommended to avoid allocations. ```Go import "github.com/klauspost/compress/zstd" // Create a writer that caches compressors. // For this operation type we supply a nil Reader. var encoder, _ = zstd.NewWriter(nil) // Compress a buffer. // If you have a destination buffer, the allocation in the call can also be eliminated. func Compress(src []byte) []byte { return encoder.EncodeAll(src, make([]byte, 0, len(src))) } ``` -------------------------------- ### Format and build project Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/spf13/cobra/CONTRIBUTING.md Command to ensure code consistency and perform project builds. ```bash make all ``` -------------------------------- ### GET /ls Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_ls.md Lists the tags available in a specified container repository. ```APIDOC ## GET /ls ### Description List the tags in a repository. ### Method GET ### Endpoint crane ls REPO [flags] ### Parameters #### Path Parameters - **REPO** (string) - Required - The repository to list tags from. #### Query Parameters - **--full-ref** (boolean) - Optional - If true, print the full image reference. - **--omit-digest-tags** (boolean) - Optional - If true, omit digest tags (e.g., ':sha256-...'). - **--allow-nondistributable-artifacts** (boolean) - Optional - Allow pushing non-distributable (foreign) layers. - **--insecure** (boolean) - Optional - Allow image references to be fetched without TLS. - **--platform** (string) - Optional - Specifies the platform in the form os/arch[/variant][:osversion]. - **--verbose** (boolean) - Optional - Enable debug logs. ``` -------------------------------- ### GET /auth/get Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_auth_get.md Retrieves the configured credentials for a specified registry address. ```APIDOC ## GET crane auth get ### Description Retrieves the configured credentials for a given registry address. ### Method GET ### Endpoint crane auth get [REGISTRY_ADDR] ### Parameters #### Path Parameters - **REGISTRY_ADDR** (string) - Required - The address of the registry to retrieve credentials for. ### Request Example $ crane auth get reg.example.com ### Response #### Success Response (200) - **Username** (string) - The username for the registry. - **Secret** (string) - The secret/password for the registry. #### Response Example { "Username": "AzureDiamond", "Secret": "hunter2" } ``` -------------------------------- ### crane auth get Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_auth.md Implements a credential helper for retrieving authentication credentials. ```APIDOC ## crane auth get ### Description Implements a credential helper to retrieve authentication credentials for a registry. ### Usage ``` crane auth get [flags] ``` ### SEE ALSO * [crane auth](crane_auth.md) - Log in or access credentials ``` -------------------------------- ### Run golangci-lint locally Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/Microsoft/go-winio/README.md Execute linting across the repository from the root directory. ```shell # use . or specify a path to only lint a package # to show all lint errors, use flags "--max-issues-per-linter=0 --max-same-issues=0" > golangci-lint run ./... ``` -------------------------------- ### Examples of crane index filter Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_index_filter.md Common usage patterns for filtering platforms in image indexes. ```bash # Filter out weird platforms from ubuntu, copy result to example.com/ubuntu crane index filter ubuntu --platform linux/amd64 --platform linux/arm64 -t example.com/ubuntu # Filter out any non-linux platforms, push to example.com/hello-world crane index filter hello-world --platform linux -t example.com/hello-world # Same as above, but in-place crane index filter example.com/hello-world:some-tag --platform linux ``` -------------------------------- ### Inspect registry manifest Source: https://github.com/google/go-containerregistry/blob/main/pkg/v1/tarball/README.md Retrieves and displays the manifest list from the registry for the specified image. ```bash $ crane manifest hello-world:nanoserver | jq . { "manifests": [ { "digest": "sha256:63c287625c2b0b72900e562de73c0e381472a83b1b39217aef3856cd398eca0b", "mediaType": "application/vnd.docker.distribution.manifest.v2+json", "platform": { "architecture": "amd64", "os": "windows", "os.version": "10.0.17763.1040" }, "size": 1124 } ], "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json", "schemaVersion": 2 } ``` -------------------------------- ### Blob command help options Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_blob.md Displays help information for the blob command. ```bash -h, --help help for blob ``` -------------------------------- ### Basic Logrus Usage Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Demonstrates the simplest way to use Logrus with the package-level exported logger. Ensure the import path is correct to avoid case-sensitivity issues. ```go package main import "github.com/sirupsen/logrus" func main() { logrus.WithFields(logrus.Fields{ "animal": "walrus", }).Info("A walrus appears") } ``` -------------------------------- ### Logfmt Formatter Output (No TTY) Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Example output using the default TextFormatter when a TTY is not attached, which is compatible with the logfmt format. ```text time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true ``` -------------------------------- ### Docker Config Plaintext Format Source: https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md Example of a Docker config.json file storing credentials in plaintext using Basic Auth. ```json { "auths": { "registry.example.com": { "auth": "QXp1cmVEaWFtb25kOmh1bnRlcjI=" } } } ``` -------------------------------- ### Use DefaultKeychain for Registry Authentication Source: https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md Demonstrates using the DefaultKeychain to authenticate with a registry using credentials from the local Docker configuration. ```go package main import ( "fmt" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" ) func main() { ref, err := name.ParseReference("registry.example.com/private/repo") if err != nil { panic(err) } // Fetch the manifest using default credentials. img, err := remote.Get(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain)) if err != nil { panic(err) } // Prints the digest of registry.example.com/private/repo fmt.Println(img.Digest) } ``` -------------------------------- ### Initialize the root logger Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/go-logr/logr/README.md Create a root logger instance early in the application lifecycle using a specific logging implementation. ```go func main() { // ... other setup code ... // Create the "root" logger. We have chosen the "logimpl" implementation, // which takes some initial parameters and returns a logr.Logger. logger := logimpl.New(param1, param2) // ... other setup code ... ``` -------------------------------- ### crane auth Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_auth.md The base command for authentication operations in crane. It serves as a namespace for subcommands like login, logout, and get. ```APIDOC ## crane auth ### Description Log in or access credentials for container registries. ### Usage ``` crane auth [flags] ``` ### Options ``` -h, --help help for auth ``` ### Options inherited from parent commands ``` --allow-nondistributable-artifacts Allow pushing non-distributable (foreign) layers --insecure Allow image references to be fetched without TLS --platform platform Specifies the platform in the form os/arch[/variant][:osversion] (e.g. linux/amd64). (default all) -v, --verbose Enable debug logs ``` ### SEE ALSO * [crane](crane.md) - Crane is a tool for managing container images * [crane auth get](crane_auth_get.md) - Implements a credential helper * [crane auth login](crane_auth_login.md) - Log in to a registry * [crane auth logout](crane_auth_logout.md) - Log out of a registry * [crane auth token](crane_auth_token.md) - Retrieves a token for a remote repo ``` -------------------------------- ### Import hash implementations Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/opencontainers/go-digest/README.md Register required hash algorithms in the application entrypoint to prevent runtime panics. ```go import ( _ "crypto/sha256" _ "crypto/sha512" ) ``` -------------------------------- ### Version command options Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_version.md Available flags for the version command. ```bash -h, --help help for version ``` -------------------------------- ### JSON Formatter Output Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Example output when using the JSON formatter, suitable for parsing by log aggregation tools like logstash or Splunk. ```text {"animal":"walrus","level":"info","msg":"A group of walrus emerges from the ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} {"level":"warning","msg":"The group's number increased tremendously!", "number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} {"animal":"walrus","level":"info","msg":"A giant walrus appears!", "size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} {"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", "size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} {"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, "time":"2014-03-10 19:57:38.562543128 -0400 EDT"} ``` -------------------------------- ### Convert klog.Infof with Retry-After to structured log Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/go-logr/logr/README.md Example of converting a klog.Infof call involving a Retry-After duration and other parameters to a structured logger call. ```go logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url) ``` -------------------------------- ### Login command options Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_auth_login.md Available flags for configuring the login process, including password input methods. ```text -h, --help help for login -p, --password string Password --password-stdin Take the password from stdin -u, --username string Username ``` -------------------------------- ### Get Latest Release Version Source: https://github.com/google/go-containerregistry/blob/main/cmd/crane/README.md Fetches the latest release tag from the GitHub API. Use this to dynamically set the VERSION variable for downloads. ```sh $ VERSION=$(curl -s "https://api.github.com/repos/google/go-containerregistry/releases/latest" | jq -r '.tag_name') ``` -------------------------------- ### Set Environment-Specific Logrus Formatters Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Configure Logrus formatters based on the application's environment. This example sets the JSONFormatter for production and the TextFormatter for other environments. ```go import ( "github.com/sirupsen/logrus" ) func init() { // do something here to set environment depending on an environment variable // or command-line flag if Environment == "production" { logrus.SetFormatter(&logrus.JSONFormatter{}) } else { // The TextFormatter is default, you don't actually have to do this. logrus.SetFormatter(&logrus.TextFormatter{}) } } ``` -------------------------------- ### Run project tests Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/spf13/cobra/CONTRIBUTING.md Commands to execute the test suite for the project. ```bash go test ./... ``` ```bash make test ``` -------------------------------- ### Text Output with Caller Reporting Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Example text log entry when caller reporting is enabled, including the 'method' field indicating the calling function. ```text time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin ``` -------------------------------- ### JSON Output with Caller Reporting Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Example JSON log entry when caller reporting is enabled, including the 'method' field indicating the calling function. ```json {"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by", "time":"2014-03-10 19:57:38.562543129 -0400 EDT"} ``` -------------------------------- ### Logrus Logging Levels Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/sirupsen/logrus/README.md Demonstrates how to use the seven different logging levels provided by Logrus, from Trace to Panic. Note that Fatal calls os.Exit(1) and Panic calls panic(). ```go logrus.Trace("Something very low level.") lugrus.Debug("Useful debugging information.") lugrus.Info("Something noteworthy happened!") lugrus.Warn("You should probably take a look at this.") lugrus.Error("Something failed but I'm not quitting.") // Calls os.Exit(1) after logging lugrus.Fatal("Bye.") // Calls panic() after logging lugrus.Panic("I'm bailing.") ``` -------------------------------- ### Create a hard-coded credential helper Source: https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md Implements a credential helper that returns static credentials for testing. ```bash #!/usr/bin/env bash echo '{"Username":"","Secret":"hunter2"}' ``` -------------------------------- ### Direct Hashing Functions Source: https://github.com/google/go-containerregistry/blob/main/vendor/github.com/cespare/xxhash/v2/README.md Use Sum64 for byte slices and Sum64String for strings to get the XXH64 hash directly. These are convenient for one-off hashing operations. ```go func Sum64(b []byte) uint64 func Sum64String(s string) uint64 ``` -------------------------------- ### Unexported Config Struct Example Source: https://github.com/google/go-containerregistry/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Defines an unexported config struct for package-internal use. This pattern is generally preferred to avoid external dependencies on internal configuration details. ```go // config contains configuration options for a thing. type config struct { // options ... } ```