### Install color package Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/cppforlife/color/README.md Use 'go get' to install the color package. ```bash go get github.com/fatih/color ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/mattn/go-isatty/README.md Install the go-isatty package using the go get command. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Install go-version Library Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/hashicorp/go-version/README.md Install the go-version library using the standard Go get command. This is the initial step before using the library in your project. ```bash $ go get github.com/hashicorp/go-version ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/go.yaml.in/yaml/v3/README.md Install the yaml package for Go using the go get command. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install difflib Go Library Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/carvel-dev/difflib/README.md Use 'go get' to install the difflib library. Ensure your Go environment is set up correctly. ```bash go get github.com/aryann/difflib ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/json-iterator/go/README.md Install the json-iterator/go library using the go get command. ```go go get github.com/json-iterator/go ``` -------------------------------- ### Install and Import YAML Package Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/sigs.k8s.io/yaml/README.md Install the package using go get and import it into your Go project. ```bash $ go get sigs.k8s.io/yaml ``` ```go import "sigs.k8s.io/yaml" ``` -------------------------------- ### Install Cobra Library Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/spf13/cobra/README.md Install the latest version of the Cobra library using go get. ```go go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Installing go-colorable Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/mattn/go-colorable/README.md Installs the go-colorable package using the go get command. This is the standard method for adding Go packages to your project. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Define a WebService and a Route Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/emicklei/go-restful/v3/README.md Example demonstrating how to define a WebService, set its path and supported content types, and add a GET route with a path parameter. The route is mapped to a handler function 'findUser'. ```go ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser). Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Writes(User{})) ... func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... } ``` -------------------------------- ### Install uuid Package Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/google/uuid/README.md Use 'go get' to install the uuid package. This command fetches and installs the package and its dependencies. ```sh go get github.com/google/uuid ``` -------------------------------- ### Coexist with klog/v1 and klog/v2 Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/klog/v2/README.md This example demonstrates how to manage coexistence between klog/v1 and klog/v2 within the same project. Refer to the `examples/coexist_klog_v1_and_v2/` directory for the implementation. ```go // See examples/coexist_klog_v1_and_v2/ ``` -------------------------------- ### User Resource Example Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/emicklei/go-restful/v3/README.md Example demonstrating how to define a WebService for user resources, including path parameters, content types, and route definitions. ```APIDOC ## GET /users/{user-id} ### Description Retrieves a specific user resource based on its identifier. ### Method GET ### Endpoint /users/{user-id} ### Parameters #### Path Parameters - **user-id** (string) - Required - identifier of the user ### Response #### Success Response (200) - **User{}** (User) - Represents the user resource. ### Request Example ```json { "example": "No request body for GET" } ``` ### Response Example ```json { "example": "{\"id\": \"123\", \"name\": \"John Doe\"}" } ``` ``` -------------------------------- ### Initialize Procfs and Get Stat Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to get basic system CPU information. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Check Version Against Constraints in Go Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/hashicorp/go-version/README.md Shows how to create version constraints and check if a given version satisfies them. The example uses a range constraint. ```go v1, err := version.NewVersion("1.2") // Constraints example. constraints, err := version.NewConstraint(">= 1.0, < 1.4") if constraints.Check(v1) { fmt.Printf("%s satisfies constraints %s", v1, constraints) } ``` -------------------------------- ### Deploy STS Alternative with ytt and kapp Source: https://github.com/carvel-dev/kapp/blob/develop/examples/sts-alternative/README.md Use this command to deploy the STS alternative example. It pipes the output of ytt to kapp for deployment. ```bash kapp deploy -a redis -f <(ytt -f examples/sts-alternative) ``` -------------------------------- ### Install Latest JSON-Patch (v5) Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get the latest version of the json-patch library for your Go project. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/spf13/cobra/README.md Install the cobra-cli command line program, used for generating Cobra application scaffolding. ```go go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Coexist with glog Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/klog/v2/README.md This example shows how to initialize and synchronize flags between klog and glog using the global `flag.CommandLine` FlagSet. It also configures `alsologtostderr` (or `logtostderr`) to true for combined stderr output. ```go // See examples/coexist_glog/coexist_glog.go ``` -------------------------------- ### Example using TagSet and TagOptions Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/fxamacker/cbor/v2/README.md Illustrates creating a TagSet, adding custom tag options for COSE_Sign1 (tag 18), and using it to create DecMode and EncMode for unmarshalling and marshalling data with tag support. ```go // Use signedCWT struct defined in "Decoding CWT" example. // Create TagSet (safe for concurrency). tags := cbor.NewTagSet() // Register tag COSE_Sign1 18 with signedCWT type. tags.Add( cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, reflect.TypeOf(signedCWT{}), 18) // Create DecMode with immutable tags. dm, _ := cbor.DecOptions{}.DecModeWithTags(tags) // Unmarshal to signedCWT with tag support. var v signedCWT if err := dm.Unmarshal(data, &v); err != nil { return err } // Create EncMode with immutable tags. em, _ := cbor.EncOptions{}.EncModeWithTags(tags) // Marshal signedCWT with tag number. if data, err := em.Marshal(v); err != nil { return err } ``` -------------------------------- ### Initialize Block Device FS and Get Disk Stats Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/prometheus/procfs/README.md Initializes a filesystem object requiring both /proc and /sys, then retrieves disk statistics. Use this for block device metrics that span both filesystems. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Download Pinniped v0.32.0 Configuration Source: https://github.com/carvel-dev/kapp/blob/develop/examples/pinniped-v0.32.0/README.md Use ytt to download the Pinniped v0.32.0 installation configuration files and combine them into a single config.yml file. ```bash ytt \ -f https://get.pinniped.dev/v0.32.0/install-pinniped-concierge.yaml \ -f https://get.pinniped.dev/v0.32.0/install-local-user-authenticator.yaml \ -f https://get.pinniped.dev/v0.32.0/install-pinniped-supervisor.yaml > config.yml ``` -------------------------------- ### Verbose Logging with Data Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/klog/v2/README.md Log verbose messages including data, using Infoln for space-separated output. This example logs when verbosity is set to 2 or higher. ```go glog.V(2).Infoln("Processed", nItems, "elements") ``` -------------------------------- ### Run difflib Demo Application Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/carvel-dev/difflib/README.md Execute the provided demo application by running the Go program with two file paths as arguments. This launches a web server displaying diff results. ```bash go run src/github.com/aryann/difflib/difflib_server/difflib_demo.go ``` -------------------------------- ### Deprecating a Flag Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/spf13/pflag/README.md Example of how to mark a flag as deprecated, providing a message to guide users to an alternative flag. ```go // deprecate a flag by specifying its name and a usage message flags.MarkDeprecated("badflag", "please use --good-flag instead") ``` -------------------------------- ### Trace Introspection Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/utils/trace/README.md Provides examples of how to get the total elapsed time of a trace and how to unconditionally log the trace details. ```go opTrace.TotalTime() // Duration since the Trace was created ``` ```go opTrace.Log() // unconditionally log the trace ``` -------------------------------- ### Install Specific JSON-Patch Version (v4) Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command if you need to install a specific older version of the json-patch library. ```bash go get -u gopkg.in/evanphx/json-patch.v4 ``` -------------------------------- ### Parse and Compare Versions in Go Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/hashicorp/go-version/README.md Demonstrates how to parse version strings into Version objects and compare them using LessThan. Ensure error handling for NewVersion calls in production code. ```go v1, err := version.NewVersion("1.2") v2, err := version.NewVersion("1.5+metadata") // Comparison example. There is also GreaterThan, Equal, and just // a simple Compare that returns an int allowing easy >=, <=, etc. if v1.LessThan(v2) { fmt.Printf("%s is less than %s", v1, v2) } ``` -------------------------------- ### Even Slice Length Validator Example Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a generic validator function that ensures a slice has an even number of items. It can be used with any type T. ```go // Even validates that a slice has an even number of items. func Even[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList ``` -------------------------------- ### NonEmpty Validator Example Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a validator function that checks if a string value is not empty. It takes context, operation, field path, and the string value as input. ```go // NonEmpty validates that a string is not empty. func NonEmpty(ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList ``` -------------------------------- ### Create a New Trace Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/utils/trace/README.md Demonstrates how to create a new trace with an initial operation name and fields. A defer statement ensures the trace is logged if its duration exceeds the specified limit. ```go func doSomething() { opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"}) defer opTrace.LogIfLong(100 * time.Millisecond) // do something } ``` -------------------------------- ### Map Keys Max Length Validator Example Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a generic validator function that checks if all string keys in a map are below a specified maximum length. It accepts a map with string keys and any value type T. ```go // KeysMaxLen validates that all of the string keys in a map are under the // specified length. func KeysMaxLen[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ map[string]T, maxLen int) field.ErrorList ``` -------------------------------- ### Run Benchmarks Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/go-openapi/swag/BENCHMARK.md Command to execute benchmarks for the go-openapi/swag package. Use -bench XXX to specify benchmark functions and -run XXX to skip tests. ```bash go test -bench XXX -run XXX -benchtime 30s ``` -------------------------------- ### Example using Embedded JSON Tag for CBOR (tag 262) Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/fxamacker/cbor/v2/README.md Demonstrates encoding and decoding a tagged CBOR data item with tag number 262, where the tag content is a JSON object embedded as a CBOR byte string. This example defines custom MarshalCBOR and UnmarshalCBOR methods. ```go // https://github.com/fxamacker/cbor/issues/657 package cbor_test // NOTE: RFC 8949 does not mention tag number 262. IANA assigned // CBOR tag number 262 as "Embedded JSON Object" specified by the // document Embedded JSON Tag for CBOR: // // "Tag 262 can be applied to a byte string (major type 2) to indicate // that the byte string is a JSON Object. The length of the byte string // indicates the content." // // For more info, see Embedded JSON Tag for CBOR at: // https://github.com/toravir/CBOR-Tag-Specs/blob/master/embeddedJSON.md import ( "bytes" "encoding/json" "fmt" "github.com/fxamacker/cbor/v2" ) // cborTagNumForEmbeddedJSON is the CBOR tag number 262. const cborTagNumForEmbeddedJSON = 262 // EmbeddedJSON represents a Go value to be encoded as a tagged CBOR data item // with tag number 262 and the tag content is a JSON object "embedded" as a // CBOR byte string (major type 2). type EmbeddedJSON struct { any } func NewEmbeddedJSON(val any) EmbeddedJSON { return EmbeddedJSON{val} } // MarshalCBOR encodes EmbeddedJSON to a tagged CBOR data item with the // tag number 262 and the tag content is a JSON object that is // "embedded" as a CBOR byte string. func (v EmbeddedJSON) MarshalCBOR() ([]byte, error) { // Encode v to JSON object. data, err := json.Marshal(v) if err != nil { return nil, err } // Create cbor.Tag representing a tagged CBOR data item. tag := cbor.Tag{ Number: cborTagNumForEmbeddedJSON, Content: data, } // Marshal to a tagged CBOR data item. return cbor.Marshal(tag) } // UnmarshalCBOR decodes a tagged CBOR data item to EmbeddedJSON. // The byte slice provided to this function must contain a single // tagged CBOR data item with the tag number 262 and tag content // must be a JSON object "embedded" as a CBOR byte string. func (v *EmbeddedJSON) UnmarshalCBOR(b []byte) error { // Unmarshal tagged CBOR data item. var tag cbor.Tag if err := cbor.Unmarshal(b, &tag); err != nil { return err } // Check tag number. if tag.Number != cborTagNumForEmbeddedJSON { return fmt.Errorf("got tag number %d, expect tag number %d", tag.Number, cborTagNumForEmbeddedJSON) } // Check tag content. jsonData, isByteString := tag.Content.([]byte) if !isByteString { return fmt.Errorf("got tag content type %T, expect tag content []byte", tag.Content) } // Unmarshal JSON object. return json.Unmarshal(jsonData, v) } // MarshalJSON encodes EmbeddedJSON to a JSON object. func (v EmbeddedJSON) MarshalJSON() ([]byte, error) { return json.Marshal(v.any) } // UnmarshalJSON decodes a JSON object. func (v *EmbeddedJSON) UnmarshalJSON(b []byte) error { dec := json.NewDecoder(bytes.NewReader(b)) dec.UseNumber() return dec.Decode(&v.any) } func Example_embeddedJSONTagForCBOR() { value := NewEmbeddedJSON(map[string]any{ "name": "gopher", "id": json.Number("42"), }) data, err := cbor.Marshal(value) if err != nil { panic(err) } fmt.Printf("cbor: %x\n", data) var v EmbeddedJSON err = cbor.Unmarshal(data, &v) if err != nil { panic(err) } ``` -------------------------------- ### Create Root Logger Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/go-logr/logr/README.md Initialize the root logger with a specific implementation and parameters early in the application's lifecycle. ```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 ... } ``` -------------------------------- ### Redirect klog Output Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/klog/v2/README.md Use the `klog.SetOutput()` method to redirect all klog output to a custom `io.Writer`, such as syslog. See `examples/set_output/usage_set_output.go` for an example. ```go // See examples/set_output/usage_set_output.go ``` -------------------------------- ### Log to a Single File with klog Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/klog/v2/README.md Use the `log_file` option instead of `log_dir` to direct logs to a single file. Refer to the `examples/log_file/usage_log_file.go` for detailed usage. ```go // See examples/log_file/usage_log_file.go ``` -------------------------------- ### Split Trace into Steps Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/utils/trace/README.md Shows how to divide a single trace into multiple sequential steps, logging each step with its own name and optional fields. This is useful for tracking progress within a larger operation. ```go func doSomething() { opTrace := trace.New("operation") defer opTrace.LogIfLong(100 * time.Millisecond) // do step 1 opTrace.Step("step1", Field{Key: "stepFieldKey1", Value: "stepFieldValue1"}) // do step 2 opTrace.Step("step2") } ``` -------------------------------- ### xxhash Benchmarking Commands Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/cespare/xxhash/v2/README.md Commands to benchmark the pure Go and assembly implementations of the Sum64 function. Use benchstat to analyze the results. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Get integer value from FlagSet Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/spf13/pflag/README.md Retrieve the integer value of a flag from a FlagSet using GetInt. This requires the flag to exist and be of type int. ```go i, err := flagset.GetInt("flagname") ``` -------------------------------- ### Format Code with Make Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/spf13/cobra/CONTRIBUTING.md Ensure code consistency by running the 'make all' command, which formats the Go code according to project standards. ```bash make all ``` -------------------------------- ### Create and Apply a Merge Patch in Go Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/gopkg.in/evanphx/json-patch.v4/README.md Demonstrates how to create a JSON merge patch from two documents and then apply that patch to a third document. Requires the jsonpatch library. ```go package main import ( "fmt" jsonpatch "github.com/evanphx/json-patch" ) func main() { // Let's create a merge patch from these two documents... original := []byte(`{"name": "John", "age": 24, "height": 3.21}`) target := []byte(`{"name": "Jane", "age": 24}`) patch, err := jsonpatch.CreateMergePatch(original, target) if err != nil { panic(err) } // Now lets apply the patch against a different JSON document... alternative := []byte(`{"name": "Tina", "age": 28, "height": 3.75}`) modifiedAlternative, err := jsonpatch.MergePatch(alternative, patch) fmt.Printf("patch document: %s\n", patch) fmt.Printf("updated alternative doc: %s\n", modifiedAlternative) } ``` -------------------------------- ### Basic Info Log Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/klog/v2/README.md Use glog.Info for standard informational messages. ```go glog.Info("Prepare to repel boarders") ``` -------------------------------- ### Get/Set interface{} Value using reflect2 Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/modern-go/reflect2/README.md To get and set values of interface{} types, always use their pointers. This method provides type checking during the operation. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 ``` -------------------------------- ### Clone cf-for-k8s and Generate Configuration Source: https://github.com/carvel-dev/kapp/blob/develop/examples/cf-for-k8s-v0.2.0-custom/README.md Clone the repository, generate values using a script, and then use ytt to create the final configuration file. Note that secrets in the generated config.yml are temporary. ```bash git clone https://github.com/cloudfoundry/cf-for-k8s # was 86f5a6ed49ff6f132104c52c4a983b202c304211 at the time cd cf-for-k8s ./hack/generate-values.sh -d cf.cppforlife.io > /tmp/cf-vals.yml ytt -f config/ -f /tmp/cf-vals.yml > config.yml ``` -------------------------------- ### Import and Use difflib in Go Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/carvel-dev/difflib/README.md Import the difflib package and use its functions like HTMLDiff to compare string slices. This example shows a basic usage scenario. ```go import ( ... "fmt" "github.com/aryann/difflib" ... ) fmt.Println(difflib.HTMLDiff([]string{"one", "two", "three"}, []string{"two", "four", "three"})) ``` -------------------------------- ### Basic Word Wrapping Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/mitchellh/go-wordwrap/README.md Demonstrates the basic usage of WrapString to wrap a given string to a specified width. This is useful for formatting CLI output. ```go wrapped := wordwrap.WrapString("foo bar baz", 3) fmt.Println(wrapped) ``` -------------------------------- ### Add or Update Go Module Dependency Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use 'go get' to manage external package dependencies. This command fetches the latest tagged release or a specific version. ```bash # Pick the latest tagged release. go get example.com/some/module/pkg # Pick a specific version. go get example.com/some/module/pkg@vX.Y.Z ``` -------------------------------- ### Get/Set unsafe.Pointer Value using reflect2 Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/modern-go/reflect2/README.md To get and set values using unsafe.Pointer, always use the pointer to the type. This method bypasses type checking for performance. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.UnsafeSet(unsafe.Pointer(&i), unsafe.Pointer(&j)) // i will be 10 ``` -------------------------------- ### Use fmt.Sprintf for logr key values Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/go-logr/logr/README.md When absolutely necessary, use fmt.Sprintf to format values for logr keys, though this should be infrequent. ```go logger.Info("unable to reflect over type", "type", fmt.Sprintf("%T")) ``` -------------------------------- ### Using go-colorable with logrus Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/mattn/go-colorable/README.md Integrates go-colorable with the logrus logger to force color output on Windows. This setup ensures that log messages with color codes are displayed correctly. ```go logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) lugrus.SetOutput(colorable.NewColorableStdout()) lugrus.Info("succeeded") lugrus.Warn("not correct") lugrus.Error("something error") lugrus.Fatal("panic") ``` -------------------------------- ### Check if Started by Explorer Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/inconshreveable/mousetrap/README.md Use this function to determine if the current process was initiated by a double-click in Windows Explorer. This is useful for providing alternative user experiences for GUI-oriented users. ```go func StartedByExplorer() (bool) ``` -------------------------------- ### Sort Versions in Go Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/hashicorp/go-version/README.md Illustrates how to sort a slice of version strings using the go-version library's Collection type. This ensures proper ordering, including prerelease versions. ```go versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"} versions := make([]*version.Version, len(versionsRaw)) for i, raw := range versionsRaw { v, _ := version.NewVersion(raw) versions[i] = v } // After this, the versions are properly sorted sort.Sort(version.Collection(versions)) ``` -------------------------------- ### Conditional Verbose Logging (Level 2) Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/k8s.io/klog/v2/README.md Use glog.V(level) to conditionally log messages based on verbosity level. This example logs when verbosity is set to 2 or higher. ```go if glog.V(2) { glog.Info("Starting transaction...") } ``` -------------------------------- ### Using concurrent.Map Source: https://github.com/carvel-dev/kapp/blob/develop/vendor/github.com/modern-go/concurrent/README.md Demonstrates basic usage of concurrent.Map for storing and retrieving key-value pairs, suitable for Go versions prior to 1.9. ```go m := concurrent.NewMap() m.Store("hello", "world") elem, found := m.Load("hello") // elem will be "world" // found will be true ``` -------------------------------- ### Get Redis Max Memory Configuration Source: https://github.com/carvel-dev/kapp/blob/develop/examples/gitops/redis-with-configmap/README.md Executes `redis-cli` within a Redis pod to retrieve the current `maxmemory` setting. This command is useful for verifying the configuration applied via the ConfigMap. ```bash kubectl exec -it redis redis-cli 127.0.0.1:6379> CONFIG GET maxmemory 1) "maxmemory" 2) "2097152" ```