### Install go-isatty Package (Go) Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/mattn/go-isatty/README.md Use the go get command to install the go-isatty package. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Install diskv Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/peterbourgon/diskv/README.md Use the go get command to install the diskv package. ```bash $ go get github.com/peterbourgon/diskv ``` -------------------------------- ### Install the color library Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/fatih/color/README.md Use the go get command to add the package to your project. ```bash go get github.com/fatih/color ``` -------------------------------- ### Create and Run a SOCKS5 Server Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/cloudfoundry/go-socks5/README.md This example demonstrates how to create a new SOCKS5 server with default configuration and start listening for TCP connections on a specified address and port. Ensure the 'socks5' package is imported. ```go // Create a SOCKS5 server conf := &socks5.Config{} server, err := socks5.New(conf) if err != nil { panic(err) } // Create SOCKS5 proxy on localhost port 8000 if err := server.ListenAndServe("tcp", "127.0.0.1:8000"); err != nil { panic(err) } ``` -------------------------------- ### Install and Run Go Doc Site Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Commands to install the local documentation server and launch it. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install go-colorable Package Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/mattn/go-colorable/README.md Install the go-colorable package using the go get command. This is a prerequisite for using the colorable writer. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Install Backoff Package Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/jpillora/backoff/README.md Use 'go get' to install the backoff library. This command fetches and installs the package and its dependencies. ```bash $ go get -v github.com/jpillora/backoff ``` -------------------------------- ### Install Doublestar Package Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/bmatcuk/doublestar/README.md Install the doublestar package using the go get command. This is the initial step to include it in your project. ```bash go get github.com/bmatcuk/doublestar ``` -------------------------------- ### Start All Instances in Deployment Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Starts all instances within a specified deployment. Use this command to bring all application components online. ```bash bosh -e my-bosh -d cf start ``` -------------------------------- ### Install Graphemes Package Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/clipperhouse/uax29/v2/graphemes/README.md Use 'go get' to install the graphemes package for your project. ```bash go get github.com/clipperhouse/uax29/v2/graphemes ``` -------------------------------- ### Create Root Logger Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/go-logr/logr/README.md Initialize the root logger early in your application's setup. This example uses a hypothetical 'logimpl' 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 ... } ``` -------------------------------- ### Install Google Auth Library Source: https://github.com/cloudfoundry/bosh-cli/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 go.yaml.in/yaml/v3 Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the v3 version of the YAML package for your Go projects. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install Cobra Library Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/spf13/cobra/README.md Use the go get command to fetch the latest version of the Cobra library. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install IAM Go Client Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/cloud.google.com/go/iam/README.md Use this command to install the IAM Go client library via the Go module system. ```bash go get cloud.google.com/go/iam ``` -------------------------------- ### Install Ginkgo Locally Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Installs the Ginkgo CLI locally. Ensure you have Go installed and configured. ```bash go install ./... ``` -------------------------------- ### Install Compute Metadata Library Source: https://github.com/cloudfoundry/bosh-cli/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 ``` -------------------------------- ### Initialize Vagrant Environment Source: https://github.com/cloudfoundry/bosh-cli/blob/main/ci/docker/README.md Starts and accesses the Vagrant virtual machine. ```bash vagrant up vagrant ssh ``` -------------------------------- ### Installation Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/bmatcuk/doublestar/README.md Instructions on how to install and import the doublestar package. ```bash go get github.com/bmatcuk/doublestar ``` ```go import "github.com/bmatcuk/doublestar" ``` -------------------------------- ### Migrate Format Strings to Structured Logging Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/go-logr/logr/README.md Examples demonstrating the conversion of standard format-string logging calls to structured key-value logging. ```go klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err) ``` ```go logger.Error(err, "client returned an error", "code", responseCode) ``` ```go klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url) ``` ```go logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url) ``` ```go log.Printf("unable to reflect over type %T") ``` ```go logger.Info("unable to reflect over type", "type", fmt.Sprintf("%T")) ``` -------------------------------- ### Start Specific Instance Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Starts a single, specific instance identified by its group and index. This allows for targeted restarts or startup of individual components. ```bash bosh -e my-bosh -d cf start web/0 ``` -------------------------------- ### Install counterfeiter to GOPATH Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/maxbrunsfeld/counterfeiter/v6/README.md Install the binary to your GOPATH to allow invocation outside of a Go module. ```shell $ go install github.com/maxbrunsfeld/counterfeiter/v6 $ ~/go/bin/counterfeiter USAGE counterfeiter [-generate>] [-o ] [-p] [--fake-name ] [-header ] [] [-] ``` -------------------------------- ### Start Specific Instance Group Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Starts all instances belonging to a particular instance group within a deployment. Useful for rolling out updates or restarting specific services. ```bash bosh -e my-bosh -d cf start web ``` -------------------------------- ### Install gouuid package Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/nu7hatch/gouuid/README.md Use the go tool to fetch the package dependency. ```bash $ go get github.com/nu7hatch/gouuid ``` -------------------------------- ### Ginkgo Spec Example Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md This example demonstrates a typical Ginkgo spec structure, including BeforeEach, When, Context, It, and assertions using Gomega matchers. It covers scenarios for checking out books from a library. ```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)) }) }) ``` -------------------------------- ### Install UUID package Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/google/uuid/README.md Use this command to install the UUID package via Go modules. ```sh go get github.com/google/uuid ``` -------------------------------- ### Get opentelemetry-go Project Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use `go get` to download the opentelemetry-go project. This command may print warnings about build constraints, which can be ignored. ```go go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/spf13/cobra/README.md Install the cobra-cli tool to bootstrap application scaffolding. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Run tests with pflag Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/spf13/pflag/README.md Example command demonstrating how pflag can cause go test flags to be ignored. ```bash go test /your/tests -run ^YourTest -v --your-test-pflags ``` -------------------------------- ### Manage BOSH Deployment Instances Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Control deployment instances by starting, stopping, restarting, and recreating them. Use VMInfos to retrieve current VM states. ```go package main import ( "fmt" boshdir "github.com/cloudfoundry/bosh-cli/v7/director" ) func manageInstances(deployment boshdir.Deployment) error { // Get VM information vmInfos, err := deployment.VMInfos() if err != nil { return err } for _, vm := range vmInfos { fmt.Printf("VM: %s/%s - State: %s, AZ: %s\n", vm.JobName, vm.ID, vm.ProcessState, vm.AZ) } // Start all instances in deployment err = deployment.Start( boshdir.NewAllOrInstanceGroupOrInstanceSlug("", ""), boshdir.StartOpts{ Canaries: "1", MaxInFlight: "10%", Converge: true, }, ) if err != nil { return err } // Stop a specific instance group err = deployment.Stop( boshdir.NewAllOrInstanceGroupOrInstanceSlug("web", ""), boshdir.StopOpts{ Hard: false, // soft stop (process only) SkipDrain: false, Canaries: "1", MaxInFlight: "1", Converge: true, }, ) if err != nil { return err } // Restart a specific instance err = deployment.Restart( boshdir.NewAllOrInstanceGroupOrInstanceSlug("web", "0"), boshdir.RestartOpts{ SkipDrain: true, Canaries: "0", MaxInFlight: "100%", Converge: false, // act only on specified instance }, ) if err != nil { return err } // Recreate instances with fix option for unresponsive agents err = deployment.Recreate( boshdir.NewAllOrInstanceGroupOrInstanceSlug("", ""), boshdir.RecreateOpts{ Fix: true, SkipDrain: true, DryRun: false, Canaries: "1", MaxInFlight: "10%", Converge: true, }, ) return err } ``` -------------------------------- ### Demonstrate key collision error Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/peterbourgon/diskv/README.md Example of a key collision where a key resolves to a directory name instead of a file. ```go d.Write("abcabc", val) // OK: written to /abc/abc/abcabc d.Write("abc", val) // Error: attempted write to /abc/abc, but it's a directory ``` -------------------------------- ### Explicit and Localized Instrumentation Initialization Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Encapsulate instrumentation setup in constructor functions for clear ownership and scope. This ensures explicit, side-effect-free initialization. ```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 } ``` -------------------------------- ### Positional Args Writer Example (Java) Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/aws/smithy-go/AGENTS.md Demonstrates using positional arguments with `writer.write` and `writer.openBlock` for generating Go code. Arguments are referenced with '$'-prefixed format characters. ```java // $1L is used twice, $2L once — only 2 args needed writer.write("type $1L struct{}\nvar _ $2L = (*$1L)(nil)", DEFAULT_NAME, INTERFACE_NAME); ``` ```java writer.openBlock("func (c $P) $T(ctx $T) ($P, error) {", "}", serviceSymbol, operationSymbol, contextSymbol, outputSymbol, () -> { writer.write("return nil, nil"); }); ``` -------------------------------- ### Attribute and Option Allocation Management with sync.Pool Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md This Go code demonstrates pooling attribute slices and options using sync.Pool to minimize allocations during measurement calls with dynamic attributes. It includes the setup for attribute and add option pools and a record function utilizing these pools. ```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...) } ``` -------------------------------- ### Initialize and use diskv Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/peterbourgon/diskv/README.md Demonstrates basic initialization, writing, reading, and erasing data in a diskv store. ```go package main import ( "fmt" "github.com/peterbourgon/diskv" ) func main() { // Simplest transform function: put all the data files into the base dir. flatTransform := func(s string) []string { return []string{} } // Initialize a new diskv store, rooted at "my-data-dir", with a 1MB cache. d := diskv.New(diskv.Options{ BasePath: "my-data-dir", Transform: flatTransform, CacheSizeMax: 1024 * 1024, }) // Write three bytes to the key "alpha". key := "alpha" d.Write(key, []byte{'1', '2', '3'}) // Read the value back out of the store. value, _ := d.Read(key) fmt.Printf("%v\n", value) // Erase the key+value from the store (and the disk). d.Erase(key) } ``` -------------------------------- ### Preview Documentation Changes Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Builds and serves the Ginkgo documentation locally using Jekyll. Navigate to the `docs` directory to run this command. ```bash bundle && bundle exec jekyll serve ``` -------------------------------- ### Go get I/O Timeout Error Example Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/google.golang.org/grpc/README.md This console output shows a typical I/O timeout error when trying to 'go get' a package from golang.org, often due to network restrictions. ```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) ``` -------------------------------- ### List Instances with Details Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Lists instances in a deployment along with their detailed information, including VM and disk CIDs. Useful for troubleshooting and inventory. ```bash bosh -e my-bosh -d cf instances --details ``` -------------------------------- ### List Instances with Processes Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Lists instances in a deployment and includes information about the running processes on each instance. Helpful for debugging application processes. ```bash bosh -e my-bosh -d cf instances --ps ``` -------------------------------- ### Initialize Cloud Storage Client Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/cloud.google.com/go/storage/README.md Creates a new storage client instance. Ensure the context is properly configured before calling this method. ```go client, err := storage.NewClient(ctx) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Build Docker Image on VM Source: https://github.com/cloudfoundry/bosh-cli/blob/main/ci/docker/README.md Navigates to the BOSH directory, authenticates with Docker, and runs the build script. ```bash cd /opt/bosh docker login ... sudo ./build_docker_image.sh ``` -------------------------------- ### Access Remaining Arguments Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/spf13/pflag/README.md After parsing flags, access any remaining command-line arguments that were not consumed by flags. Use flag.Args() to get a slice of all remaining arguments or flag.Arg(i) to get a specific argument by index. ```go flag.Args() ``` ```go flag.Arg(i) ``` -------------------------------- ### Create a Director Client Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Initializes a Director client to manage BOSH resources. Requires a UAA client instance to handle token authentication automatically. ```go package main import ( "fmt" boshlog "github.com/cloudfoundry/bosh-utils/logger" boshdir "github.com/cloudfoundry/bosh-cli/v7/director" boshuaa "github.com/cloudfoundry/bosh-cli/v7/uaa" ) func buildDirector(uaa boshuaa.UAA) (boshdir.Director, error) { logger := boshlog.NewLogger(boshlog.LevelError) factory := boshdir.NewFactory(logger) // Build Director config from URL (HTTPS required) config, err := boshdir.NewConfigFromURL("https://192.168.50.6:25555") if err != nil { return nil, err } // Configure trusted CA certificates config.CACert = `-----BEGIN CERTIFICATE----- MIIDXzCCAkegAwIBAgIJAJLKKzS3Z2x3... -----END CERTIFICATE-----` // Allow Director to fetch UAA tokens automatically config.TokenFunc = boshuaa.NewClientTokenSession(uaa).TokenFunc return factory.New(config, boshdir.NewNoopTaskReporter(), boshdir.NewNoopFileReporter()) } func main() { uaa, _ := buildUAA() director, err := buildDirector(uaa) if err != nil { panic(err) } // Fetch Director information info, err := director.Info() if err != nil { panic(err) } fmt.Printf("Director Name: %s\n", info.Name) fmt.Printf("Director UUID: %s\n", info.UUID) fmt.Printf("Director Version: %s\n", info.Version) fmt.Printf("CPI: %s\n", info.CPI) } ``` -------------------------------- ### Manage BOSH Configuration with Go SDK Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt This Go code snippet demonstrates how to manage BOSH cloud and runtime configurations using the BOSH CLI's Go SDK. It covers fetching, updating, and diffing configurations, as well as listing existing configs. ```go package main import ( "fmt" boshdir "github.com/cloudfoundry/bosh-cli/v7/director" ) func manageConfigs(director boshdir.Director) error { // Get latest cloud config cloudConfig, err := director.LatestCloudConfig("") if err != nil { return err } fmt.Printf("Cloud Config:\n%s\n", cloudConfig) // Update cloud config newCloudConfig := []byte(` azs: - name: z1 cloud_properties: zone: us-central1-a vm_types: - name: default cloud_properties: machine_type: n1-standard-2 networks: - name: default type: manual subnets: - range: 10.0.0.0/24 gateway: 10.0.0.1 az: z1 `) err = director.UpdateCloudConfig("", newCloudConfig) if err != nil { return err } // Diff cloud config before applying diff, err := director.DiffCloudConfig("", newCloudConfig) if err != nil { return err } fmt.Printf("Cloud config diff:\n%v\n", diff.Diff) // Get runtime config runtimeConfig, err := director.LatestRuntimeConfig("") if err != nil { return err } fmt.Printf("Runtime Config:\n%s\n", runtimeConfig) // Update runtime config newRuntimeConfig := []byte(` releases: - name: bpm version: 1.1.15 addons: - name: bpm jobs: - name: bpm release: bpm `) err = director.UpdateRuntimeConfig("", newRuntimeConfig) if err != nil { return err } // List all configs configs, err := director.ListConfigs(10, boshdir.ConfigsFilter{ Type: "cloud", }) if err != nil { return err } fmt.Println("Configs:") for _, config := range configs { fmt.Printf("- %s/%s (ID: %s)\n", config.Type, config.Name, config.ID) } return nil } ``` -------------------------------- ### Mousetrap - StartedByExplorer Function Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/inconshreveable/mousetrap/README.md This function checks if the current process was started by a user double-clicking the executable in Windows Explorer. ```APIDOC ## StartedByExplorer Function ### Description Checks if the process was invoked by double-clicking the executable file in Windows Explorer. ### Method Function Call ### Endpoint N/A (Library function) ### Parameters None ### Request Example ```go import "github.com/cloudfoundry/bosh-cli/v7/common/mousetrap" func main() { if mousetrap.StartedByExplorer() { // Provide user-friendly instructions } } ``` ### Response #### Success Response (bool) - **bool** (bool) - Returns `true` if started by Explorer, `false` otherwise. #### Response Example ```json { "startedByExplorer": true } ``` ``` -------------------------------- ### Benchmark commands Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/cespare/xxhash/v2/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$') ``` -------------------------------- ### Clone opentelemetry-go with Git Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Alternatively, use `git clone` directly to get the project. Note that `git` does not use the `go.opentelemetry.io/otel` redirector name. ```sh git clone https://github.com/open-telemetry/opentelemetry-go ``` -------------------------------- ### Plug into existing code Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/fatih/color/README.md Use global Set and Unset functions to apply colors to subsequent standard output calls. ```go // Use handy standard colors color.Set(color.FgYellow) fmt.Println("Existing text will now be in yellow") fmt.Printf("This one %s\n", "too") color.Unset() // Don't forget to unset // You can mix up parameters color.Set(color.FgMagenta, color.Bold) defer color.Unset() // Use it in your function fmt.Println("All text will now be bold magenta.") ``` -------------------------------- ### Initialize and Use EWMA Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/VividCortex/ewma/README.md Demonstrates how to instantiate both SimpleEWMA and VariableEWMA types and add samples to calculate moving averages. ```go package main import "github.com/VividCortex/ewma" func main() { samples := [100]float64{ 4599, 5711, 4746, 4621, 5037, 4218, 4925, 4281, 5207, 5203, 5594, 5149, } e := ewma.NewMovingAverage() //=> Returns a SimpleEWMA if called without params a := ewma.NewMovingAverage(5) //=> returns a VariableEWMA with a decay of 2 / (5 + 1) for _, f := range samples { e.Add(f) a.Add(f) } e.Value() //=> 13.577404704631077 a.Value() //=> 1.5806140565521463e-12 } ``` -------------------------------- ### Get BOSH Deployment Manifest Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Retrieves the manifest of a specific BOSH deployment and outputs it to a file. This is useful for reviewing or backing up deployment configurations. ```bash bosh -e my-bosh -d cf manifest > manifest.yml ``` -------------------------------- ### Define Option Wrapper Signature Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Exported configuration functions should follow the With* or Without* naming convention. ```go func With*(…) Option { … } ``` -------------------------------- ### Handle protocol decoding errors Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/gopacket/gopacket/CONTRIBUTING.md Example of how to report errors during packet decoding, either by returning an error or adding an ErrorLayer to the packet builder. ```go func decodeMyProtocol(data []byte, p gopacket.PacketBuilder) error { prot := &MyProtocol{} if len(data) < 10 { // This error occurred before we did ANYTHING, so there's nothing in my // protocol that the caller could possibly want. Just return the error. return fmt.Errorf("Length %d less than 10", len(data)) } prot.ImportantField1 = data[:5] prot.ImportantField2 = data[5:10] // At this point, we've already got enough information in 'prot' to // warrant returning it to the caller, so we'll add it now. p.AddLayer(prot) if len(data) < 15 { // We encountered an error later in the packet, but the caller already // has the important info we've gleaned so far. return fmt.Errorf("Length %d less than 15", len(data)) } prot.ImportantField3 = data[10:15] return nil // We've already added the layer, we can just return success. } ``` -------------------------------- ### Define Instantiation Function Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use variadic options to configure object instantiation. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Validate Version Against Constraint Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/Masterminds/semver/v3/README.md Use this to validate a version against a constraint and get detailed error messages if validation fails. Ensure constraints and versions are parsed correctly before validation. ```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" } ``` -------------------------------- ### List Instances in Deployment Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Lists all instances within a specific deployment. This command helps in understanding the current state of your deployed applications. ```bash bosh -e my-bosh -d cf instances ``` -------------------------------- ### Run Gomega linter Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/onsi/gomega/CONTRIBUTING.md Check the codebase for potential issues using the Go vet tool. ```bash go vet ./... ``` -------------------------------- ### Check if Started by Explorer Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/inconshreveable/mousetrap/README.md Use this function to determine if the current process was launched by a user double-clicking the executable in Windows Explorer. This is useful for providing alternative user experiences for less technical users. ```Go func StartedByExplorer() (bool) ``` -------------------------------- ### Get Integer Value from FlagSet Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/spf13/pflag/README.md Retrieve the integer value of a flag from a specific FlagSet using GetInt(). This method requires the flag to exist and be of type int. It will return an error if these conditions are not met. ```go i, err := flagset.GetInt("flagname") ``` -------------------------------- ### Parse Command-Line Arguments with Go Flags Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/jessevdk/go-flags/README.md Parse command-line arguments into a struct using the flags.ParseArgs function. This example demonstrates various option types including slices, callbacks, required flags, choices, pointers, maps, and environment variables. ```go var opts struct { // Slice of bool will append 'true' each time the option // is encountered (can be set multiple times, like -vvv) Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` // Example of automatic marshalling to desired type (uint) Offset uint `long:"offset" description:"Offset"` // Example of a callback, called each time the option is found. Call func(string) `short:"c" description:"Call phone number"` // Example of a required flag Name string `short:"n" long:"name" description:"A name" required:"true"` // Example of a flag restricted to a pre-defined set of strings Animal string `long:"animal" choice:"cat" choice:"dog"` // Example of a value name File string `short:"f" long:"file" description:"A file" value-name:"FILE"` // Example of a pointer Ptr *int `short:"p" description:"A pointer to an integer"` // Example of a slice of strings StringSlice []string `short:"s" description:"A slice of strings"` // Example of a slice of pointers PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"` // Example of a map IntMap map[string]int `long:"intmap" description:"A map from string to int"` // Example of env variable Thresholds []int `long:"thresholds" default:"1" default:"2" env:"THRESHOLD_VALUES" env-delim:","` } // Callback which will invoke callto: to call a number. // Note that this works just on OS X (and probably only with // Skype) but it shows the idea. opts.Call = func(num string) { cmd := exec.Command("open", "callto:"+num) cmd.Start() cmd.Process.Release() } // Make some fake arguments to parse. args := []string{ "-vv", "--offset=5", "-n", "Me", "--animal", "dog", // anything other than "cat" or "dog" will raise an error "-p", "3", "-s", "hello", "-s", "world", "--ptrslice", "hello", "--ptrslice", "world", "--intmap", "a:1", "--intmap", "b:5", "arg1", "arg2", "arg3", } // Parse flags from `args'. Note that here we use flags.ParseArgs for // the sake of making a working example. Normally, you would simply use // flags.Parse(&opts) which uses os.Args args, err := flags.ParseArgs(&opts, args) if err != nil { panic(err) } fmt.Printf("Verbosity: %v\n", opts.Verbose) fmt.Printf("Offset: %d\n", opts.Offset) fmt.Printf("Name: %s\n", opts.Name) fmt.Printf("Animal: %s\n", opts.Animal) fmt.Printf("Ptr: %d\n", *opts.Ptr) fmt.Printf("StringSlice: %v\n", opts.StringSlice) fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1]) fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"]) fmt.Printf("Remaining args: %s\n", strings.Join(args, " ")) // Output: Verbosity: [true true] // Offset: 5 // Name: Me // Ptr: 3 // StringSlice: [hello world] // PtrSlice: [hello world] // IntMap: [a:1 b:5] // Remaining args: arg1 arg2 arg3 ``` -------------------------------- ### Instantiate a Fake Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/maxbrunsfeld/counterfeiter/v6/README.md Import the generated fakes package and instantiate the fake object. This fake can then be used in your tests. ```go import "my-repo/path/to/foo/foofakes" var fake = &foofakes.FakeMySpecialInterface{} ``` -------------------------------- ### Create BOSH Release Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Initializes a new BOSH release in the current directory. Requires specifying the release name and version. ```bash bosh create-release --name=my-release --version=1.0.0 ``` -------------------------------- ### Run Unit Tests (Go Runtime) Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/aws/smithy-go/AGENTS.md Execute unit tests for the Go runtime components of smithy-go. This command is used to verify the correctness of the Go packages. ```bash make unit ``` -------------------------------- ### Run Unit Tests Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/cloud.google.com/go/storage/TESTING.md Executes unit tests for the storage package using the short flag. ```bash go test ./google-cloud-go/storage -short ``` -------------------------------- ### List All VMs Across Deployments Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Displays all virtual machines managed by BOSH across all deployments. This provides a global view of your BOSH-managed infrastructure. ```bash bosh -e my-bosh vms ``` -------------------------------- ### Create a UAA Client for Authentication Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Initializes a UAA client using client credentials to obtain OAuth2 tokens. Requires an HTTPS URL and optional CA certificate configuration. ```go package main import ( "fmt" boshlog "github.com/cloudfoundry/bosh-utils/logger" boshuaa "github.com/cloudfoundry/bosh-cli/v7/uaa" ) func buildUAA() (boshuaa.UAA, error) { logger := boshlog.NewLogger(boshlog.LevelError) factory := boshuaa.NewFactory(logger) // Build a UAA config from a URL (HTTPS required) config, err := boshuaa.NewConfigFromURL("https://10.244.3.2:8443") if err != nil { return nil, err } // Set client credentials for machine-level access config.Client = "my-automation-script" config.ClientSecret = "my-secret" // Configure trusted CA certificates (optional) config.CACert = `-----BEGIN CERTIFICATE----- MIIDXzCCAkegAwIBAgIJAJLKKzS3Z2x3MA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV ... -----END CERTIFICATE-----` return factory.New(config) } func main() { uaa, err := buildUAA() if err != nil { panic(err) } // Get access token using client credentials token, err := uaa.ClientCredentialsGrant() if err != nil { panic(err) } fmt.Printf("Token Type: %s\n", token.Type()) fmt.Printf("Token Valid: %v\n", token.IsValid()) } ``` -------------------------------- ### View Original Interface File Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/maxbrunsfeld/counterfeiter/v6/README.md This command displays the content of the Go file containing the interface definition. ```shell $ cat path/to/foo/file.go ``` -------------------------------- ### List All Task Types Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Shows all available task types that BOSH can execute. This command is useful for understanding the full scope of BOSH operations. ```bash bosh -e my-bosh tasks --all ``` -------------------------------- ### Implement Instrumentation Initialization Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Return errors to the caller rather than handling them internally to allow for partial initialization usage. ```go func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } m := otel.GetMeterProvider().Meter(/* initialize meter */) counter, err := otelconv.NewSDKComponentCounter(m) // Use the partially initialized counter if available. i := &instrumentation{counter: counter} // Return any error to the caller. return i, err } ``` ```go // ❌ Avoid this pattern. func newInstrumentation() *instrumentation { if !x.Observability.Enabled() { return nil, nil } m := otel.GetMeterProvider().Meter(/* initialize meter */) counter, err := otelconv.NewSDKComponentCounter(m) if err != nil { // ❌ Do not dump the error to the OTel Handler. Return it to the // caller. otel.Handle(err) // ❌ Do not return nil if we can still use the partially initialized // counter. return nil } return &instrumentation{counter: counter} } ``` -------------------------------- ### Create BOSH Environment Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Use this command to create a new BOSH Director environment. Ensure you provide the correct path to the BOSH deployment manifest, state file, credentials file, CPI configuration, and director properties. ```bash bosh create-env bosh-deployment/bosh.yml \ --state=state.json \ --vars-store=creds.yml \ -o bosh-deployment/gcp/cpi.yml \ -v director_name=my-bosh \ -v internal_cidr=10.0.0.0/24 \ -v internal_gw=10.0.0.1 \ -v internal_ip=10.0.0.6 ``` -------------------------------- ### Check Version Against Constraints Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/Masterminds/semver/v3/README.md Parses a constraint string and a version string, then evaluates if the version satisfies the constraint. ```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) ``` -------------------------------- ### Implement Configuration Constructor Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Pattern for applying functional options to a configuration struct with default values. ```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 } ``` -------------------------------- ### Define Configuration Struct Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Standard structure for holding configuration options within a package. ```go // config contains configuration options for a thing. type config struct { // options ... } ``` -------------------------------- ### Run Gomega tests locally Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/github.com/onsi/gomega/CONTRIBUTING.md Execute all unit tests using Ginkgo to ensure code quality before submission. ```bash ginkgo -r -p ``` -------------------------------- ### Upload and Manage BOSH Releases Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt This function demonstrates how to list all releases, check if a release exists, retrieve its jobs and packages, upload releases from a URL or a local file, and delete a specific release. Ensure you have the correct release URL and SHA1 checksum for uploads. ```go package main import ( "fmt" "os" boshdir "github.com/cloudfoundry/bosh-cli/v7/director" ) func manageReleases(director boshdir.Director) error { // List all releases releases, err := director.Releases() if err != nil { return err } fmt.Println("Releases:") for _, rel := range releases { fmt.Printf("- %s/%s\n", rel.Name(), rel.Version()) // Check if release exists exists, _ := rel.Exists() fmt.Printf(" Exists: %v\n", exists) // Get jobs in release jobs, _ := rel.Jobs() for _, job := range jobs { fmt.Printf(" Job: %s (fingerprint: %s)\n", job.Name, job.Fingerprint) } // Get packages in release packages, _ := rel.Packages() for _, pkg := range packages { fmt.Printf(" Package: %s (fingerprint: %s)\n", pkg.Name, pkg.Fingerprint) } } // Upload release from URL err = director.UploadReleaseURL( "https://bosh.io/d/github.com/cloudfoundry/cf-release?v=287", "sha1:abc123...", // SHA1 checksum false, // rebase false, // fix ) if err != nil { return err } // Upload release from local file file, err := os.Open("/path/to/release.tgz") if err != nil { return err } defer file.Close() err = director.UploadReleaseFile(file, false, false) if err != nil { return err } // Find and delete a specific release releaseSlug := boshdir.NewReleaseSlug("my-release", "1.0.0") release, err := director.FindRelease(releaseSlug) if err != nil { return err } err = release.Delete(false) // force=false return err } ``` -------------------------------- ### Generate Files with mkall.sh Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/golang.org/x/sys/unix/README.md Use `mkall.sh` to generate Go files for the sys/unix package. Running with `-n` shows the commands without execution. Requires bash and go. ```bash mkall.sh ``` ```bash mkall.sh -n ``` -------------------------------- ### Run Pre-release Make Target Source: https://github.com/cloudfoundry/bosh-cli/blob/main/vendor/go.opentelemetry.io/otel/RELEASING.md Initiates the creation of a release branch for a specific module set. ```bash make prerelease MODSET= ``` -------------------------------- ### List and Manage BOSH Deployments Source: https://context7.com/cloudfoundry/bosh-cli/llms.txt Use this function to list all deployments, retrieve details about releases and stemcells used by each deployment, find a specific deployment by name, and access its manifest and instance information. ```go package main import ( "fmt" boshdir "github.com/cloudfoundry/bosh-cli/v7/director" ) func manageDeployments(director boshdir.Director) error { // List all deployments deployments, err := director.Deployments() if err != nil { return err } fmt.Println("Deployments:") for _, dep := range deployments { fmt.Printf("- %s\n", dep.Name()) // Get releases used by this deployment releases, _ := dep.Releases() for _, rel := range releases { fmt.Printf(" Release: %s/%s\n", rel.Name(), rel.Version()) } // Get stemcells used by this deployment stemcells, _ := dep.Stemcells() for _, stem := range stemcells { fmt.Printf(" Stemcell: %s/%s\n", stem.Name(), stem.Version()) } } // Find a specific deployment deployment, err := director.FindDeployment("cf-deployment") if err != nil { return err } // Get deployment manifest manifest, err := deployment.Manifest() if err != nil { return err } fmt.Printf("Manifest length: %d bytes\n", len(manifest)) // List instances in deployment instances, err := deployment.Instances() if err != nil { return err } fmt.Printf("Instance count: %d\n", len(instances)) return nil } ```