### Install and run example program Source: https://github.com/activestate/cli/blob/master/vendor/github.com/go-ole/go-ole/README.md Commands to get the go-ole package, run tests, and execute the Excel example. ```bash go get github.com/go-ole/go-ole cd /path/to/go-ole/ go test cd /path/to/go-ole/example/excel go run excel.go ``` -------------------------------- ### Echo quick start example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/labstack/echo/v4/README.md Minimal Echo server with RequestLogger and Recover middleware, a GET route, and graceful shutdown handling. The handler returns a plain text response. ```go package main import ( "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "log/slog" "net/http" ) func main() { // Echo instance e := echo.New() // Middleware e.Use(middleware.RequestLogger()) // use the default RequestLogger middleware with slog logger e.Use(middleware.Recover()) // recover panics as errors for proper error handling // Routes e.GET("/", hello) // Start server if err := e.Start(":8080"); err != nil && !errors.Is(err, http.ErrServerClosed) { slog.Error("failed to start server", "error", err) } } // Handler func hello(c echo.Context) error { return c.String(http.StatusOK, "Hello, World!") } ``` -------------------------------- ### Install Afero with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/spf13/afero/README.md Install the Afero package using the go get command. ```bash go get github.com/spf13/afero ``` -------------------------------- ### Install plist with go get Source: https://github.com/activestate/cli/blob/master/vendor/howett.net/plist/README.md Install the plist package using the go get command. ```shell $ go get howett.net/plist ``` -------------------------------- ### Install go-version with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/hashicorp/go-version/README.md Install the go-version library using the standard go get command. ```shell $ go get github.com/hashicorp/go-version ``` -------------------------------- ### Install go-funk with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Install the go-funk library using the go get command. ```bash go get github.com/thoas/go-funk ``` -------------------------------- ### Simple Example: Registering a GET Responder Source: https://github.com/activestate/cli/blob/master/vendor/github.com/jarcoal/httpmock/README.md Shows the basic usage of httpmock: activate, register a responder for a GET request, and check call counts. Use this as a starting point for mocking HTTP in tests. ```go func TestFetchArticles(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json", httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`)) // get count info httpmock.GetTotalCallCount() // get the amount of calls for the registered responder info := httpmock.GetCallCountInfo() info["GET https://api.mybiz.com/articles.json"] // number of GET calls made to https://api.mybiz.com/articles.json // do stuff that makes a request to articles.json } ``` -------------------------------- ### Install go-colorable with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/mattn/go-colorable/README.md Install the go-colorable package using the go get command. ```shell $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Install pgzip with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/klauspost/pgzip/README.md Install the pgzip package using the go get command. ```bash go get github.com/klauspost/pgzip/... ``` -------------------------------- ### Install go-capturer with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/kami-zh/go-capturer/README.md Install the go-capturer package using the go get command. ```shell $ go get github.com/kami-zh/go-capturer ``` -------------------------------- ### Install termenv with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/muesli/termenv/README.md Install the termenv library using the go get command. ```bash go get github.com/muesli/termenv ``` -------------------------------- ### Install pflag with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/spf13/pflag/README.md Install the pflag package using the standard go get command. ```bash go get github.com/spf13/pflag ``` -------------------------------- ### Install govalidator with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/asaskevich/govalidator/README.md Install the govalidator package using the standard go get command, or fetch a specific release via gopkg.in. ```bash go get github.com/asaskevich/govalidator ``` ```bash go get gopkg.in/asaskevich/govalidator.v10 ``` -------------------------------- ### Install go-colorful with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/lucasb-eyer/go-colorful/README.md Use this command to install the go-colorful library. It fetches the package from the repository. ```bash $ go get github.com/lucasb-eyer/go-colorful ``` -------------------------------- ### Install mholt/archives with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/mholt/archives/README.md Install the library using the standard Go package manager command. ```bash $ go get github.com/mholt/archives ``` -------------------------------- ### Install semver with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/blang/semver/README.md Install the semver library using go get. Always vendor your dependencies or fix on a specific version tag. ```bash $ go get github.com/blang/semver ``` -------------------------------- ### Install gxz command-line tool with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/ulikunitz/xz/README.md Command to install the gxz command-line utility from the package repository using go get. ```shell $ go get github.com/ulikunitz/xz/cmd/gxz ``` -------------------------------- ### Ginkgo Example: Setup and Test Files Source: https://github.com/activestate/cli/blob/master/vendor/github.com/jarcoal/httpmock/README.md Shows how to integrate httpmock with Ginkgo: activate in BeforeSuite, reset in BeforeEach, and deactivate in AfterSuite. The test file registers a responder and makes a request. ```go // article_suite_test.go import ( // ... "github.com/jarcoal/httpmock" ) // ... var _ = BeforeSuite(func() { // block all HTTP requests httpmock.Activate() }) var _ = BeforeEach(func() { // remove any mocks httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) // article_test.go import ( // ... "github.com/jarcoal/httpmock" ) var _ = Describe("Articles", func() { It("returns a list of articles", func() { httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json", httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`)) // do stuff that makes a request to articles.json }) }) ``` -------------------------------- ### First-time build setup Source: https://github.com/activestate/cli/blob/master/readme.md First-time setup commands for building State Tool from source. Run these before building if you are building for the first time. ```bash state run install-deps-dev ``` ```bash state run preprocess ``` -------------------------------- ### Install gommon/bytes with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/labstack/gommon/bytes/README.md Install the gommon/bytes package using the go get command. ```go go get github.com/labstack/gommon/bytes ``` -------------------------------- ### Install go-isatty with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/mattn/go-isatty/README.md Command to install the go-isatty package using the Go package manager. ```shell $ go get github.com/mattn/go-isatty ``` -------------------------------- ### Install sqlite with go get Source: https://github.com/activestate/cli/blob/master/vendor/modernc.org/sqlite/README.md Use this command to install the sqlite package. It is the standard Go module installation command. ```shell $ go get modernc.org/sqlite ``` -------------------------------- ### Install ULID with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/oklog/ulid/README.md Install the ULID library using the Go module tool. ```shell go get github.com/oklog/ulid ``` -------------------------------- ### Install ansi with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/mgutz/ansi/README.md Clone and install the ansi package using 'go get -u github.com/mgutz/ansi'. ```sh go get -u github.com/mgutz/ansi ``` -------------------------------- ### Installation command for dsnet/compress Source: https://github.com/activestate/cli/blob/master/vendor/github.com/dsnet/compress/README.md Run this command to install the library. Requires Go1.9 or higher. ```go go get -u github.com/dsnet/compress ``` -------------------------------- ### Full semver example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/blang/semver/README.md Full example showing version creation, accessing major/minor/patch/pre/build fields, iterating prerelease and build arrays, comparison helpers (GT, LT, GTE, LTE), Compare method, in-place manipulation with NewPRVersion, and validation with Validate. ```go import github.com/blang/semver v, err := semver.Make("0.0.1-alpha.preview+123.github") fmt.Printf("Major: %d\n", v.Major) fmt.Printf("Minor: %d\n", v.Minor) fmt.Printf("Patch: %d\n", v.Patch) fmt.Printf("Pre: %s\n", v.Pre) fmt.Printf("Build: %s\n", v.Build) // Prerelease versions array if len(v.Pre) > 0 { fmt.Println("Prerelease versions:") for i, pre := range v.Pre { fmt.Printf("%d: %q\n", i, pre) } } // Build meta data array if len(v.Build) > 0 { fmt.Println("Build meta data:") for i, build := range v.Build { fmt.Printf("%d: %q\n", i, build) } } v001, err := semver.Make("0.0.1") // Compare using helpers: v.GT(v2), v.LT, v.GTE, v.LTE v001.GT(v) == true v.LT(v001) == true v.GTE(v) == true v.LTE(v) == true // Or use v.Compare(v2) for comparisons (-1, 0, 1): v001.Compare(v) == 1 v.Compare(v001) == -1 v.Compare(v) == 0 // Manipulate Version in place: v.Pre[0], err = semver.NewPRVersion("beta") if err != nil { fmt.Printf("Error parsing pre release version: %q", err) } fmt.Println("\nValidate versions:") v.Build[0] = "?" err = v.Validate() if err != nil { fmt.Printf("Validation failed: %s\n", err) } ``` -------------------------------- ### Install workerpool with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/gammazero/workerpool/README.md Installs the workerpool library into the Go workspace. ```bash $ go get github.com/gammazero/workerpool ``` -------------------------------- ### Install doublestar with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/bmatcuk/doublestar/v4/README.md Installs the doublestar v4 package using the go get command. ```bash go get github.com/bmatcuk/doublestar/v4 ``` -------------------------------- ### Install Participle v0 Source: https://github.com/activestate/cli/blob/master/vendor/github.com/alecthomas/participle/v2/README.md Installs the latest version from v0. Use this command to get the v0 module. ```shell $ go get github.com/alecthomas/participle@latest ``` -------------------------------- ### Install Cobra with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/spf13/cobra/README.md Installs the Cobra library and its dependencies, including the cobra generator executable. ```bash go get -u github.com/spf13/cobra ``` -------------------------------- ### Install go-localereader with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/mattn/go-localereader/README.md Installs the go-localereader package using the go get command. ```shell $ go get github.com/mattn/go-localereader ``` -------------------------------- ### Install s2c and s2d command-line tools Source: https://github.com/activestate/cli/blob/master/vendor/github.com/klauspost/compress/s2/README.md Installs the s2c and s2d binaries using Go's install command. Requires Go to be installed. ```shell go install github.com/klauspost/compress/s2/cmd/s2c@latest && go install github.com/klauspost/compress/s2/cmd/s2d@latest ``` -------------------------------- ### Install uniseg with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/rivo/uniseg/README.md Install the uniseg package using the Go module tool. ```bash go get github.com/rivo/uniseg ``` -------------------------------- ### Create Foo fixture Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Creates a Foo instance used as a fixture in examples. ```go f := &Foo{ ID: 1, FirstName: "Foo", LastName: "Bar", Age: 30, } ``` -------------------------------- ### Install stripansi with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/acarl005/stripansi/README.md Install the stripansi package using the go get command. ```sh $ go get -u github.com/acarl005/stripansi ``` -------------------------------- ### Install Participle v2 Source: https://github.com/activestate/cli/blob/master/vendor/github.com/alecthomas/participle/v2/README.md Installs the latest beta version of Participle v2. Use this command to get the v2 module. ```shell $ go get github.com/alecthomas/participle/v2@latest ``` -------------------------------- ### Install mapstructure with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/mitchellh/mapstructure/README.md Standard Go installation command for the mapstructure library. Run this in your terminal to fetch the package. ```shell $ go get github.com/mitchellh/mapstructure ``` -------------------------------- ### Install cpuid package with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/klauspost/cpuid/v2/README.md Installs the cpuid package using Go modules. Use 'go get -u github.com/klauspost/cpuid' without the v2 suffix for older versions. ```sh go get -u github.com/klauspost/cpuid/v2 ``` -------------------------------- ### Install netdb via go get Source: https://github.com/activestate/cli/blob/master/vendor/modernc.org/libc/honnef.co/go/netdb/README.md Installs the honnef.co/go/netdb package from the Go module proxy. ```shell go get honnef.co/go/netdb ``` -------------------------------- ### Install glzip command-line utility from source Source: https://github.com/activestate/cli/blob/master/vendor/github.com/sorairolake/lzip-go/README.md Installs the glzip command-line utility from source using the Go toolchain. ```sh go install github.com/sorairolake/lzip-go/cmd/glzip@latest ``` -------------------------------- ### Install deque package with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/gammazero/deque/README.md Install the deque library into your Go module using the standard go get command. ```shell $ go get github.com/gammazero/deque ``` -------------------------------- ### Install go-ogle-analytics Source: https://github.com/activestate/cli/blob/master/vendor/github.com/ActiveState/go-ogle-analytics/README.md Install the go-ogle-analytics package using the go get command. ```bash go get -v github.com/jpillora/go-ogle-analytics ``` -------------------------------- ### Run survey examples Source: https://github.com/activestate/cli/blob/master/vendor/gopkg.in/AlecAivazis/survey.v1/README.md Commands to fetch the survey package and run the example programs from the examples/ directory. ```bash go get gopkg.in/AlecAivazis/survey.v1 cd $GOPATH/src/gopkg.in/AlecAivazis/survey.v1 go run examples/simple.go go run examples/validation.go ``` -------------------------------- ### Install cpuid binary with go install Source: https://github.com/activestate/cli/blob/master/vendor/github.com/klauspost/cpuid/v2/README.md Installs the cpuid command-line tool. Alternatively, download binaries from the release page. ```sh go install github.com/klauspost/cpuid/v2/cmd/cpuid@latest ``` -------------------------------- ### Install mergo with go get Source: https://github.com/activestate/cli/blob/master/vendor/dario.cat/mergo/README.md Install the mergo package using go get. The import statement is shown for use in Go code. ```shell go get dario.cat/mergo ``` ```go // use in your .go code import ( "dario.cat/mergo" ) ``` -------------------------------- ### Install httpmock with $GOPATH Source: https://github.com/activestate/cli/blob/master/vendor/github.com/jarcoal/httpmock/README.md Install httpmock using $GOPATH. The v1 branch is the default branch on GitHub, so go get automatically downloads it into $GOPATH/src. Then import the package in your Go files. ```bash go get github.com/jarcoal/httpmock ``` ```go import "github.com/jarcoal/httpmock" ``` -------------------------------- ### Install uint128 package with go get Source: https://github.com/activestate/cli/blob/master/vendor/lukechampine.com/uint128/README.md Use this command to install the uint128 package. It is the standard way to fetch the package for use in a Go project. ```bash go get lukechampine.com/uint128 ``` -------------------------------- ### Install uuid package with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/google/uuid/README.md Use this command to install the github.com/google/uuid package. It is the standard Go module installation command. ```sh go get github.com/google/uuid ``` -------------------------------- ### mz c compression help and example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/minio/minlz/README.md Help text for the `mz c` compression command. It lists all options and shows an example invocation with its output. Note that output files are overwritten by default and wildcards are accepted. ```text Usage: mz c [options] Compresses all files supplied as input separately. Output files are written as 'filename.ext.mz. By default output files will be overwritten. Use - as the only file name to read from stdin and write to stdout. Wildcards are accepted: testdir/*.txt will compress all files in testdir ending with .txt Directories can be wildcards as well. testdir/*/*.txt will match testdir/subdir/b.txt File names beginning with 'http://' and 'https://' will be downloaded and compressed. Only http response code 200 is accepted. Options: -1 Compress faster, but with a minor compression loss -2 Default compression speed (default true) -3 Compress more, but a lot slower -bench int Run benchmark n times. No output will be written -block Use as a single block. Will load content into memory. Max 8MB. -bs string Max block size. Examples: 64K, 256K, 1M, 8M. Must be power of two and <= 8MB (default "8M") -c Write all output to stdout. Multiple input files will be concatenated -cpu int Maximum number of threads to use (default 32) -help Display help -index Add seek index (default true) -o string Write output to another file. Single input file only -pad string Pad size to a multiple of this value, Examples: 500, 64K, 256K, 1M, 4M, etc (default "1") -q Don't write any output to terminal, except errors -recomp Recompress MinLZ, Snappy or S2 input -rm Delete source file(s) after success -safe Do not overwrite output files -verify Verify files, but do not write output Example: λ mz c apache.log Compressing apache.log -> apache.log.mz 2622574440 -> 170960982 [6.52%]; 4155.2MB/s ``` -------------------------------- ### Compression example with SetConcurrency Source: https://github.com/activestate/cli/blob/master/vendor/github.com/klauspost/pgzip/README.md Example of using pgzip to compress data with a custom block size and concurrency. ```go var b bytes.Buffer w := gzip.NewWriter(&b) w.SetConcurrency(100000, 10) w.Write([]byte("hello, world\n")) w.Close() ``` -------------------------------- ### Sample output of cpuid example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/klauspost/cpuid/v2/README.md Sample output from running the example program. Shows the expected output format and values for a specific CPU. ```text >go run main.go Name: AMD Ryzen 9 3950X 16-Core Processor PhysicalCores: 16 ThreadsPerCore: 2 LogicalCores: 32 Family 23 Model: 113 Vendor ID: AMD Features: ADX,AESNI,AVX,AVX2,BMI1,BMI2,CLMUL,CMOV,CX16,F16C,FMA3,HTT,HYPERVISOR,LZCNT,MMX,MMXEXT,NX,POPCNT,RDRAND,RDSEED,RDTSCP,SHA,SSE,SSE2,SSE3,SSE4,SSE42,SSE4A,SSSE3 Cacheline bytes: 64 L1 Data Cache: 32768 bytes L1 Instruction Cache: 32768 bytes L2 Cache: 524288 bytes L3 Cache: 16777216 bytes Frequency 0 hz We have Streaming SIMD 2 Extensions ``` -------------------------------- ### Go usage example for EWMA package Source: https://github.com/activestate/cli/blob/master/vendor/github.com/VividCortex/ewma/README.md Shows how to create a SimpleEWMA (default) and a VariableEWMA with a decay factor, add samples, and retrieve values. The example includes sample data and expected output values. ```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 } ``` -------------------------------- ### Install go-m1cpu Source: https://github.com/activestate/cli/blob/master/vendor/github.com/shoenig/go-m1cpu/README.md Install the go-m1cpu module using the Go module tool. ```shell go get github.com/shoenig/go-m1cpu@latest ``` -------------------------------- ### Install color package Source: https://github.com/activestate/cli/blob/master/vendor/github.com/fatih/color/README.md Installs the color package using the Go module system. ```bash go get github.com/fatih/color ``` -------------------------------- ### Install Echo v4 with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/labstack/echo/v4/README.md Installs the Echo v4 package. The commented line shows the pattern for specifying a version. ```sh // go get github.com/labstack/echo/{version} go get github.com/labstack/echo/v4 ``` -------------------------------- ### Install flock with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/gofrs/flock/README.md Installs the flock package using the Go package manager. ```bash go get -u github.com/gofrs/flock ``` -------------------------------- ### Install Denco with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/go-openapi/runtime/middleware/denco/README.md Install the Denco package using the Go package manager. This command fetches the latest version of the library. ```bash go get -u github.com/go-openapi/runtime/middleware/denco ``` -------------------------------- ### Install State Tool on Linux/macOS Source: https://github.com/activestate/cli/blob/master/readme.md Install State Tool on Linux and macOS using the official installation script. Run in a terminal. ```bash sh <(curl -q https://platform.activestate.com/dl/cli/install.sh) ``` -------------------------------- ### Install uritemplate with go get Source: https://github.com/activestate/cli/blob/master/vendor/github.com/yosida95/uritemplate/v3/README.rst Install the uritemplate package using the Go module tool. This command fetches the latest version of the library. ```sh $ go get -u github.com/yosida95/uritemplate/v3 ``` -------------------------------- ### Basic interactive prompt example with survey.Ask Source: https://github.com/activestate/cli/blob/master/vendor/gopkg.in/AlecAivazis/survey.v1/README.md Shows how to define a set of questions using survey.Question, including Input and Select prompts, with validation, transformation, and default values. Answers are collected into a struct, with field tags to map question names. The example prints an error if the prompt fails. ```go package main import ( "fmt" "gopkg.in/AlecAivazis/survey.v1" ) // the questions to ask var qs = []*survey.Question{ { Name: "name", Prompt: &survey.Input{Message: "What is your name?"}, Validate: survey.Required, Transform: survey.Title, }, { Name: "color", Prompt: &survey.Select{ Message: "Choose a color:", Options: []string{"red", "blue", "green"}, Default: "red", }, }, { Name: "age", Prompt: &survey.Input{Message: "How old are you?"}, }, } func main() { // the answers will be written to this struct answers := struct { Name string // survey will match the question and field names FavoriteColor string `survey:"color"` // or you can tag fields to match a specific name Age int // if the types don't match exactly, survey will try to convert for you }{} // perform the questions err := survey.Ask(qs, &answers) if err != nil { fmt.Println(err.Error()) return } fmt.Printf("%s chose %s.", answers.Name, answers.FavoriteColor) } ``` -------------------------------- ### Install lz4 package Source: https://github.com/activestate/cli/blob/master/vendor/github.com/pierrec/lz4/v4/README.md Install the lz4 package using the Go toolchain. ```bash go get github.com/pierrec/lz4/v4 ``` -------------------------------- ### Example fish completion with descriptions Source: https://github.com/activestate/cli/blob/master/vendor/github.com/spf13/cobra/shell_completions.md Example fish completion output showing descriptions for commands. Descriptions are automatically provided based on usage information. ```bash $ helm s[tab] search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) ``` -------------------------------- ### Usage example for numcpus.GetOnline and numcpus.GetPossible Source: https://github.com/activestate/cli/blob/master/vendor/github.com/tklauser/numcpus/README.md Shows how to use the numcpus package to retrieve and print the number of online and possible CPUs. Handles errors by printing to stderr. The example is a complete Go program that can be run directly. ```Go package main import ( "fmt" "os" "github.com/tklauser/numcpus" ) func main() { online, err := numcpus.GetOnline() if err != nil { fmt.Fprintf(os.Stderr, "GetOnline: %v\n", err) } fmt.Printf("online CPUs: %v\n", online) possible, err := numcpus.GetPossible() if err != nil { fmt.Fprintf(os.Stderr, "GetPossible: %v\n", err) } fmt.Printf("possible CPUs: %v\n", possible) } ``` -------------------------------- ### Example zsh completion with descriptions Source: https://github.com/activestate/cli/blob/master/vendor/github.com/spf13/cobra/shell_completions.md Example zsh completion output showing descriptions for commands. Descriptions are automatically provided based on usage information. ```bash $ helm s[tab] search -- search for a keyword in charts show -- show information of a chart status -- displays the status of the named release ``` -------------------------------- ### Install levenshtein package Source: https://github.com/activestate/cli/blob/master/vendor/github.com/agnivade/levenshtein/README.md Install the levenshtein package using the Go module tool. ```shell go get github.com/agnivade/levenshtein ``` -------------------------------- ### Tail a file with follow mode Source: https://github.com/activestate/cli/blob/master/vendor/github.com/hpcloud/tail/README.md Starts tailing a file with follow mode enabled, iterating over lines as they are appended. The example prints each line to standard output. ```go t, err := tail.TailFile("/var/log/nginx.log", tail.Config{Follow: true}) for line := range t.Lines { fmt.Println(line.Text) } ``` -------------------------------- ### funk.Initial example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Gets all but the last element of an array. ```go funk.Initial([]int{0, 1, 2, 3, 4}) // []int{0, 1, 2, 3} ``` -------------------------------- ### funk.Difference usage examples Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Shows how to use funk.Difference to get the difference between two collections. ```go funk.Difference([]int{1, 2, 3, 4}, []int{2, 4, 6}) // []int{1, 3}, []int{6} funk.Difference([]string{"foo", "bar", "hello", "bar"}, []string{"foo", "bar"}) // []string{"hello"}, []string{} ``` -------------------------------- ### Install State Tool on Windows Source: https://github.com/activestate/cli/blob/master/readme.md Install State Tool on Windows using PowerShell with Administrator privileges. ```powershell IEX(New-Object Net.WebClient).downloadString('https://platform.activestate.com/dl/cli/install.ps1') ``` -------------------------------- ### funk.Tail example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Gets all but the first element of an array. ```go funk.Tail([]int{0, 1, 2, 3, 4}) // []int{1, 2, 3, 4} ``` -------------------------------- ### Install tail package Source: https://github.com/activestate/cli/blob/master/vendor/github.com/hpcloud/tail/README.md Installs the tail package and its dependencies using the Go toolchain. ```shell go get github.com/hpcloud/tail/... ``` -------------------------------- ### Install and run tomll CLI Source: https://github.com/activestate/cli/blob/master/vendor/github.com/pelletier/go-toml/README.md Installs the tomll command-line tool and shows its help output. tomll reads TOML files and lints them. ```shell go install github.com/pelletier/go-toml/cmd/tomll tomll --help ``` -------------------------------- ### Usage example: get clock ticks with sysconf.Sysconf Source: https://github.com/activestate/cli/blob/master/vendor/github.com/tklauser/go-sysconf/README.md Shows how to call sysconf.Sysconf to retrieve the SC_CLK_TCK value, equivalent to C.sysconf(C._SC_CLK_TCK). The example prints the result or handles an error if the call fails. ```Go package main import ( "fmt" "github.com/tklauser/go-sysconf" ) func main() { // get clock ticks, this will return the same as C.sysconf(C._SC_CLK_TCK) clktck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) if err == nil { fmt.Printf("SC_CLK_TCK: %v\n", clktck) } } ``` -------------------------------- ### Ginkgo + Resty Example: Setup and Test Files Source: https://github.com/activestate/cli/blob/master/vendor/github.com/jarcoal/httpmock/README.md Shows how to use httpmock with Ginkgo and Resty: activate the non-default client, reset mocks, and deactivate. The test registers a responder and uses Resty to fetch and unmarshal a response. ```go // article_suite_test.go import ( // ... "github.com/jarcoal/httpmock" "github.com/go-resty/resty" ) // ... var _ = BeforeSuite(func() { // block all HTTP requests httpmock.ActivateNonDefault(resty.DefaultClient.GetClient()) }) var _ = BeforeEach(func() { // remove any mocks httpmock.Reset() }) var _ = AfterSuite(func() { httpmock.DeactivateAndReset() }) // article_test.go import ( // ... "github.com/jarcoal/httpmock" "github.com/go-resty/resty" ) var _ = Describe("Articles", func() { It("returns a list of articles", func() { fixture := `{"status":{"message": "Your message", "code": 200}}` responder := httpmock.NewStringResponder(200, fixture) fakeUrl := "https://api.mybiz.com/articles.json" httpmock.RegisterResponder("GET", fakeUrl, responder) // fetch the article into struct articleObject := &models.Article{} _, err := resty.R().SetResult(articleObject).Get(fakeUrl) // do stuff with the article object ... }) }) ``` -------------------------------- ### Define flags and initConfig in cmd/root.go Source: https://github.com/activestate/cli/blob/master/vendor/github.com/spf13/cobra/README.md Full example of cmd/root.go with persistent flags for config, author, license, and viper, plus initConfig that reads a config file from home directory or flag. Uses Viper for configuration and binds flags. ```go package cmd import ( "fmt" "os" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( // Used for flags. cfgFile string userLicense string rootCmd = &cobra.Command{ Use: "cobra", Short: "A generator for Cobra based Applications", Long: `Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, } ) // Execute executes the root command. func Execute() error { return rootCmd.Execute() } func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) viper.SetDefault("author", "NAME HERE ") viper.SetDefault("license", "apache") rootCmd.AddCommand(addCmd) rootCmd.AddCommand(initCmd) } func er(msg interface{}) { fmt.Println("Error:", msg) os.Exit(1) } func initConfig() { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { er(err) } // Search config in home directory with name ".cobra" (without extension). viper.AddConfigPath(home) viper.SetConfigName(".cobra") } viper.AutomaticEnv() if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } } ``` -------------------------------- ### Clone a repository with git.PlainClone Source: https://github.com/activestate/cli/blob/master/vendor/github.com/go-git/go-git/v5/README.md Basic example that mimics the standard `git clone` command using git.PlainClone. The output shows the progress messages printed to os.Stdout. The CheckIfError and Info functions are from the examples package. ```go // Clone the given repository to the given directory Info("git clone https://github.com/go-git/go-git") _, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{ URL: "https://github.com/go-git/go-git", Progress: os.Stdout, }) CheckIfError(err) ``` ```text Counting objects: 4924, done. Compressing objects: 100% (1333/1333), done. Total 4924 (delta 530), reused 6 (delta 6), pack-reused 3533 ``` -------------------------------- ### Run command with pty.Start Source: https://github.com/activestate/cli/blob/master/vendor/github.com/ActiveState/pty/README.md Starts a command with a pseudo-terminal using pty.Start, writes input to it, and copies its output to stdout. For demonstration only. ```go package main import ( "io" "os" "os/exec" "github.com/creack/pty" ) func main() { c := exec.Command("grep", "--color=auto", "bar") f, err := pty.Start(c) if err != nil { panic(err) } go func() { f.Write([]byte("foo\n")) f.Write([]byte("bar\n")) f.Write([]byte("baz\n")) f.Write([]byte{4}) // EOT }() io.Copy(os.Stdout, f) } ``` -------------------------------- ### SplitPattern usage example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/bmatcuk/doublestar/v4/README.md Shows how to use SplitPattern with os.DirFS and Glob to handle patterns with meta characters. ```go base, pattern := SplitPattern("../../path/to/meta*/**") fsys := os.DirFS(base) matches, err := Glob(fsys, pattern) ``` -------------------------------- ### Get a directory listing with fsys.ReadDir Source: https://github.com/activestate/cli/blob/master/vendor/github.com/mholt/archives/README.md Reads the directory entries for a given path. The example reads the 'Playlists' directory and prints the extension of each entry. ```go entries, err := fsys.ReadDir("Playlists") if err != nil { return err } for _, e := range entries { fmt.Println(e.Extension()) } ``` -------------------------------- ### Initialize repository with OS filesystem Source: https://github.com/activestate/cli/blob/master/vendor/github.com/go-git/go-git/v5/EXTENDING.md Initializes a repository against the OS filesystem using osfs. ```go fs := osfs.New("/tmp/foo") r, err := git.Init(memory.NewStorage(), fs) ``` -------------------------------- ### Install gommon/color Source: https://github.com/activestate/cli/blob/master/vendor/github.com/labstack/gommon/color/README.md Install the gommon/color package using the Go module tool. ```sh go get github.com/labstack/gommon/color ``` -------------------------------- ### Go example using github.com/gammazero/deque Source: https://github.com/activestate/cli/blob/master/vendor/github.com/gammazero/deque/README.md Complete Go program demonstrating how to create a deque, add elements at both ends, query front/back, remove elements, and consume the deque with PopFront. Panics if reading from an empty deque. ```go package main import ( "fmt" "github.com/gammazero/deque" ) func main() { var q deque.Deque q.PushBack("foo") q.PushBack("bar") q.PushBack("baz") fmt.Println(q.Len()) // Prints: 3 fmt.Println(q.Front()) // Prints: foo fmt.Println(q.Back()) // Prints: baz q.PopFront() // remove "foo" q.PopBack() // remove "baz" q.PushFront("hello") q.PushBack("world") // Consume deque and print elements. for q.Len() != 0 { fmt.Println(q.PopFront()) } } ``` -------------------------------- ### Configure go-codegen plugin in smithy-build.json Source: https://github.com/activestate/cli/blob/master/vendor/github.com/aws/smithy-go/README.md Applies the go-codegen build plugin to the Smithy quickstart example created from `smithy init`. The configuration sets the service shape ID, module name, enables go.mod generation, and sets the Go directive to 1.24. ```json { "version": "1.0", "sources": [ "models" ], "maven": { "dependencies": [ "software.amazon.smithy.go:smithy-go-codegen:0.1.0" ] }, "plugins": { "go-codegen": { "service": "example.weather#Weather", "module": "github.com/example/weather", "generateGoMod": true, "goDirective": "1.24" } } } ``` -------------------------------- ### Install lzip-go package Source: https://github.com/activestate/cli/blob/master/vendor/github.com/sorairolake/lzip-go/README.md Installs the lzip-go package using the Go module system. ```sh go get -u github.com/sorairolake/lzip-go ``` -------------------------------- ### Install yaml.v3 for tests Source: https://github.com/activestate/cli/blob/master/vendor/dario.cat/mergo/README.md If tests fail due to a missing package, install gopkg.in/yaml.v3. ```shell go get gopkg.in/yaml.v3 ``` -------------------------------- ### Go example: Creating and pushing a toast notification Source: https://github.com/activestate/cli/blob/master/vendor/gopkg.in/toast.v1/readme.md Example Go program that creates a toast.Notification with an app ID, title, message, icon, and two actions, then pushes it. Requires the 'go.png' file to exist; remove the Icon line if it doesn't. On error, it logs a fatal message. ```go package main import ( "log" "gopkg.in/toast.v1" ) func main() { notification := toast.Notification{ AppID: "Example App", Title: "My notification", Message: "Some message about how important something is...", Icon: "go.png", // This file must exist (remove this line if it doesn't) Actions: []toast.Action{ {"protocol", "I'm a button", ""}, {"protocol", "Me too!", ""}, }, } err := notification.Push() if err != nil { log.Fatalln(err) } } ``` -------------------------------- ### funk.Keys: Get map keys or struct field names Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Returns an array of the own enumerable map keys or struct field names. For maps, iteration order is not guaranteed. The example shows usage with a map and a struct. ```go funk.Keys(map[string]int{"one": 1, "two": 2}) // []string{"one", "two"} (iteration order is not guaranteed) foo := &Foo{ ID: 1, FirstName: "Dark", LastName: "Vador", Age: 30, } funk.Keys(foo) // []string{"ID", "FirstName", "LastName", "Age"} (iteration order is not guaranteed) ``` -------------------------------- ### Run the program with tea.NewProgram Source: https://github.com/activestate/cli/blob/master/vendor/github.com/charmbracelet/bubbletea/README.md Starts the Bubble Tea program with the initial model and runs it, exiting with an error message if Run fails. ```go func main() { p := tea.NewProgram(initialModel()) if _, err := p.Run(); err != nil { fmt.Printf("Alas, there's been an error: %v", err) os.Exit(1) } } ``` -------------------------------- ### funk.Values: Get map values or struct field values Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Creates an array of the own enumerable map values or struct field values. The example shows usage with a map. Iteration order is not guaranteed. ```go funk.Values(map[string]int{"one": 1, "two": 2}) // []string{1, 2} (iteration order is not guaranteed) ``` -------------------------------- ### Install and run tomljson CLI Source: https://github.com/activestate/cli/blob/master/vendor/github.com/pelletier/go-toml/README.md Installs the tomljson command-line tool and shows its help output. tomljson reads a TOML file and outputs its JSON representation. ```shell go install github.com/pelletier/go-toml/cmd/tomljson tomljson --help ``` -------------------------------- ### Example dynamic flag completion output Source: https://github.com/activestate/cli/blob/master/vendor/github.com/spf13/cobra/shell_completions.md Example output showing the dynamic completion choices for the --output flag. The choices are displayed as a space-separated list. ```bash $ helm status --output [tab][tab] json table yaml ``` -------------------------------- ### Install and run jsontoml CLI Source: https://github.com/activestate/cli/blob/master/vendor/github.com/pelletier/go-toml/README.md Installs the jsontoml command-line tool and shows its help output. jsontoml reads a JSON file and outputs a TOML representation. ```shell go install github.com/pelletier/go-toml/cmd/jsontoml jsontoml --help ``` -------------------------------- ### Example output of dynamic completion Source: https://github.com/activestate/cli/blob/master/vendor/github.com/spf13/cobra/shell_completions.md Example output of dynamic completion for the helm status command, showing the available releases as completion choices. ```bash $ helm status [tab][tab] harbor notary rook thanos ``` -------------------------------- ### Go example: Using cpuid.Flags(), flag.Parse(), and cpuid.Detect() Source: https://github.com/activestate/cli/blob/master/vendor/github.com/klauspost/cpuid/v2/README.md Shows how to add flags that affect CPU detection. Must call cpuid.Flags() before flag.Parse() and cpuid.Detect() after parsing. Detection in init() functions will not include these flags. The example then checks for SSE and SSE2 features using cpuid.CPU.Supports(). ```Go package main import ( "flag" "fmt" "strings" "github.com/klauspost/cpuid/v2" ) func main() { cpuid.Flags() flag.Parse() cpuid.Detect() // Test if we have these specific features: if cpuid.CPU.Supports(cpuid.SSE, cpuid.SSE2) { fmt.Println("We have Streaming SIMD 2 Extensions") } } ``` -------------------------------- ### Output of YAML example Source: https://github.com/activestate/cli/blob/master/vendor/gopkg.in/yaml.v2/README.md Expected output from the Go example, showing the unmarshalled struct and map, and their YAML dumps. ```text --- t: {Easy! {2 [3 4]}} --- t dump: a: Easy! b: c: 2 d: [3, 4] --- m: map[a:Easy! b:map[c:2 d:[3 4]]] --- m dump: a: Easy! b: c: 2 d: - 3 - 4 ``` -------------------------------- ### Install golang.org/x/sys dependency Source: https://github.com/activestate/cli/blob/master/vendor/github.com/fsnotify/fsnotify/README.md Install the latest version of golang.org/x/sys, which fsnotify uses instead of the standard library's syscall package. ```console go get -u golang.org/x/sys/... ``` -------------------------------- ### funk.Shard examples Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Generates a sharded string with a fixed length and depth. Three examples show different parameters and their resulting slices. ```go funk.Shard("e89d66bdfdd4dd26b682cc77e23a86eb", 1, 2, false) // []string{"e", "8", "e89d66bdfdd4dd26b682cc77e23a86eb"} ``` ```go funk.Shard("e89d66bdfdd4dd26b682cc77e23a86eb", 2, 2, false) // []string{"e8", "9d", "e89d66bdfdd4dd26b682cc77e23a86eb"} ``` ```go funk.Shard("e89d66bdfdd4dd26b682cc77e23a86eb", 2, 3, true) // []string{"e8", "9d", "66", "bdfdd4dd26b682cc77e23a86eb"} ``` -------------------------------- ### funk.SliceOf example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Returns a slice based on an element. The example shows that calling funk.SliceOf(f) returns a []*Foo{f}. ```go funk.SliceOf(f) // will return a []*Foo{f} ``` -------------------------------- ### Basic LRU cache example in Go Source: https://github.com/activestate/cli/blob/master/vendor/github.com/hashicorp/golang-lru/v2/README.md Shows how to create a fixed-size thread-safe LRU cache using lru.New[int, any](128), add items, and check the length. The example adds 256 items and expects the cache to hold only 128, panicking if the length is incorrect. ```go package main import ( "fmt" "github.com/hashicorp/golang-lru/v2" ) func main() { l, _ := lru.New[int, any](128) for i := 0; i < 256; i++ { l.Add(i, nil) } if l.Len() != 128 { panic(fmt.Sprintf("bad len: %v", l.Len())) } } ``` -------------------------------- ### funk.Subset examples Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Returns true if a collection is a subset of another. Two examples show different input collections and their boolean results. ```go funk.Subset([]int{1, 2, 4}, []int{1, 2, 3, 4, 5}) // true ``` ```go funk.Subset([]string{"foo", "bar"},[]string{"foo", "bar", "hello", "bar", "hi"}) //true ``` -------------------------------- ### funk.RandomString example Source: https://github.com/activestate/cli/blob/master/vendor/github.com/thoas/go-funk/README.rst Generates a random string with a fixed length. The example shows that funk.RandomString(4) returns a string of 4 random characters. ```go funk.RandomString(4) // will be a string of 4 random characters ```