### Install and Run Go Doc Site Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Commands to install the pkgsite tool and launch a local documentation server. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install bosh-gcscli Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/README.md Use the go tool to download and install the CLI. ```bash go get github.com/cloudfoundry/bosh-gcscli ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the YAML package for Go. This command fetches and installs the specified package and its dependencies. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Display Help and Version Source: https://context7.com/cloudfoundry/bosh-gcscli/llms.txt Use these commands to verify the installation and view available CLI options. ```bash # Display help with usage examples bosh-gcscli --help # Display version bosh-gcscli -v # Output: # version dev ``` -------------------------------- ### Install Google Auth Library Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cloud.google.com/go/auth/README.md Use the go get command to add the library to your Go project dependencies. ```bash go get cloud.google.com/go/auth@latest ``` -------------------------------- ### Install IAM Go Client Library Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cloud.google.com/go/iam/README.md Use this command to install the Go client library for the IAM API. Ensure your Go environment is set up correctly. ```bash go get cloud.google.com/go/iam ``` -------------------------------- ### Install Compute Metadata Library Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cloud.google.com/go/compute/metadata/README.md Use the go get command to add the metadata package to your Go project. ```bash go get cloud.google.com/go/compute/metadata ``` -------------------------------- ### Install uuid Package Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/google/uuid/README.md Use this command to install the uuid package using go get. ```sh go get github.com/google/uuid ``` -------------------------------- ### Get opentelemetry-go Package Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use `go get` to download the opentelemetry-go package. Ignore any build constraint warnings. ```go go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Initialize Instrumentation Explicitly Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use constructor functions for instrumentation setup to ensure clear ownership and avoid global side effects. ```go import ( "errors" semconv "go.opentelemetry.io/otel/semconv/v1.40.0" "go.opentelemetry.io/otel/semconv/v1.40.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 } ``` ```go // ❌ Avoid this pattern. func (c *Component) initObservability() { // Initialize observability metrics if !x.Observability.Enabled() { return } // Initialize observability metrics c.inst = &instrumentation{/* ... */} } ``` -------------------------------- ### Setup Integration Test Environment Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/README.md Configure environment variables and service account permissions required to run integration tests. ```bash export project_id=$(gcloud config get-value project) export service_account_name=bosh-gcscli-integration-tests export service_account_email=${service_account_name}@${project_id}.iam.gserviceaccount.com credentials_file=$(mktemp) gcloud config set project ${project_id} gcloud iam service-accounts create ${service_account_name} --display-name "Integration Test Access for bosh-gcscli" gcloud iam service-accounts keys create ${credentials_file} --iam-account ${service_account_email} gcloud project add-iam-policy-binding ${project_id} --member serviceAccount:${service_account_email} --role roles/storage.admin export GOOGLE_SERVICE_ACCOUNT="$(cat ${credentials_file})" export GOOGLE_APPLICATION_CREDENTIALS="$(cat ${credentials_file})" export LC_ALL=C # fix `tr` complaining about "illegal byte sequence" on OSX ``` -------------------------------- ### Create Root Logger Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/go-logr/logr/README.md Initialize the root logger early in an application's lifecycle. This example shows creating a logger using a hypothetical 'logimpl' implementation with initial parameters. ```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 ... } ``` -------------------------------- ### CEL Boolean Conditions and Object Construction Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cel.dev/expr/README.md Illustrates typical CEL usage for evaluating boolean conditions and constructing objects. No specific setup is required beyond having a CEL environment. ```cel // Condition account.balance >= transaction.withdrawal || (account.overdraftProtection && account.overdraftLimit >= transaction.withdrawal - account.balance) ``` ```cel // Object construction common.GeoPoint{ latitude: 10.0, longitude: -5.5 } ``` -------------------------------- ### xxhash Benchmarking Commands Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/cespare/xxhash/v2/README.md Commands to benchmark the pure Go and assembly implementations of the Sum64 function. Ensure you have benchstat installed. These commands measure performance under different build tags and configurations. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Regenerate Protobuf Go Code Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/googleapis/gax-go/v2/apierror/internal/proto/README.md Execute these commands from the project directory to regenerate the Go source files. Requires protoc, the Go protobuf plugin, and goimports to be installed. ```sh protoc -I $GOOGLEAPIS -I. --go_out=. --go_opt=module=github.com/googleapis/gax-go/v2/apierror/internal/proto error.proto goimports -w . ``` -------------------------------- ### Simulate I/O Timeout Error Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/google.golang.org/grpc/README.md Example of the error message encountered when the golang.org domain is unreachable. ```console $ go get -u google.golang.org/grpc package google.golang.org/grpc: unrecognized import path "google.golang.org/grpc" (https fetch: Get https://google.golang.org/grpc?go-get=1: dial tcp 216.239.37.1:443: i/o timeout) ``` -------------------------------- ### Generate Signed URLs with CLI Source: https://context7.com/cloudfoundry/bosh-gcscli/llms.txt Create time-limited URLs for secure GET, PUT, or DELETE operations on GCS blobs. ```bash # Generate a signed URL for downloading (GET) valid for 6 hours bosh-gcscli -c config.json sign releases/my-release-1.0.tgz GET 6h # Output (single URL string): # https://storage.googleapis.com/my-bosh-blobstore/releases/my-release-1.0.tgz?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=...&X-Goog-Signature=... # Generate a signed URL for uploading (PUT) valid for 24 hours bosh-gcscli -c config.json sign releases/new-release-2.0.tgz PUT 24h # Generate a signed URL for deleting valid for 1 hour bosh-gcscli -c config.json sign releases/temp-release.tgz DELETE 1h # Use the signed URL with curl for download SIGNED_URL=$(bosh-gcscli -c config.json sign releases/my-release-1.0.tgz GET 1h) curl -o downloaded-release.tgz "$SIGNED_URL" # Use signed URL for upload (PUT) UPLOAD_URL=$(bosh-gcscli -c config.json sign releases/new-release.tgz PUT 1h) curl -X PUT -T /path/to/release.tgz "$UPLOAD_URL" ``` -------------------------------- ### Initialize Cloud Storage Client Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cloud.google.com/go/storage/README.md Create a storage.Client to interact with Cloud Storage. Ensure proper error handling. ```go client, err := storage.NewClient(ctx) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Initialize GCSBlobstore Client in Go Source: https://context7.com/cloudfoundry/bosh-gcscli/llms.txt Configure and instantiate a blobstore client using JSON credentials. ```go package main import ( "context" "log" "os" "strings" "github.com/cloudfoundry/bosh-gcscli/client" "github.com/cloudfoundry/bosh-gcscli/config" ) func main() { // Create configuration from JSON configJSON := `{ "bucket_name": "my-bosh-blobstore", "credentials_source": "static", "json_key": "{\"type\":\"service_account\",...}" }` cfg, err := config.NewFromReader(strings.NewReader(configJSON)) if err != nil { log.Fatalf("Failed to parse config: %v", err) } // Create the blobstore client ctx := context.Background() blobstore, err := client.New(ctx, &cfg) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Use the client for operations exists, err := blobstore.Exists("releases/my-release-1.0.tgz") if err != nil { log.Fatalf("Failed to check existence: %v", err) } log.Printf("Blob exists: %v", exists) } ``` -------------------------------- ### Go Library: Download Object (Get) Source: https://context7.com/cloudfoundry/bosh-gcscli/llms.txt Downloads a blob from GCS to a local file or memory buffer. ```APIDOC ## Go Library: Download Object (Get) ### Description Downloads a blob from GCS to an io.Writer destination. ### Method blobstore.Get(remotePath, destination) ### Parameters - **remotePath** (string) - Required - The path of the blob to download. - **destination** (io.Writer) - Required - The destination to write the blob data. ### Response - **err** (error) - Returns nil on success, or an error if the download fails. ``` -------------------------------- ### Show mkall.sh commands (Old Build System) Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/golang.org/x/sys/unix/README.md Use this command to preview the build process without executing it. Ensure GOOS and GOARCH are set correctly. ```bash mkall.sh -n ``` -------------------------------- ### BOSH Director GCS Configuration Source: https://context7.com/cloudfoundry/bosh-gcscli/llms.txt Example YAML configuration for integrating GCS as a BOSH Director blobstore backend. ```yaml # director.yml blobstore: provider: gcs options: bucket_name: my-bosh-blobstore credentials_source: static json_key: | { "type": "service_account", "project_id": "my-project", "private_key_id": "...", "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n", "client_email": "blobstore@my-project.iam.gserviceaccount.com" } storage_class: REGIONAL ``` -------------------------------- ### Create and Check Version Constraint Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/Masterminds/semver/v3/README.md Demonstrates how to create a new version constraint and check if a given version satisfies it. Handles potential errors during constraint or version parsing. ```go c, err := semver.NewConstraint(">= 1.2.3") if err != nil { // Handle constraint not being parsable. } v, err := semver.NewVersion("1.3") if err != nil { // Handle version not being parsable. } // Check if the version meets the constraints. The variable a will be true. a := c.Check(v) ``` -------------------------------- ### Get GPG Key ID Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/RELEASING.md Retrieve your GPG key ID, which is a 16-character string following `sec rsa4096/` (or similar), used for signing artifacts. ```terminal gpg --list-secret-keys --keyid-format=long ``` -------------------------------- ### Run Unit Tests Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cloud.google.com/go/storage/TESTING.md Execute unit tests for the storage package using the 'go test' command with the '-short' flag. This flag typically skips long-running tests. ```bash go test ./google-cloud-go/storage -short ``` -------------------------------- ### Run Prerelease Make Target Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/RELEASING.md Execute the `prerelease` make target to create a branch with all release changes. Specify the module set to be released. ```bash make prerelease MODSET= ``` -------------------------------- ### Define Option Wrapper Signature Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Exported configuration functions should be prefixed with With or Without and follow this signature. ```go func With*(…) Option { … } ``` -------------------------------- ### Run mkall.sh to build current OS/Arch files (Old Build System) Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/golang.org/x/sys/unix/README.md Use this command when GOOS is not 'linux'. Ensure GOOS and GOARCH are set correctly. This script generates Go files based on local C header files. ```bash mkall.sh ``` -------------------------------- ### Enable Experimental Resource Conventions Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/sdk/internal/x/README.md Set the OTEL_GO_X_RESOURCE environment variable to 'true' to enable experimental resource semantic conventions. This feature may change in backwards-incompatible ways. ```bash export OTEL_GO_X_RESOURCE=true ``` -------------------------------- ### Run Gomega linter Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/onsi/gomega/CONTRIBUTING.md Check the codebase for potential issues using the Go vet tool. ```bash go vet ./... ``` -------------------------------- ### Load the Slim-Sprig library Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/go-task/slim-sprig/v3/README.md The FuncMap must be registered with the template instance before parsing any template files. ```go import ( "html/template" "github.com/go-task/slim-sprig" ) // This example illustrates that the FuncMap *must* be set before the // templates themselves are loaded. tpl := template.Must( template.New("base").Funcs(sprig.FuncMap()).ParseGlob("*.html") ) ``` -------------------------------- ### Activate Observability via Environment Variable Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Check the OTEL_GO_X_OBSERVABILITY environment variable to conditionally enable experimental observability features. ```go import "go.opentelemetry.io/otel/*/internal/x" if x.Observability.Enabled() { // Initialize observability metrics } ``` -------------------------------- ### Run Gomega tests Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/onsi/gomega/CONTRIBUTING.md Execute all unit tests locally using Ginkgo. ```bash ginkgo -r -p ``` -------------------------------- ### CLI Command Usage Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/README.md Standard commands for interacting with Google Cloud Storage buckets via the CLI. ```bash bosh-gcscli --help ``` ```bash bosh-gcscli -c config.json put ``` ```bash bosh-gcscli -c config.json get ``` ```bash bosh-gcscli -c config.json delete ``` ```bash bosh-gcscli -c config.json exists ``` ```bash bosh-gcscli -c config.json sign ``` -------------------------------- ### Define a Ginkgo test suite Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md Use Describe, Context, and It blocks to structure test scenarios. Requires importing Ginkgo and Gomega packages. ```go import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ... ) var _ = Describe("Checking books out of the library", Label("library"), func() { var library *libraries.Library var book *books.Book var valjean *users.User BeforeEach(func() { library = libraries.NewClient() book = &books.Book{ Title: "Les Miserables", Author: "Victor Hugo", } valjean = users.NewUser("Jean Valjean") }) When("the library has the book in question", func() { BeforeEach(func(ctx SpecContext) { Expect(library.Store(ctx, book)).To(Succeed()) }) Context("and the book is available", func() { It("lends it to the reader", func(ctx SpecContext) { Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books()).To(ContainElement(book)) Expect(library.UserWithBook(ctx, book)).To(Equal(valjean)) }, SpecTimeout(time.Second * 5)) }) Context("but the book has already been checked out", func() { var javert *users.User BeforeEach(func(ctx SpecContext) { javert = users.NewUser("Javert") Expect(javert.Checkout(ctx, library, "Les Miserables")).To(Succeed()) }) It("tells the user", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is currently checked out")) }, SpecTimeout(time.Second * 5)) It("lets the user place a hold and get notified later", func(ctx SpecContext) { Expect(valjean.Hold(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Holds(ctx)).To(ContainElement(book)) By("when Javert returns the book") Expect(javert.Return(ctx, library, book)).To(Succeed()) By("it eventually informs Valjean") notification := "Les Miserables is ready for pick up" Eventually(ctx, valjean.Notifications).Should(ContainElement(notification)) Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books(ctx)).To(ContainElement(book)) Expect(valjean.Holds(ctx)).To(BeEmpty()) }, SpecTimeout(time.Second * 10)) }) }) When("the library does not have the book in question", func() { It("tells the reader the book is unavailable", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is not in the library catalog")) }, SpecTimeout(time.Second * 5)) }) }) ``` -------------------------------- ### Implement Configuration Constructor Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Pattern for a newConfig function that applies functional options and sets defaults. ```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 } ``` -------------------------------- ### Run Live Service Integration Tests Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cloud.google.com/go/storage/TESTING.md Execute integration tests against the live Google Cloud Storage service. This requires a configured Google Cloud project, a service account key, and a VM. Set GCLOUD_TESTS_GOLANG_PROJECT_ID and GCLOUD_TESTS_GOLANG_KEY environment variables. ```bash GCLOUD_TESTS_GOLANG_PROJECT_ID="${PROJECT_ID?}" GCLOUD_TESTS_GOLANG_KEY="${KEYFILE?}" \ go test ./google-cloud-go/storage -run="^Test.*Integration" ``` -------------------------------- ### Enable gRPC-Go Logging Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/google.golang.org/grpc/README.md Set environment variables to increase log verbosity and specify severity levels for debugging. ```console $ export GRPC_GO_LOG_VERBOSITY_LEVEL=99 $ export GRPC_GO_LOG_SEVERITY_LEVEL=info ``` -------------------------------- ### Create and Push Branch Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Create a new branch, make modifications, run precommit checks, stage changes, commit, and push to your fork. ```sh git checkout -b # edit files # update changelog make precommit git add -p git commit git push ``` -------------------------------- ### Clone Repositories for Testing Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cloud.google.com/go/storage/TESTING.md Clone the google-cloud-go repository and the storage-testbench emulator repository. This is a prerequisite for running integration tests. ```bash git clone https://github.com/googleapis/google-cloud-go git clone https://github.com/googleapis/storage-testbench # emulator ``` -------------------------------- ### Run Emulated Integration Tests Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/cloud.google.com/go/storage/TESTING.md Run integration tests against a local storage emulator. Ensure the emulator is running and accessible on the specified ports. Set STORAGE_EMULATOR_HOST_GRPC and STORAGE_EMULATOR_HOST environment variables. ```bash STORAGE_EMULATOR_HOST_GRPC="localhost:8888"STORAGE_EMULATOR_HOST="http://localhost:9000" go test ./google-cloud-go/storage -short -run="^Test(RetryConformance|.*Emulated)" ``` -------------------------------- ### Go Library: GCSBlobstore Client Source: https://context7.com/cloudfoundry/bosh-gcscli/llms.txt Programmatically create a blobstore client for use in Go applications using a configuration file. ```APIDOC ## Go Library: GCSBlobstore Client ### Description Initializes a GCSBlobstore client using a JSON configuration reader. ### Method client.New(ctx, &cfg) ### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **cfg** (config.Config) - Required - The configuration object parsed from JSON. ### Response - **blobstore** (client.GCSBlobstore) - The initialized client instance. - **err** (error) - Error object if initialization fails. ``` -------------------------------- ### System Call Entry Points (Assembly) Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/golang.org/x/sys/unix/README.md These are the hand-written assembly functions for system call dispatch. They differ in the number of arguments passed to the kernel. RawSyscall is for low-level use and bypasses the scheduler. ```go func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` -------------------------------- ### Initialize GCP Resource Detector in Go Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/contrib/detectors/gcp/README.md Configures the resource detector with GCP support and custom service attributes for use in telemetry providers. ```golang ctx := context.Background() // Detect your resources res, err := resource.New(ctx, // Use the GCP resource detector! resource.WithDetectors(gcp.NewDetector()), // Keep the default detectors resource.WithTelemetrySDK(), // Add your own custom attributes to identify your application resource.WithAttributes( semconv.ServiceNameKey.String("my-application"), semconv.ServiceNamespaceKey.String("my-company-frontend-team"), ), ) if err != nil { // Handle err } // Use the resource in your tracerprovider (or meterprovider) tp := trace.NewTracerProvider( // ... other options trace.WithResource(res), ) ``` -------------------------------- ### Sign Release Artifacts Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/RELEASING.md Sign the downloaded `.tar.gz` and `.zip` archives using your GPG key. Set the `VERSION` and `KEY_ID` environment variables before signing. ```bash export VERSION="" export KEY_ID="" gpg --local-user $KEY_ID --armor --detach-sign opentelemetry-go-$VERSION.tar.gz gpg --local-user $KEY_ID --armor --detach-sign opentelemetry-go-$VERSION.zip ``` -------------------------------- ### Create GitHub Release Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/onsi/ginkgo/v2/RELEASING.md Commands to commit changes, push to origin, and create a new GitHub release. Ensure the version number (vM.m.p) is correctly formatted. ```bash git commit -m "vM.m.p" git push gh release create "vM.m.p" git fetch --tags origin master ``` -------------------------------- ### Define Instantiation Function Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md NewT functions accept variadic options to configure the instance. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Import gRPC-Go Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/google.golang.org/grpc/README.md Add this import statement to your Go source files to include the gRPC dependency. ```go import "google.golang.org/grpc" ``` -------------------------------- ### Attribute and Option Allocation Management with sync.Pool Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md This Go code utilizes `sync.Pool` to pre-allocate and reuse slices for attributes and metric add options, minimizing memory allocations during measurement calls with dynamic attributes. It demonstrates pooling attribute slices and options. ```go var ( attrPool = sync.Pool{ New: func() any { // Pre-allocate common capacity knowCap := 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...) } ``` -------------------------------- ### Run local verification and test commands Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/google.golang.org/grpc/CONTRIBUTING.md Execute these commands from the repository root to ensure code quality and test coverage before submitting a pull request. ```bash ./scripts/vet.sh ``` ```bash go test -cpu 1,4 -timeout 7m ./... ``` ```bash go test -race -cpu 1,4 -timeout 7m ./... ``` -------------------------------- ### Handle Overlapping Configurations Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use interface composition to share common configuration logic across different types. ```go // config holds options for all animals. type config struct { Weight float64 Color string MaxAltitude float64 } // DogOption apply Dog specific options. type DogOption interface { applyDog(config) config } // BirdOption apply Bird specific options. type BirdOption interface { applyBird(config) config } // Option apply options for all animals. type Option interface { BirdOption DogOption } type weightOption float64 func (o weightOption) applyDog(c config) config { c.Weight = float64(o) return c } func (o weightOption) applyBird(c config) config { c.Weight = float64(o) return c } func WithWeight(w float64) Option { return weightOption(w) } type furColorOption string func (o furColorOption) applyDog(c config) config { c.Color = string(o) return c } func WithFurColor(c string) DogOption { return furColorOption(c) } type maxAltitudeOption float64 func (o maxAltitudeOption) applyBird(c config) config { c.MaxAltitude = float64(o) return c } func WithMaxAltitude(a float64) BirdOption { return maxAltitudeOption(a) } func NewDog(name string, o ...DogOption) Dog {…} func NewBird(name string, o ...BirdOption) Bird {…} ``` -------------------------------- ### Verify Prerelease Changes Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/RELEASING.md Compare the current state with the newly created prerelease branch to verify version updates. All module versions should be updated to the new tag. ```bash git diff ...prerelease__ ``` -------------------------------- ### Define Configuration Struct Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Standard pattern for defining an internal configuration struct. ```go // config contains configuration options for a thing. type config struct { // options ... } ``` -------------------------------- ### Clone opentelemetry-go Repository Directly Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Alternatively, clone the repository directly using Git. Note that this does not use the `go.opentelemetry.io/otel` alias. ```sh git clone https://github.com/open-telemetry/opentelemetry-go ``` -------------------------------- ### Configure BOSH GCSCLI Source: https://context7.com/cloudfoundry/bosh-gcscli/llms.txt Configuration files define the target bucket, authentication method, and optional security settings like encryption keys. ```json { "bucket_name": "my-bosh-blobstore", "credentials_source": "static", "json_key": "{\"type\":\"service_account\",\"project_id\":\"my-project\",\"private_key_id\":\"...\",\"private_key\":\"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n\",\"client_email\":\"blobstore@my-project.iam.gserviceaccount.com\",\"client_id\":\"...\",\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"token_uri\":\"https://oauth2.googleapis.com/token\"}", "storage_class": "REGIONAL", "encryption_key": "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY=" } ``` ```json { "bucket_name": "public-read-bucket", "credentials_source": "none" } ``` ```json { "bucket_name": "my-bosh-blobstore" } ``` -------------------------------- ### Clone opentelemetry-go Repository Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use this command to clone the opentelemetry-go repository to your local machine. ```sh git clone https://github.com/open-telemetry/opentelemetry-go.git ``` -------------------------------- ### Set the bosh-gcscli pipeline Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/ci/README.md Configure the pipeline using the provided YAML files. ```bash fly -t google set-pipeline -p bosh-gcscli -c pipeline.yml -l credentials.yml ``` -------------------------------- ### Unmarshal and Marshal YAML Data in Go Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.yaml.in/yaml/v3/README.md Demonstrates unmarshaling YAML data into a Go struct and a map, and then marshaling them back into YAML format. Ensure struct fields are public for correct unmarshaling. ```go package main import ( "fmt" "log" "go.yaml.in/yaml/v3" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` // Note: struct fields must be public in order for unmarshal to // correctly populate the data. type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` -------------------------------- ### Validate a version against a constraint in Go Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/github.com/Masterminds/semver/v3/README.md Use NewConstraint and NewVersion to define constraints and versions, then call Validate to check compatibility and retrieve error messages. ```go c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") if err != nil { // Handle constraint not being parseable. } v, err := semver.NewVersion("1.3") if err != nil { // Handle version not being parseable. } // Validate a version against a constraint. a, msgs := c.Validate(v) // a is false for _, m := range msgs { fmt.Println(m) // Loops over the errors which would read // "1.3 is greater than 1.2.3" // "1.3 is less than 1.4" } ``` -------------------------------- ### Add Release Tags Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/otel/RELEASING.md Use the `add-tags` make target to create release tags for each module set. Provide the commit hash if it's not the current HEAD. ```bash make add-tags MODSET= COMMIT= ``` -------------------------------- ### Configure Go Modules for Restricted Networks Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/google.golang.org/grpc/README.md Use the replace directive to alias golang.org packages to GitHub mirrors when the primary domain is blocked. ```sh go mod edit -replace=google.golang.org/grpc=github.com/grpc/grpc-go@latest go mod tidy go mod vendor go build -mod=vendor ``` -------------------------------- ### Enable Environment Variable Unpacking in Go Source: https://github.com/cloudfoundry/bosh-gcscli/blob/main/vendor/go.opentelemetry.io/contrib/detectors/gcp/README.md Uses the WithFromEnv option to automatically parse OTEL_RESOURCE_ATTRIBUTES environment variables. ```golang ... // Detect your resources res, err := resource.New(ctx, resource.WithDetectors(gcp.NewDetector()), resource.WithTelemetrySDK(), resource.WithFromEnv(), // unpacks OTEL_RESOURCE_ATTRIBUTES // Add your own custom attributes to identify your application resource.WithAttributes( semconv.ServiceNameKey.String("my-application"), semconv.ServiceNamespaceKey.String("my-company-frontend-team"), ), ) ... ```