### Install Blackfriday v2 Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Use `go get` to install the package in module mode. Alternatively, import it in your project and run `go get`. ```go go get github.com/russross/blackfriday/v2 ``` -------------------------------- ### Install ansi Go Library Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/mgutz/ansi/README.md Use 'go get' to install or update the ansi library. ```sh go get -u github.com/mgutz/ansi ``` -------------------------------- ### Install blackfriday-tool Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Install the `blackfriday-tool` command-line utility using `go get`. This tool provides a standalone way to process markdown files. ```go go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Install lo Library Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Install the lo library using the go get command. This library is v1 and strictly follows SemVer. ```sh go get github.com/samber/lo@v1 ``` -------------------------------- ### Install go-colorable Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/mattn/go-colorable/README.md Install the go-colorable package using the go get command. This is a prerequisite for using the package in your Go projects. ```bash go get github.com/mattn/go-colorable ``` -------------------------------- ### Run Demo Examples Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/nsf/termbox-go/README.md Execute demo applications to see termbox-go in action. This example runs the keyboard demo. ```bash go run _demos/keyboard.go ``` -------------------------------- ### Install yaml.v3 Package Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/gopkg.in/yaml.v3/README.md Use 'go get' to install the yaml.v3 package for use in your Go projects. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/mattn/go-isatty/README.md Use this command to install the go-isatty package into your Go workspace. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Install pkcs8 Package Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/youmark/pkcs8/README.md Use 'go get' to install the pkcs8 package. Supports Go 1.10+. ```bash go get github.com/youmark/pkcs8 ``` -------------------------------- ### Install s2c and s2d Commandline Tools Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/klauspost/compress/s2/README.md Installs the s2 compression and decompression commandline tools using Go. Ensure Go is installed and configured. ```bash go install github.com/klauspost/compress/s2/cmd/s2c@latest && go install github.com/klauspost/compress/s2/cmd/s2d@latest ``` -------------------------------- ### Install Dependencies Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/youmark/pkcs8/README.md Retrieve the necessary crypto dependencies for the pkcs8 package using 'go get'. ```bash go get golang.org/x/crypto/pbkdf2 go get golang.org/x/crypto/scrypt ``` -------------------------------- ### Install uuid Package Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/google/uuid/README.md Use this command to install the uuid package using go get. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install Golang Set v2 Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/deckarep/golang-set/v2/README.md Use 'go get' to install this package. Requires Go 1.18 or higher. ```shell go get github.com/deckarep/golang-set/v2 ``` -------------------------------- ### Install Graphemes Package Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/clipperhouse/uax29/v2/graphemes/README.md Use 'go get' to install the graphemes package for your Go project. ```bash go get github.com/clipperhouse/uax29/v2/graphemes ``` -------------------------------- ### Full Example: Parsing Command-Line Arguments Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/jessevdk/go-flags/README.md A comprehensive example demonstrating various features of the go-flags library, including different data types, callbacks, required flags, choices, value names, pointers, slices, maps, and environment variables. It parses a predefined set of arguments and prints the results. ```go var opts struct { // Slice of bool will append 'true' each time the option // is encountered (can be set multiple times, like -vvv) Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"` // Example of automatic marshalling to desired type (uint) Offset uint `long:"offset" description:"Offset"` // Example of a callback, called each time the option is found. Call func(string) `short:"c" description:"Call phone number"` // Example of a required flag Name string `short:"n" long:"name" description:"A name" required:"true"` // Example of a flag restricted to a pre-defined set of strings Animal string `long:"animal" choice:"cat" choice:"dog"` // Example of a value name File string `short:"f" long:"file" description:"A file" value-name:"FILE"` // Example of a pointer Ptr *int `short:"p" description:"A pointer to an integer"` // Example of a slice of strings StringSlice []string `short:"s" description:"A slice of strings"` // Example of a slice of pointers PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"` // Example of a map IntMap map[string]int `long:"intmap" description:"A map from string to int"` // Example of env variable Thresholds []int `long:"thresholds" default:"1" default:"2" env:"THRESHOLD_VALUES" env-delim:","` } // Callback which will invoke callto: to call a number. // Note that this works just on OS X (and probably only with // Skype) but it shows the idea. opts.Call = func(num string) { cmd := exec.Command("open", "callto:"+num) cmd.Start() cmd.Process.Release() } // Make some fake arguments to parse. args := []string{ "-vv", "--offset=5", "-n", "Me", "--animal", "dog", // anything other than "cat" or "dog" will raise an error "-p", "3", "-s", "hello", "-s", "world", "--ptrslice", "hello", "--ptrslice", "world", "--intmap", "a:1", "--intmap", "b:5", "arg1", "arg2", "arg3", } // Parse flags from `args'. Note that here we use flags.ParseArgs for // the sake of making a working example. Normally, you would simply use // flags.Parse(&opts) which uses os.Args args, err := flags.ParseArgs(&opts, args) if err != nil { panic(err) } fmt.Printf("Verbosity: %v\n", opts.Verbose) fmt.Printf("Offset: %d\n", opts.Offset) fmt.Printf("Name: %s\n", opts.Name) fmt.Printf("Animal: %s\n", opts.Animal) fmt.Printf("Ptr: %d\n", *opts.Ptr) fmt.Printf("StringSlice: %v\n", opts.StringSlice) fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1]) fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"]) fmt.Printf("Remaining args: %s\n", strings.Join(args, " ")) // Output: Verbosity: [true true] // Offset: 5 // Name: Me // Ptr: 3 // StringSlice: [hello world] // PtrSlice: [hello world] // IntMap: [a:1 b:5] // Remaining args: arg1 arg2 arg3 ``` -------------------------------- ### Manage Dependencies with build.go Source: https://github.com/mongodb/mongo-tools/blob/master/CONTRIBUTING.md Use these commands to add or update project dependencies. Ensure Podman is installed for these operations. ```bash # Adds the latest version. go run build.go addDep -pkg=github.com/some/package ``` ```bash # Adds the specified version. go run build.go addDep -pkg=github.com/some/package@v1.2.3 ``` ```bash # Updates to the latest version. go run build.go updateDep -pkg=github.com/some/package ``` ```bash # Updates to the specified version. go run build.go updateDep -pkg=github.com/some/package@v1.2.3 ``` ```bash # Updates all dependencies to their latest versions. go run build.go updateAllDeps ``` -------------------------------- ### Install Dev Dependencies Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Installs necessary development dependencies for the project using the make tool. ```bash # Install some dev dependencies make tools ``` -------------------------------- ### Install Termbox-Go Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/nsf/termbox-go/README.md Use this command to install or update the termbox-go package. ```bash go get -u github.com/nsf/termbox-go ``` -------------------------------- ### Basic Oglematchers Examples Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/smarty/assertions/internal/oglematchers/README.md Demonstrates the usage of various oglematchers for different data types. These can be used to define conditions for testing. ```go // Numbers Equals(17.13) LessThan(19) // Strings Equals("taco") HasSubstr("burrito") MatchesRegex("t.*o") // Combining matchers AnyOf(LessThan(17), GreaterThan(19)) ``` -------------------------------- ### Install Golang JWT Library v5 Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/golang-jwt/jwt/v5/README.md Use this command to add the jwt-go library as a dependency in your Go program. Ensure you have Go installed. ```sh go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### Build s2c and s2d Binaries Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/klauspost/compress/s2/README.md Builds the s2 compression and decompression commandline tool binaries to the current directory. Requires Go to be installed. ```bash go build github.com/klauspost/compress/s2/cmd/s2c && go build github.com/klauspost/compress/s2/cmd/s2d ``` -------------------------------- ### Markdown Table Example Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Demonstrates the syntax for creating tables in Markdown. This is a common extension supported by Blackfriday. ```markdown Name | Age --------|------ Bob | 27 Alice | 23 ``` -------------------------------- ### Configure Repository in etc/repo-config.yml Source: https://github.com/mongodb/mongo-tools/blob/master/PLATFORMSUPPORT.md Add this configuration to `etc/repo-config.yml` to define the repository details for the new platform. This example is for the 'org' edition. ```yaml - name: ubuntu2004 type: deb code_name: "bionic" edition: org bucket: repo.mongodb.org component: multiverse architectures: - amd64 repos: - apt/ubuntu/dists/bionic/mongodb-org ``` -------------------------------- ### Create and Initialize Sets Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/deckarep/golang-set/v2/README.md Demonstrates how to create multiple string-based sets and add elements to them. Sets automatically handle deduplication. ```go package main import ( "fmt" mapset "github.com/deckarep/golang-set/v2" ) func main() { // Create a string-based set of required classes. required := mapset.NewSet[string]() required.Add("cooking") required.Add("english") required.Add("math") required.Add("biology") // Create a string-based set of science classes. sciences := mapset.NewSet[string]() sciences.Add("biology") sciences.Add("chemistry") // Create a string-based set of electives. electives := mapset.NewSet[string]() electives.Add("welding") electives.Add("music") electives.Add("automotive") // Create a string-based set of bonus programming classes. bonus := mapset.NewSet[string]() bonus.Add("beginner go") bonus.Add("python for dummies") } ``` -------------------------------- ### Basic CLI Application Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt The simplest possible CLI application using the framework. It initializes an empty App and runs it with command-line arguments. ```go func main() { (&cli.App{}).Run(os.Args) } ``` -------------------------------- ### DefaultAzureCredential Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md Provides a simplified authentication experience for getting started developing Azure applications. It attempts to authenticate using a variety of methods in a default order. ```APIDOC ## DefaultAzureCredential ### Description This credential type offers a streamlined way to authenticate your Azure applications. It automatically tries multiple authentication methods in a predefined order, making it easy to get started. ### Usage Use `DefaultAzureCredential` when you need a simple and convenient way to authenticate without explicitly configuring each authentication method. ### Reference [DefaultAzureCredential overview](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DefaultAzureCredential) ``` -------------------------------- ### Create S2 Dictionary from Sample File Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/klauspost/compress/s2/README.md Demonstrates how to create an S2 dictionary using a sample file. This is useful when input data is uniform. The dictionary can be saved and reloaded. ```Go // Read a sample sample, err := os.ReadFile("sample.json") // Create a dictionary. dict := s2.MakeDict(sample, nil) // b := dict.Bytes() will provide a dictionary that can be saved // and reloaded with s2.NewDict(b). // To encode: encoded := dict.Encode(nil, file) // To decode: decoded, err := dict.Decode(nil, file) ``` -------------------------------- ### Fenced Code Block Sanitization Policy Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Provides an example of how to configure the bluemonday HTML sanitizer to preserve classes on fenced code blocks, specifically those starting with 'language-'. ```go p := bluemonday.UGCPolicy() p.AllowAttrs("class").Matching(regexp.MustCompile("^language-[a-zA-Z0-9]+$")).OnElements("code") html := p.SanitizeBytes(unsafe) ``` -------------------------------- ### Install Azure Identity Module Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md Installs the Azure Identity module using Go modules. Ensure you have a supported version of Go installed. ```sh go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity ``` -------------------------------- ### Show Application Help Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt An action that displays the help information for the application. This is a common function to trigger when a user requests help. ```go func ShowAppHelp(cCtx *Context) error ShowAppHelp is an action that displays the help. ``` -------------------------------- ### Show All Completions Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Prints a list of all available commands within the current context. This is used for general command completion. ```go func ShowCompletions(cCtx *Context) ShowCompletions prints the lists of commands within a given context ``` -------------------------------- ### Customizable App Help Template Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Demonstrates how to customize the default help text template for the CLI application. This allows for a more tailored user experience when users request help. ```go var AppHelpTemplate = `NAME: {{template "helpNameTemplate" .}} USAGE: {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Args}} [arguments...]{{end}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} VERSION: {{.Version}}{{end}}{{end}}{{if .Description}} DESCRIPTION: {{template "descriptionTemplate" .}}{{end}}{{if len .Authors}} AUTHOR{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}} COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}} GLOBAL OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} GLOBAL OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}} COPYRIGHT: {{template "copyrightTemplate" .}}{{end}} ` ``` -------------------------------- ### Build All MongoDB Tools Source: https://github.com/mongodb/mongo-tools/blob/master/AGENTS.md Use this command to build all the tools in the project. Binaries are placed in the ./bin/ directory. ```bash go run build.go build ``` -------------------------------- ### Slice Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Returns a copy of a slice from a start index up to, but not including, an end index. ```APIDOC ## Slice ### Description Returns a copy of a slice from `start` up to, but not including, `end`. Like `slice[start:end]`, but does not panic on overflow. ### Parameters - `slice` ([]T) - The input slice. - `start` (int) - The starting index (inclusive). - `end` (int) - The ending index (exclusive). ### Returns - []T - A new slice representing the specified range. ### Example ```go in := []int{0, 1, 2, 3, 4} slice := lo.Slice(in, 0, 5) // []int{0, 1, 2, 3, 4} slice := lo.Slice(in, 2, 3) // []int{2} slice := lo.Slice(in, 2, 6) // []int{2, 3, 4} slice := lo.Slice(in, 4, 3) // []int{} ``` ``` -------------------------------- ### Start mlaunch Managed Cluster Source: https://github.com/mongodb/mongo-tools/blob/master/AGENTS.md Restarts a previously initialized cluster managed by mlaunch. ```bash mlaunch start ``` -------------------------------- ### Configure Go Client Code Generation Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/aws/smithy-go/README.md Example `smithy-build.json` configuration to enable the `go-codegen` plugin. Ensure the `smithy-go-codegen` dependency is available in your local Maven repository. ```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" } } } ``` -------------------------------- ### NewApp Function Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Creates a new cli Application with default settings for Name, Usage, Version, and Action. ```go func NewApp() *App ``` -------------------------------- ### ChannelToSlice Example Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Converts a channel into a slice. This function blocks until the channel is closed and all items are read. ```go list := []int{1, 2, 3, 4, 5} ch := lo.SliceToChannel(2, list) items := ChannelToSlice(ch) // []int{1, 2, 3, 4, 5} ``` -------------------------------- ### Get Set Cardinality Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/deckarep/golang-set/v2/README.md Returns the number of elements in a set. This is useful for understanding the size of the collection. ```go fmt.Println(bonus.Cardinality()) ``` -------------------------------- ### xxhash Benchmarking Commands Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md Commands to run benchmarks comparing pure Go and assembly implementations of Sum64. Use benchstat to analyze results. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') ``` ```bash benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Substring Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Extracts a portion of a string based on start index and length. Supports negative indexing. ```APIDOC ## Substring ### Description Returns a substring from the given string. The start index and length define the portion to extract. Negative start indices count from the end of the string. `math.MaxUint` can be used for length to extract until the end. ### Signature `lo.Substring(str string, start int, length int) string` ### Examples ```go sub1 := lo.Substring("hello", 2, 3) // sub1 is "llo" sub2 := lo.Substring("hello", -4, 3) // sub2 is "ell" sub3 := lo.Substring("hello", -2, math.MaxUint) // sub3 is "lo" ``` ``` -------------------------------- ### Use Uniq Helper Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Example of using the Uniq helper to remove duplicate elements from a string slice. ```go names := lo.Uniq([]string{"Samuel", "John", "Samuel"}) // []string{"Samuel", "John"} ``` -------------------------------- ### Footnote Example Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Demonstrates how to create footnotes in Markdown. A marker in the text links to a definition at the end of the document. ```markdown This is a footnote.[^1] [^1]: the footnote text. ``` -------------------------------- ### Client Certificate Authentication with autorest/adal Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md This snippet demonstrates client certificate authentication using the `autorest/adal` package. It requires reading a PFX file and decoding it. ```go import ( "os" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/adal" ) certData, err := os.ReadFile("./example.pfx") handle(err) certificate, rsaPrivateKey, err := decodePkcs12(certData, "") handle(err) oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) handle(err) spt, err := adal.NewServicePrincipalTokenFromCertificate( *oauthConfig, clientID, certificate, rsaPrivateKey, "https://management.azure.com/", ) client := subscriptions.NewClient() client.Authorizer = autorest.NewBearerAuthorizer(spt) ``` -------------------------------- ### Show Subcommand Help Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Prints the help information for a subcommand. This is used when a user requests help for a specific subcommand. ```go func ShowSubcommandHelp(cCtx *Context) error ShowSubcommandHelp prints help for the given subcommand ``` -------------------------------- ### Clone MongoDB Tools Repository Source: https://github.com/mongodb/mongo-tools/blob/master/README.md Clone the official MongoDB Tools repository to start building and developing. ```bash git clone https://github.com/mongodb/mongo-tools cd mongo-tools ``` -------------------------------- ### Show App Help and Exit Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Prints the list of subcommands for the application and then exits with a specified exit code. Useful for commands that only display help information. ```go func ShowAppHelpAndExit(c *Context, exitCode int) ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code. ``` -------------------------------- ### SliceToChannel Example Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Converts a slice into a read-only channel. The channel is closed after all elements are sent. The capacity of the channel can be specified. ```go list := []int{1, 2, 3, 4, 5} for v := range lo.SliceToChannel(2, list) { println(v) } // prints 1, then 2, then 3, then 4, then 5 ``` -------------------------------- ### Basic Word Wrapping Example Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/mitchellh/go-wordwrap/README.md Demonstrates basic usage of the WrapString function to wrap a given string to a specified width. This is useful for formatting text for command-line interfaces. ```go wrapped := wordwrap.WrapString("foo bar baz", 3) fmt.Println(wrapped) ``` -------------------------------- ### Show Command Help Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Prints the help information for a specific command. This function is used when a user requests help for a particular subcommand. ```go func ShowCommandHelp(ctx *Context, command string) error ShowCommandHelp prints help for the given command ``` -------------------------------- ### Get Last Element or Zero Value Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Returns the last element of a collection or its zero value if the collection is empty. ```go last := lo.LastOrEmpty([]int{1, 2, 3}) // 3 last := lo.LastOrEmpty([]int{}) // 0 ``` -------------------------------- ### Get First Element or Zero Value Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Returns the first element of a collection or its zero value if the collection is empty. ```go first := lo.FirstOrEmpty([]int{1, 2, 3}) // 1 first := lo.FirstOrEmpty([]int{}) // 0 ``` -------------------------------- ### Initialize mlaunch for Testing Source: https://github.com/mongodb/mongo-tools/blob/master/CONTRIBUTING.md Initialize a MongoDB replica set for integration testing on localhost:33333 using the mlaunch tool. ```bash $> mlaunch init --replicaset --port 33333 ``` -------------------------------- ### Get Latest Time Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Searches for the maximum time.Time in a collection. Returns the zero value of time.Time if the collection is empty. ```go latest := lo.Latest(time.Now(), time.Time{}) // 2023-04-01 01:02:03 +0000 UTC ``` -------------------------------- ### Get Rune Length of String Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Returns the number of Unicode code points (runes) in a string, aliased from `utf8.RuneCountInString`. ```go sub := lo.RuneLength("hellĂ´") // 5 ``` ```go sub := len("hellĂ´") // 6 ``` -------------------------------- ### CLI Application with Name, Usage, and Action Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt A more functional CLI application that defines a name, usage string, and a default action to be executed when the application runs. ```go func main() { app := &cli.App{ Name: "greet", Usage: "say a greeting", Action: func(c *cli.Context) error { fmt.Println("Greetings") return nil }, } app.Run(os.Args) } ``` -------------------------------- ### ClientCertificateCredential Initialization Change Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md Demonstrates the change in NewClientCertificateCredential, which now requires certificate data and a private key instead of a file path. Includes the use of ParseCertificates for simplification. ```go // before cred, err := NewClientCertificateCredential("tenant", "client-id", "/cert.pem", nil) // after certData, err := os.ReadFile("/cert.pem") certs, key, err := ParseCertificates(certData, password) cred, err := NewClientCertificateCredential(tenantID, clientID, certs, key, nil) ``` -------------------------------- ### Import Golang JWT Library v5 Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/golang-jwt/jwt/v5/README.md Import the jwt package into your Go code to start using its functionalities. ```go import "github.com/golang-jwt/jwt/v5" ``` -------------------------------- ### Show Command Help and Exit Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Exits the application with a specified code after displaying help for a given command. This is a convenient way to show help and terminate. ```go func ShowCommandHelpAndExit(c *Context, command string, code int) ShowCommandHelpAndExit - exits with code after showing help ``` -------------------------------- ### Check if Slice is Sorted in Go Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/samber/lo/README.md Verifies if a slice of integers is sorted in ascending order. No specific setup is required. ```go slice := lo.IsSorted([]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) // true ``` -------------------------------- ### Set Go Root Directory Source: https://github.com/mongodb/mongo-tools/blob/master/README.md Set the GOROOT environment variable to your Go installation directory. This is required for the build/test scripts. ```bash export GOROOT=/usr/local/go ``` -------------------------------- ### NewApp Source: https://github.com/mongodb/mongo-tools/blob/master/vendor/github.com/urfave/cli/v2/godoc-current.txt Creates a new cli Application with default settings for Name, Usage, Version, and Action. ```APIDOC ## NewApp ### Description `NewApp` is a constructor function that initializes a new `App` instance with sensible default values for essential fields like `Name`, `Usage`, `Version`, and `Action`. ### Signature ```go func NewApp() *App ``` ### Returns - `*App`: A pointer to a newly created `App` instance. ```