### Basic WebService Setup and Route Definition Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md Defines a new WebService, sets its path and supported content types, and defines a GET route for retrieving a user. This example demonstrates basic routing and parameter handling. ```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 jsonpointer library Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/go-openapi/jsonpointer/README.md Use the go get command to add the library to your project. ```cmd go get github.com/go-openapi/jsonpointer ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/shipwright-io/build/blob/main/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the v3 version of the yaml package. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install Shipwright Sample Strategies (Latest Release) Source: https://github.com/shipwright-io/build/blob/main/README.md Apply the sample strategies for the latest Shipwright Build release. These provide example build configurations. ```bash kubectl apply --filename https://github.com/shipwright-io/build/releases/download/v0.18.4/sample-strategies.yaml --server-side ``` -------------------------------- ### Install the yaml package Source: https://github.com/shipwright-io/build/blob/main/vendor/go.yaml.in/yaml/v2/README.md Use the go get command to install the package into your Go environment. ```bash go get go.yaml.in/yaml/v2 ``` -------------------------------- ### Install OTLP Prometheus Translator Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/prometheus/otlptranslator/README.md Install the library using the go get command. ```bash go get github.com/prometheus/otlptranslator ``` -------------------------------- ### Install Shipwright Sample Strategies (Nightly Release) Source: https://github.com/shipwright-io/build/blob/main/README.md Apply the sample strategies for the latest nightly Shipwright Build release. These provide example build configurations from the main branch. ```bash kubectl apply --filename "https://github.com/shipwright-io/build/releases/download/nightly/nightly-$(curl --silent --location https://github.com/shipwright-io/build/releases/download/nightly/latest.txt)-sample-strategies.yaml" --server-side ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/shipwright-io/build/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs and runs a local instance of the Go Doc site for previewing package documentation. Ensure you have Go installed and configured. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install uniseg Package Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/rivo/uniseg/README.md Use 'go get' to install the uniseg package for your Go project. ```bash go get github.com/rivo/uniseg ``` -------------------------------- ### Mknod Command Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the 'mknod' command to create a device node. ```shell mknod dev path ``` -------------------------------- ### Install Cobra Library Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/spf13/cobra/README.md Install the latest version of the Cobra library using go get. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install uuid package Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/google/uuid/README.md Use this command to install the package via go get. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install Ginkgo Locally Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Use 'go install' to install the Ginkgo CLI locally. Ensure you are in the project root directory. ```bash go install ./... ``` -------------------------------- ### Touch Command Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the 'touch' command to create or update a file. ```shell touch path ``` -------------------------------- ### Install and Import Kubernetes YAML Package Source: https://github.com/shipwright-io/build/blob/main/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 cpuid CLI Tool Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/klauspost/cpuid/v2/README.md Install the cpuid CLI tool from source using the go install command. Ensure you have Go installed and configured. ```bash go install github.com/klauspost/cpuid/v2/cmd/cpuid@latest ``` -------------------------------- ### Install Ginkgo Plugin Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/onsi/ginkgo/v2/CHANGELOG.md Use these commands to add and install the Ginkgo plugin from the marketplace. ```bash /plugin marketplace add onsi/ginkgo /plugin install ginkgo@ginkgo ``` -------------------------------- ### Connect go pprof to Profiling Data Source: https://github.com/shipwright-io/build/blob/main/docs/profiling.md Start a local web server using `go tool pprof` to browse profiling data. Ensure `graphviz` is installed for visualization. ```sh go tool pprof -http localhost:8080 http://localhost:8383/debug/pprof/heap ``` -------------------------------- ### Mkdir Command Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the 'mkdir' command to create a directory, with optional -p flag. ```shell mkdir [-p] dir ``` -------------------------------- ### Watch Command Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the 'watch' command to monitor a path for events. ```shell watch path [ops] ``` -------------------------------- ### Basic Merge Example Source: https://github.com/shipwright-io/build/blob/main/vendor/dario.cat/mergo/README.md A complete example demonstrating the default behavior of merging two structs. ```go package main import ( "fmt" "dario.cat/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } ``` -------------------------------- ### Clone and Setup Repository Source: https://github.com/shipwright-io/build/blob/main/vendor/go.uber.org/zap/CONTRIBUTING.md Initializes the local development environment by cloning the repository and configuring the upstream remote. ```bash mkdir -p $GOPATH/src/go.uber.org cd $GOPATH/src/go.uber.org git clone git@github.com:your_github_username/zap.git cd zap git remote add upstream https://github.com/uber-go/zap.git git fetch upstream ``` -------------------------------- ### Go Submodule Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md Demonstrates the submodule feature. ```go package main import ( "context" "log" "github.com/shipwright-io/build/pkg/client/clientset/versioned" ) func main() { ctx := context.Background() // Create a new clientset. clientset, err := clientset.NewForConfig(nil) if err != nil { log.Fatalf("Failed to create clientset: %v", err) } // Example usage of the submodule feature (replace with actual submodule operations) _ = clientset.ShipwrightV1alpha1().Builds( "default").Submodule(ctx, "my-build", "my-submodule") } ``` -------------------------------- ### Go Push Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md Demonstrates the push feature. ```go package main import ( "context" "log" "github.com/shipwright-io/build/pkg/client/clientset/versioned" ) func main() { ctx := context.Background() // Create a new clientset. clientset, err := clientset.NewForConfig(nil) if err != nil { log.Fatalf("Failed to create clientset: %v", err) } // Example usage of the push feature (replace with actual push operations) _ = clientset.ShipwrightV1alpha1().Builds( "default").Push(ctx, "my-build", "main") } ``` -------------------------------- ### Go Log Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md Demonstrates the log feature. ```go package main import ( "context" "log" "github.com/shipwright-io/build/pkg/client/clientset/versioned" ) func main() { ctx := context.Background() // Create a new clientset. clientset, err := clientset.NewForConfig(nil) if err != nil { log.Fatalf("Failed to create clientset: %v", err) } // Example usage of the log feature (replace with actual log operations) _ = clientset.ShipwrightV1alpha1().Builds( "default").Log(ctx, "my-build") } ``` -------------------------------- ### Go Tag Create and Push Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md Demonstrates creating and pushing a tag. ```go package main import ( "context" "log" "github.com/shipwright-io/build/pkg/client/clientset/versioned" ) func main() { ctx := context.Background() // Create a new clientset. clientset, err := clientset.NewForConfig(nil) if err != nil { log.Fatalf("Failed to create clientset: %v", err) } // Example usage of creating and pushing a tag (replace with actual operations) _ = clientset.ShipwrightV1alpha1().Builds( "default").TagCreatePush(ctx, "my-build", "v1.0.0") } ``` -------------------------------- ### Install multierr Package Source: https://github.com/shipwright-io/build/blob/main/vendor/go.uber.org/multierr/README.md Use `go get` to install the latest version of the multierr package. This command ensures you have the most up-to-date stable release. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Runtime Dockerfile Example Source: https://github.com/shipwright-io/build/blob/main/docs/proposals/runtime-image.md Illustrates a multi-stage Dockerfile for creating a runtime image, utilizing the output of a previous build stage and applying runtime configurations. ```dockerfile FROM output-image:tag as builder FROM runtime-image:tag ENV VARIABLE=value LABEL label=value RUN groupadd -g 1001 group RUN useradd -u 1001 -g group username COPY --chown="username:1001" --from=builder "/path/to/source" "/path/to/destination" USER username:1001 WORKDIR "/path/to/destination" ENTRYPOINT [ "command", "args" ] ``` -------------------------------- ### Install Latest JSON-Patch Source: https://github.com/shipwright-io/build/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get the latest version of the jsonpatch library for your Go project. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Go Branch Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md Demonstrates the usage of the branch feature. ```go package main import ( "context" "log" "github.com/shipwright-io/build/pkg/client/clientset/versioned" ) func main() { ctx := context.Background() // Create a new clientset. clientset, err := clientset.NewForConfig(nil) if err != nil { log.Fatalf("Failed to create clientset: %v", err) } // Example usage of the branch feature (replace with actual branch operations) _ = clientset.ShipwrightV1alpha1().Builds( "default").Branch(ctx, "my-build", "main") } ``` -------------------------------- ### Get Shipwright BuildRuns Source: https://github.com/shipwright-io/build/blob/main/README.md List Shipwright `BuildRun` objects to monitor their status. This command displays the name, success status, reason, start time, and completion time. ```bash $ kubectl get buildruns NAME SUCCEEDED REASON STARTTIME COMPLETIONTIME buildpack-nodejs-buildrun-xyzds True Succeeded 69s 2s ``` -------------------------------- ### Get/Set unsafe.Pointer with reflect2 Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/modern-go/reflect2/README.md This example shows how to get and set values using unsafe.Pointer with reflect2. Similar to interface{} operations, ensure you are using a pointer to the type for modifications. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.UnsafeSet(unsafe.Pointer(&i), unsafe.Pointer(&j)) // i will be 10 ``` -------------------------------- ### Basic Table Rendering in Go Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/jedib0t/go-pretty/v6/table/EXAMPLES.md Demonstrates the fundamental steps to create and render a table with headers, rows, and a footer. Ensure the 'os' and 'github.com/jedib0t/go-pretty/v6/table' packages are imported. ```golang package main import ( "os" "github.com/jedib0t/go-pretty/v6/table" ) func main() { t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{"#", "First Name", "Last Name", "Salary"}) t.AppendRows([]table.Row{ {1, "Arya", "Stark", 3000}, {20, "Jon", "Snow", 2000, "You know nothing, Jon Snow!"}, }) t.AppendSeparator() t.AppendRow([]interface{}{300, "Tyrion", "Lannister", 5000}) t.AppendFooter(table.Row{"", "", "Total", 10000}) t.Render() } ``` -------------------------------- ### Incorrect Go Module Dependency Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/antlr4-go/antlr/v4/README.md This example shows how `go get` might incorrectly resolve the ANTLR4 Go runtime version when imported directly from the main ANTLR4 repository, leading to unclear versioning and upgrade issues. ```go require ( github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230219212500-1f9a474cc2dc ) ``` -------------------------------- ### Quick Start: Translate OTLP Metric to Prometheus Format Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/prometheus/otlptranslator/README.md Demonstrates creating a metric namer with a specific strategy and translating an OTLP metric name and labels to Prometheus format. This example uses underscore escaping with suffixes and disallows UTF-8 characters. ```go package main import ( "fmt" "github.com/prometheus/otlptranslator" ) func main() { // Create a metric namer using traditional Prometheus name translation, with suffixes added and UTF-8 disallowed. strategy := otlptranslator.UnderscoreEscapingWithSuffixes namer := otlptranslator.NewMetricNamer("myapp", strategy) // Translate OTLP metric to Prometheus format metric := otlptranslator.Metric{ Name: "http.server.request.duration", Unit: "s", Type: otlptranslator.MetricTypeHistogram, } fmt.Println(namer.Build(metric)) // Output: myapp_http_server_request_duration_seconds // Translate label names labelNamer := otlptranslator.LabelNamer{UTF8Allowed: false} fmt.Println(labelNamer.Build("http.method")) // Output: http_method } ``` -------------------------------- ### Expressive Specs with Ginkgo and Gomega Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md This example demonstrates how to structure tests using Ginkgo's Describe, When, Context, and It blocks, along with Gomega matchers for assertions. It includes setup with BeforeEach and timeout specifications. Use this for defining complex test scenarios. ```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 json-iterator/go Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/json-iterator/go/README.md Command to fetch the package using the Go toolchain. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Stop Command Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the 'stop' command for debugging purposes. ```shell stop ``` -------------------------------- ### Go Remotes Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md Demonstrates the remotes feature. ```go package main import ( "context" "log" "github.com/shipwright-io/build/pkg/client/clientset/versioned" ) func main() { ctx := context.Background() // Create a new clientset. clientset, err := clientset.NewForConfig(nil) if err != nil { log.Fatalf("Failed to create clientset: %v", err) } // Example usage of the remotes feature (replace with actual remotes operations) _ = clientset.ShipwrightV1alpha1().Builds( "default").Remotes(ctx, "my-build") } ``` -------------------------------- ### Example Test Script Syntax Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Demonstrates the basic format for creating test cases using a shell-like syntax, including file operations and expected output. ```shell # Create a new empty file with some data. watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Echo Append Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the 'echo' command to append a string to a file. ```shell echo str >>path ``` -------------------------------- ### Build Resource with Runtime Configuration Source: https://github.com/shipwright-io/build/blob/main/docs/proposals/runtime-image.md Example of a Build resource specifying runtime configurations like base image, work directory, environment variables, labels, paths, user, and entrypoint. ```yaml --- apiVersion: build.dev/v1alpha1 kind: Build # ... spec: runtime: base: image: runtime-base-image:latest workDir: /workspace/source env: JAVA_HOME: /path/to/java-home labels: custom-image-label: value paths: - /path/to/file - /path/to/directory - /path/to/another/directory:/target/location user: name: username group: 1001 run: - groupadd -g 1001 group - useradd -u 1001 -g group username entrypoint: - java - -jar - ... ``` -------------------------------- ### Mkfifo Command Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the 'mkfifo' command to create a named pipe. ```shell mkfifo path ``` -------------------------------- ### Go Checkout Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md Demonstrates basic usages of the checkout feature. ```go package main import ( "context" "log" "github.com/shipwright-io/build/pkg/client/clientset/versioned" ) func main() { ctx := context.Background() // Create a new clientset. clientset, err := clientset.NewForConfig(nil) if err != nil { log.Fatalf("Failed to create clientset: %v", err) } // Example usage of the checkout feature (replace with actual checkout operations) _ = clientset.ShipwrightV1alpha1().Builds( "default").Checkout(ctx, "my-build", "main") } ``` -------------------------------- ### Debug Command Example Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of the 'debug' command to enable or disable FSNOTIFY_DEBUG. ```shell debug [yes/no] ``` -------------------------------- ### List Tags for a Repository Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/README.md This example shows how to list tags for a specific repository (e.g., gcr.io/google-containers/pause) using the go-containerregistry package. It demonstrates fetching credentials, constructing an authorized HTTP client, making the request, checking for errors, and writing the response to standard output. ```go package main import ( "io" "net/http" "os" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote/transport" ) func main() { repo, err := name.NewRepository("gcr.io/google-containers/pause") if err != nil { panic(err) } // Fetch credentials based on your docker config file, which is $HOME/.docker/config.json or $DOCKER_CONFIG. auth, err := authn.DefaultKeychain.Resolve(repo.Registry) if err != nil { panic(err) } // Construct an http.Client that is authorized to pull from gcr.io/google-containers/pause. scopes := []string{repo.Scope(transport.PullScope)} t, err := transport.New(repo.Registry, auth, http.DefaultTransport, scopes) if err != nil { panic(err) } client := &http.Client{Transport: t} // Make the actual request. resp, err := client.Get("https://gcr.io/v2/google-containers/pause/tags/list") if err != nil { panic(err) } // Assert that we get a 200, otherwise attempt to parse body as a structured error. if err := transport.CheckError(resp, http.StatusOK); err != nil { panic(err) } // Write the response to stdout. if _, err := io.Copy(os.Stdout, resp.Body); err != nil { panic(err) } } ``` -------------------------------- ### Applying Predefined Table Styles in Go Source: https://github.com/shipwright-io/build/blob/main/vendor/github.com/jedib0t/go-pretty/v6/table/EXAMPLES.md Shows how to apply ready-to-use table styles like StyleLight and StyleColoredBright. Import the 'github.com/jedib0t/go-pretty/v6/table' package. ```golang t.SetStyle(table.StyleLight) t.Render() ``` ```golang t.SetStyle(table.StyleColoredBright) t.Render() ```