### Install Bazelisk with Go Source: https://github.com/bazelbuild/bazelisk/blob/master/README.md Installs the Go version of Bazelisk using the 'go install' command. Ensure your Go environment is set up correctly. ```shell go install github.com/bazelbuild/bazelisk@latest ``` -------------------------------- ### Get Bazel Installation Source: https://context7.com/bazelbuild/bazelisk/llms.txt Use `GetBazelInstallation` to resolve and download the specified Bazel binary. The binary is cached using a content-addressed store (SHA-256) under the Bazelisk home directory. ```Go package main import ( "fmt" "log" "github.com/bazelbuild/bazelisk/core" "github.com/bazelbuild/bazelisk/repositories" "github.com/bazelbuild/bazelisk/config" ) func main() { cfg := config.Static(map[string]string{ "USE_BAZEL_VERSION": "latest", // Optionally verify the download: // "BAZELISK_VERIFY_SHA256": "abc123...", }) gcs := &repositories.GCSRepo{} gh := repositories.CreateGitHubRepo("") repos := core.CreateRepositories(gcs, gh, gcs, gcs, true) install, err := core.GetBazelInstallation(repos, cfg) if err != nil { log.Fatalf("could not get Bazel: %v", err) } fmt.Printf("Resolved version : %s\n", install.Version) fmt.Printf("Binary path : %s\n", install.Path) // Resolved version : 8.2.1 // Binary path : /home/user/.cache/bazelisk/downloads/sha256/a1b2c3.../bin/bazel } ``` -------------------------------- ### Assemble Bazel Repositories Bundle Source: https://context7.com/bazelbuild/bazelisk/llms.txt Constructs a `*core.Repositories` struct by combining different repository implementations (GCS, GitHub) for LTS, forks, commits, and rolling releases. Demonstrates full and LTS-only setups and version resolution. ```go package main import ( "fmt" "log" "github.com/bazelbuild/bazelisk/config" "github.com/bazelbuild/bazelisk/core" "github.com/bazelbuild/bazelisk/repositories" ) func main() { gcs := &repositories.GCSRepo{} gitHub := repositories.CreateGitHubRepo("ghp_mytoken") // pass "" to skip auth // Full setup: LTS=gcs, Fork=gitHub, Commits=gcs, Rolling=gcs repos := core.CreateRepositories(gcs, gitHub, gcs, gcs, true) // LTS-only setup (no fork/commit/rolling support) ltsOnly := core.CreateRepositories(gcs, nil, nil, nil, false) cfg := config.Static(map[string]string{"USE_BAZEL_VERSION": "latest"}) resolvedVersion, _, err := repos.ResolveVersion("/tmp/bazelisk_home", "bazelbuild", "latest", cfg) if err != nil { log.Fatal(err) } fmt.Println(resolvedVersion) // e.g. "8.2.1" _, _, err = ltsOnly.ResolveVersion("/tmp/bazelisk_home", "myfork", "1.0.0", cfg) fmt.Println(err) // forked versions of Bazel are not supported } ``` -------------------------------- ### Print Bazelisk Version Source: https://github.com/bazelbuild/bazelisk/blob/master/README.md Use the `bazeliskVersion` command to display the currently installed version of Bazelisk. ```shell bazelisk bazeliskVersion ``` -------------------------------- ### Configure Bazelisk with .bazelrc Source: https://github.com/bazelbuild/bazelisk/blob/master/README.md Example content for a .bazeliskrc file to set environment variables persistently. Variables are evaluated with precedence: environment variables > workspace .bazelrc > user home .bazelrc. ```shell USE_BAZEL_VERSION=0.19.0 BAZELISK_GITHUB_TOKEN=abc ``` -------------------------------- ### Add Bazelisk to PATH Source: https://github.com/bazelbuild/bazelisk/blob/master/README.md Adds the directory containing the installed Bazelisk binary to your system's PATH environment variable. This allows you to run Bazelisk from any directory. ```shell export PATH=$PATH:$(go env GOPATH)/bin ``` -------------------------------- ### Fetch Remote File with Retries Source: https://context7.com/bazelbuild/bazelisk/llms.txt Retrieves a remote file using GET requests with automatic retries, exponential back-off, and support for rate limiting headers. Returns the body and response headers. An optional authentication token can be provided. ```go package main import ( "fmt" "log" "github.com/bazelbuild/bazelisk/httputil" ) func main() { // Unauthenticated request body, headers, err := httputil.ReadRemoteFile( "https://storage.googleapis.com/bazel-builds/last_green_commit/github.com/bazelbuild/bazel.git/publish-bazel-binaries", "", ) if err != nil { log.Fatal(err) } fmt.Printf("Commit : %s\n", string(body)) fmt.Printf("Content-Type: %s\n", headers.Get("Content-Type")) // Authenticated request (GitHub API) httputil.UserAgent = "my-tool/1.0" body2, _, err := httputil.ReadRemoteFile( "https://api.github.com/repos/bazelbuild/bazel/releases?per_page=1", "token ghp_myToken", ) if err != nil { log.Fatal(err) } fmt.Printf("First 100 bytes: %.100s\n", body2) } ``` -------------------------------- ### Build Download URL with Format String Source: https://context7.com/bazelbuild/bazelisk/llms.txt Constructs a download URL by expanding a format string with version, OS, architecture, and extension placeholders. Requires a configuration object and the desired version. ```go package main import ( "fmt" "log" "github.com/bazelbuild/bazelisk/config" "github.com/bazelbuild/bazelisk/core" ) func main() { cfg := config.Static(map[string]string{ "BAZELISK_VERIFY_SHA256": "abc123def456", }) formatURL := "https://my-mirror.example.com/bazel/%v/bazel-%v-%o-%m%e" url, err := core.BuildURLFromFormat(cfg, formatURL, "7.4.1") if err != nil { log.Fatal(err) } fmt.Println(url) // Linux amd64: https://my-mirror.example.com/bazel/7.4.1/bazel-7.4.1-linux-x86_64 // macOS arm64: https://my-mirror.example.com/bazel/7.4.1/bazel-7.4.1-darwin-arm64 } ``` -------------------------------- ### Execute Bazel with Dynamic Arguments and Custom Config using ExecBazeliskWithArgsFuncAndConfig Source: https://context7.com/bazelbuild/bazelisk/llms.txt The `ExecBazeliskWithArgsFuncAndConfig` function is the production entry point for the Bazelisk binary. It accepts an `ArgsFunc` to dynamically generate arguments based on the resolved Bazel version. On Linux/macOS, this function replaces the current process; on Windows, it spawns a subprocess and returns its exit code. ```go package main import ( "log" "os" "github.com/bazelbuild/bazelisk/config" "github.com/bazelbuild/bazelisk/core" "github.com/bazelbuild/bazelisk/repositories" ) func main() { gcs := &repositories.GCSRepo{} cfg := config.Static(map[string]string{ "USE_BAZEL_VERSION": "7.x", // pin to latest Bazel 7 LTS release "BAZELISK_GITHUB_TOKEN": os.Getenv("GH_TOKEN"), "BAZELISK_SHOW_PROGRESS": "1", }) gitHub := repositories.CreateGitHubRepo(cfg.Get("BAZELISK_GITHUB_TOKEN")) repos := core.CreateRepositories(gcs, gitHub, gcs, gcs, true) argsFunc := func(resolvedVersion string) []string { log.Printf("Running Bazel %s", resolvedVersion) return os.Args[1:] // forward all CLI args unchanged } exitCode, err := core.ExecBazeliskWithArgsFuncAndConfig(argsFunc, repos, cfg) if err != nil { log.Fatal(err) } os.Exit(exitCode) } ``` -------------------------------- ### httputil.ReadRemoteFile Source: https://context7.com/bazelbuild/bazelisk/llms.txt Fetches a remote file using an HTTP GET request with built-in retry logic, exponential back-off, and support for rate limiting headers. ```APIDOC ## httputil.ReadRemoteFile — Fetch a remote file with retry logic Makes a GET request with automatic retry (up to `MaxRetries=4` attempts), exponential back-off, and support for `Retry-After` / `X-RateLimit-Reset` headers. Returns the body bytes and response headers. ### Method `httputil.ReadRemoteFile(url string, auth string) ([]byte, http.Header, error)` ### Parameters - `url` (string) - The URL of the remote file to fetch. - `auth` (string) - Authentication string (e.g., "token ghp_myToken"). ### Request Example ```go package main import ( "fmt" "log" "github.com/bazel/bazelisk/httputil" ) func main() { // Unauthenticated request body, headers, err := httputil.ReadRemoteFile( "https://storage.googleapis.com/bazel-builds/last_green_commit/github.com/bazelbuild/bazel.git/publish-bazel-binaries", "", ) if err != nil { log.Fatal(err) } fmt.Printf("Commit : %s\n", string(body)) fmt.Printf("Content-Type: %s\n", headers.Get("Content-Type")) // Authenticated request (GitHub API) httputil.UserAgent = "my-tool/1.0" body2, _, err := httputil.ReadRemoteFile( "https://api.github.com/repos/bazelbuild/bazel/releases?per_page=1", "token ghp_myToken", ) if err != nil { log.Fatal(err) } fmt.Printf("First 100 bytes: %.100s\n", body2) } ``` ### Response Example ``` Commit : a3f9b2c1d4e5... Content-Type: text/plain; charset=utf-8 First 100 bytes: [response body truncated] ``` ``` -------------------------------- ### Bazelisk Configuration Factories Source: https://context7.com/bazelbuild/bazelisk/llms.txt Demonstrates the usage of different configuration factories: Static for hardcoded values, FromEnv for environment variables, FromFile for .bazeliskrc, Layered for combining configurations, and Null for empty configurations. Useful for setting Bazel versions and other Bazelisk behaviors. ```go package main import ( "fmt" "github.com/bazelbuild/bazelisk/config" ) func main() { // Hardcoded values (useful in tests) static := config.Static(map[string]string{ "USE_BAZEL_VERSION": "7.x", "BAZELISK_NOJDK": "1", }) fmt.Println(static.Get("USE_BAZEL_VERSION")) // 7.x // Environment only fromEnv := config.FromEnv() fmt.Println(fromEnv.Get("HOME")) // /home/alice // Read from file (parses KEY=VALUE, ignores comments) fromFile, err := config.FromFile("/workspace/.bazeliskrc") if err == nil { fmt.Println(fromFile.Get("USE_BAZEL_VERSION")) } // Layered: first non-empty value wins layered := config.Layered(config.FromEnv(), static) fmt.Println(layered.Get("USE_BAZEL_VERSION")) // env wins if set, else "7.x" // Empty config (for tests that need no configuration) null := config.Null() fmt.Println(null.Get("ANYTHING")) // "" } ``` -------------------------------- ### Run Bazel with Fixed Arguments using RunBazelisk Source: https://context7.com/bazelbuild/bazelisk/llms.txt Use `RunBazelisk` to resolve, download (if needed), and execute the appropriate Bazel binary with a predefined list of arguments. It returns the Bazel process exit code. On non-Windows systems, `ExecBazelisk` can be used to replace the current process. ```go package main import ( "log" "os" "github.com/bazelbuild/bazelisk/core" "github.com/bazelbuild/bazelisk/repositories" ) func main() { gcs := &repositories.GCSRepo{} config := core.MakeDefaultConfig() gitHub := repositories.CreateGitHubRepo(config.Get("BAZELISK_GITHUB_TOKEN")) repos := core.CreateRepositories(gcs, gitHub, gcs, gcs, true) // Run: bazel build //... exitCode, err := core.RunBazelisk([]string{"build", "//..."}, repos) if err != nil { log.Fatalf("bazelisk error: %v", err) } os.Exit(exitCode) // Output (if build succeeds): exit code 0 // Output (on build failure): exit code 1 } ``` -------------------------------- ### ExecBazeliskWithArgsFuncAndConfig Source: https://context7.com/bazelbuild/bazelisk/llms.txt The production entry point used by the Bazelisk binary itself. Accepts an `ArgsFunc` that receives the resolved Bazel version string and returns the argument list to pass. On Linux/macOS this replaces the process; on Windows it spawns a subprocess and returns its exit code. ```APIDOC ## ExecBazeliskWithArgsFuncAndConfig ### Description The production entry point used by the Bazelisk binary itself. Accepts an `ArgsFunc` that receives the resolved Bazel version string and returns the argument list to pass — useful when arguments need to depend on the exact version selected. On Linux/macOS this replaces the process (no return); on Windows it spawns a subprocess and returns its exit code. ### Method Signature ```go func ExecBazeliskWithArgsFuncAndConfig(argsFunc core.ArgsFunc, repos *core.Repositories, cfg config.Config) (int, error) ``` ### Parameters #### Path Parameters - **argsFunc** (core.ArgsFunc) - Required - A function that takes the resolved Bazel version string and returns the arguments to pass to Bazel. - **repos** (*core.Repositories) - Required - A struct containing the repositories to use for downloading Bazel. - **cfg** (config.Config) - Required - A configuration object for Bazelisk. ### Request Example ```go package main import ( "log" "os" "github.com/bazelbuild/bazelisk/config" "github.com/bazelbuild/bazelisk/core" "github.com/bazelbuild/bazelisk/repositories" ) func main() { gcs := &repositories.GCSRepo{} cfg := config.Static(map[string]string{ "USE_BAZEL_VERSION": "7.x", // pin to latest Bazel 7 LTS release "BAZELISK_GITHUB_TOKEN": os.Getenv("GH_TOKEN"), "BAZELISK_SHOW_PROGRESS": "1", }) gitHub := repositories.CreateGitHubRepo(cfg.Get("BAZELISK_GITHUB_TOKEN")) repos := core.CreateRepositories(gcs, gitHub, gcs, gcs, true) argsFunc := func(resolvedVersion string) []string { log.Printf("Running Bazel %s", resolvedVersion) return os.Args[1:] // forward all CLI args unchanged } exitCode, err := core.ExecBazeliskWithArgsFuncAndConfig(argsFunc, repos, cfg) if err != nil { log.Fatal(err) } os.Exit(exitCode) } ``` ### Response #### Success Response (0) - **exitCode** (int) - 0 if the Bazel command succeeded. #### Error Response - **exitCode** (int) - Non-zero if the Bazel command failed. - **err** (error) - An error object if Bazelisk encountered an issue. ### Response Example ``` // On Linux/macOS, this function does not return if successful. // On Windows, it returns the exit code of the spawned Bazel process. ``` ``` -------------------------------- ### Build Default Configuration Source: https://context7.com/bazelbuild/bazelisk/llms.txt Use `MakeDefaultConfig` to construct the layered configuration stack. This stack prioritizes environment variables, followed by the workspace `.bazeliskrc`, and finally the user-home `.bazeliskrc`. ```Go package main import ( "fmt" "github.com/bazelbuild/bazelisk/core" ) func main() { cfg := core.MakeDefaultConfig() // Reads USE_BAZEL_VERSION from env, then workspace .bazeliskrc, then home .bazeliskrc fmt.Println(cfg.Get("USE_BAZEL_VERSION")) // e.g. "7.4.1" if set fmt.Println(cfg.Get("BAZELISK_GITHUB_TOKEN")) // token or "" fmt.Println(cfg.Get("BAZELISK_SHOW_PROGRESS")) // "1" or "" } ``` -------------------------------- ### core.BuildURLFromFormat Source: https://context7.com/bazelbuild/bazelisk/llms.txt Constructs a download URL by expanding a format string with version, OS, architecture, and extension placeholders. ```APIDOC ## core.BuildURLFromFormat — Construct a download URL from a format string Expands a `BAZELISK_FORMAT_URL` template string by substituting platform, architecture, version, and extension placeholders. The supported tokens are `%v` (version), `%o` (OS), `%m` (architecture), `%e` (extension suffix), `%h` (expected SHA-256), and `%%` (literal `%`). ### Method `core.BuildURLFromFormat(cfg *config.Config, formatURL string, version string) (string, error)` ### Parameters - `cfg` (*config.Config) - Configuration object. - `formatURL` (string) - The format string template. - `version` (string) - The Bazel version to substitute. ### Request Example ```go package main import ( "fmt" "log" "github.com/bazel/bazelisk/config" "github.com/bazel/bazelisk/core" ) func main() { cfg := config.Static(map[string]string{ "BAZELISK_VERIFY_SHA256": "abc123def456", }) formatURL := "https://my-mirror.example.com/bazel/%v/bazel-%v-%o-%m%e" url, err := core.BuildURLFromFormat(cfg, formatURL, "7.4.1") if err != nil { log.Fatal(err) } fmt.Println(url) } ``` ### Response Example ``` https://my-mirror.example.com/bazel/7.4.1/bazel-7.4.1-linux-x86_64 ``` ``` -------------------------------- ### Run Bazel and Capture Output Source: https://context7.com/bazelbuild/bazelisk/llms.txt Use `RunBazeliskWithArgsFuncAndConfigAndOutAndErr` to execute Bazel as a subprocess and capture its standard output and error streams. This is useful for programmatic integration where build output needs to be collected. ```Go package main import ( "bytes" "fmt" "log" "os" "github.com/bazelbuild/bazelisk/core" "github.com/bazelbuild/bazelisk/repositories" ) func runAndCapture(args []string) (string, int, error) { gcs := &repositories.GCSRepo{} cfg := core.MakeDefaultConfig() gh := repositories.CreateGitHubRepo(cfg.Get("BAZELISK_GITHUB_TOKEN")) repos := core.CreateRepositories(gcs, gh, gcs, gcs, true) var stdout, stderr bytes.Buffer argsFunc := func(_ string) []string { return args } exitCode, err := core.RunBazeliskWithArgsFuncAndConfigAndOutAndErr( argsFunc, repos, cfg, &stdout, &stderr, ) if err != nil { return "", -1, err } if exitCode != 0 { return "", exitCode, fmt.Errorf("bazel stderr: %s", stderr.String()) } return stdout.String(), exitCode, nil } func main() { output, code, err := runAndCapture([]string{"query", "//..."}) if err != nil { log.Fatal(err) } fmt.Printf("exit=%d\n%s", code, output) // exit=0 // //src:main // //src:lib _ = os.Args } ``` -------------------------------- ### Download and cache an executable binary with httputil.DownloadBinary Source: https://context7.com/bazelbuild/bazelisk/llms.txt Downloads a file from a URL, caches it, and optionally verifies its GPG signature. Reads .netrc for credentials. The binary is marked executable. ```go package main import ( "fmt" "log" "github.com/bazelbuild/bazelisk/config" "github.com/bazelbuild/bazelisk/httputil" ) func main() { cfg := config.Static(map[string]string{ "BAZELISK_SHOW_PROGRESS": "1", }) // Download without signature verification (e.g., commit build) path, err := httputil.DownloadBinary( "https://storage.googleapis.com/bazel-builds/artifacts/linux/a3f9b2c1.../bazel", "/tmp/downloads", "bazel_at_commit", cfg, false, // verifySignature ) if err != nil { log.Fatal(err) } fmt.Println(path) // /tmp/downloads/bazel_at_commit (chmod 755) // Download LTS release with GPG signature verification path2, err := httputil.DownloadBinary( "https://releases.bazel.build/7.4.1/release/bazel-7.4.1-linux-x86_64", "/tmp/downloads", "bazel-7.4.1", cfg, true, // verifySignature → fetches .sig, checks against embedded GPG key ) if err != nil { log.Fatalf("signature verification failed: %v", err) } fmt.Println(path2) } ``` -------------------------------- ### GetBazelInstallation Source: https://context7.com/bazelbuild/bazelisk/llms.txt Resolves the Bazel version and downloads the corresponding binary, caching it locally. It returns the path to the cached binary and the resolved version. ```APIDOC ## GetBazelInstallation ### Description Resolves the version and returns a `BazelInstallation` with the absolute path to the binary and the resolved version string. The binary is cached under the Bazelisk home directory using a content-addressed store (SHA-256). ### Method `core.GetBazelInstallation(repos core.Repositories, cfg core.Config) (*core.BazelInstallation, error)` ### Parameters - `repos` (core.Repositories) - The configured repositories to use for fetching Bazel. - `cfg` (core.Config) - The configuration object, which can specify versioning preferences and verification details. ### Returns - `*core.BazelInstallation` - A struct containing the `Version` string and the `Path` to the downloaded Bazel binary. - `error` - An error if the Bazel installation could not be obtained. ``` -------------------------------- ### Configure Bazelisk with .bazeliskrc Source: https://context7.com/bazelbuild/bazelisk/llms.txt Configure Bazelisk persistently using a KEY=VALUE file named .bazeliskrc. This file can be placed in the workspace root or user home directory. Environment variables take precedence. ```bash # /workspace/.bazeliskrc (workspace-level, checked into version control) USE_BAZEL_VERSION=7.4.1 BAZELISK_GITHUB_TOKEN=ghp_teamToken BAZELISK_SHOW_PROGRESS=1 ``` ```bash # ~/.bazeliskrc (user-level, personal defaults) BAZELISK_HOME=/ssd/cache/bazelisk BAZELISK_NOJDK=0 BAZELISK_USER_AGENT=my-corp-build-system/2.0 ``` ```bash # Override at runtime (env > workspace rc > home rc) USE_BAZEL_VERSION=8.x bazelisk build //... # Uses Bazel 8.x regardless of .bazeliskrc contents ``` -------------------------------- ### RunBazelisk Source: https://context7.com/bazelbuild/bazelisk/llms.txt Resolves, downloads (if necessary), and executes the correct Bazel binary using the default configuration. Returns the Bazel process exit code. On non-Windows platforms, `ExecBazelisk` replaces the current process via `syscall.Exec` instead of spawning a child. ```APIDOC ## RunBazelisk ### Description Resolves, downloads (if necessary), and executes the correct Bazel binary using the default configuration sourced from environment variables and `.bazeliskrc` files. Returns the Bazel process exit code. On non-Windows platforms the variant `ExecBazelisk` replaces the current process via `syscall.Exec` instead of spawning a child. ### Method Signature ```go func RunBazelisk(args []string, repos *core.Repositories) (int, error) ``` ### Parameters #### Path Parameters - **args** ([]string) - Required - The list of arguments to pass to the Bazel binary. - **repos** (*core.Repositories) - Required - A struct containing the repositories to use for downloading Bazel. ### Request Example ```go package main import ( "log" "os" "github.com/bazelbuild/bazelisk/core" "github.com/bazelbuild/bazelisk/repositories" ) func main() { gcs := &repositories.GCSRepo{} config := core.MakeDefaultConfig() gitHub := repositories.CreateGitHubRepo(config.Get("BAZELISK_GITHUB_TOKEN")) repos := core.CreateRepositories(gcs, gitHub, gcs, gcs, true) // Run: bazel build //... exitCode, err := core.RunBazelisk([]string{"build", "//..."}, repos) if err != nil { log.Fatalf("bazelisk error: %v", err) } os.Exit(exitCode) } ``` ### Response #### Success Response (0) - **exitCode** (int) - 0 if the Bazel command succeeded. #### Error Response - **exitCode** (int) - Non-zero if the Bazel command failed. - **err** (error) - An error object if Bazelisk encountered an issue. ### Response Example ``` // Output (if build succeeds): exit code 0 // Output (on build failure): exit code 1 ``` ``` -------------------------------- ### MakeDefaultConfig Source: https://context7.com/bazelbuild/bazelisk/llms.txt Constructs the layered configuration stack for Bazelisk, prioritizing environment variables, then workspace `.bazeliskrc`, and finally user-home `.bazeliskrc`. ```APIDOC ## MakeDefaultConfig ### Description Builds the layered configuration stack used by Bazelisk: environment variables (highest priority), workspace-root `.bazeliskrc`, and user-home `.bazeliskrc` (lowest priority). ### Method `core.MakeDefaultConfig() core.Config` ### Returns - `core.Config` - A configuration object that allows retrieving settings from different layers. ``` -------------------------------- ### Build with all incompatible flags using --strict Source: https://context7.com/bazelbuild/bazelisk/llms.txt Ensures forward compatibility by building with all applicable incompatible flags for the current Bazel version. ```sh # Build with every incompatible flag enabled for the current Bazel version bazelisk --strict build //... # Test with every incompatible flag enabled bazelisk --strict test //foo/... ``` -------------------------------- ### bazelisk --strict Source: https://context7.com/bazelbuild/bazelisk/llms.txt Builds with all applicable incompatible flags enabled for the current Bazel version, serving as a forward-compatibility check. ```APIDOC ## --strict — Build with all applicable incompatible flags ### Description Expands to the full list of `--incompatible_*` flags supported by the current Bazel version and passes them all to the build. Acts as a forward-compatibility check. ### Usage ```sh bazelisk --strict build //... bazelisk --strict test //foo/... ``` ``` -------------------------------- ### repositories.CreateGitHubRepo / GitHubRepo.GetVersions Source: https://context7.com/bazelbuild/bazelisk/llms.txt Fetches release tags from a GitHub-hosted Bazel fork and provides download functionality, supporting authentication for rate limit avoidance. ```APIDOC ## repositories.CreateGitHubRepo / GitHubRepo.GetVersions — GitHub fork repository Fetches available release tags from a GitHub-hosted Bazel fork and provides a download function. Authentication via a personal access token avoids API rate limits. ### Methods #### `CreateGitHubRepo(token string) *GitHubRepo` Creates a GitHub repository client. - `token` (string) - Personal access token for authentication. #### `GetVersions(basePath string, org string) ([]string, error)` Lists all stable (non-prerelease) versions available in a Bazel fork. - `basePath` (string) - Base directory for repository operations. - `org` (string) - The GitHub organization hosting the Bazel fork. ### Response Example ``` ["1.0.0", "1.1.0", "2.0.0-beta"] // Filtered to non-prerelease ``` #### `DownloadVersion(org string, version string, targetDir string, targetName string, cfg *config.Config) (string, error)` Downloads a specific version of a Bazel fork. - `org` (string) - The GitHub organization hosting the Bazel fork. - `version` (string) - The specific version tag to download. - `targetDir` (string) - The directory to save the downloaded file. - `targetName` (string) - The desired name for the downloaded file. - `cfg` (*config.Config) - Configuration object. ### Response Example ``` /tmp/bh/downloads/bazel_fork_bin ``` ### Example Usage ```go package main import ( "fmt" "log" "github.com/bazel/bazelisk/config" "github.com/bazel/bazelisk/repositories" ) func main() { gh := repositories.CreateGitHubRepo("ghp_myPersonalToken") tags, err := gh.GetVersions("/tmp/bh", "my-org") if err != nil { log.Fatal(err) } fmt.Println(tags) cfg := config.Null() path, err := gh.DownloadVersion("my-org", "1.1.0", "/tmp/bh/downloads", "bazel_fork_bin", cfg) if err != nil { log.Fatal(err) } fmt.Println(path) } ``` ``` -------------------------------- ### Enable Bash Completion for Bazelisk Source: https://github.com/bazelbuild/bazelisk/blob/master/README.md Generate and source Bash completion scripts for Bazel commands using Bazelisk. This can be done by sourcing the output directly or by emitting it to a file. ```shell source <(bazelisk completion bash) ``` ```shell bazelisk completion bash > bash-complete.bash ``` ```shell source /path/to/bazel-complete.bash ``` -------------------------------- ### Locate the Bazel workspace root with ws.FindWorkspaceRoot Source: https://context7.com/bazelbuild/bazelisk/llms.txt Walks up the directory tree to find the Bazel workspace root by looking for specific marker files. Returns the root directory or an empty string if not found. ```go package main import ( "fmt" "github.com/bazelbuild/bazelisk/ws" ) func main() { root := ws.FindWorkspaceRoot("/home/alice/projects/myapp/src/lib") if root == "" { fmt.Println("not inside a Bazel workspace") } else { fmt.Println(root) // /home/alice/projects/myapp } // Called from outside any workspace fmt.Println(ws.FindWorkspaceRoot("/tmp")) // "" } ``` -------------------------------- ### RunBazeliskWithArgsFuncAndConfigAndOutAndErr Source: https://context7.com/bazelbuild/bazelisk/llms.txt Runs Bazel as a subprocess, capturing its standard output and standard error. This is useful for integrating Bazel execution into other applications and analyzing the build output. ```APIDOC ## RunBazeliskWithArgsFuncAndConfigAndOutAndErr ### Description Runs Bazel as a subprocess (no exec-replace) and redirects its stdout and stderr to the provided `io.Writer` values. Useful for programmatic integration where you need to capture build output. ### Method `core.RunBazeliskWithArgsFuncAndConfigAndOutAndErr(argsFunc func(string) []string, repos core.Repositories, cfg core.Config, stdout io.Writer, stderr io.Writer) (int, error)` ### Parameters - `argsFunc` (func(string) []string) - A function that returns the arguments to pass to Bazel. - `repos` (core.Repositories) - The configured repositories to use for fetching Bazel. - `cfg` (core.Config) - The configuration object for Bazelisk. - `stdout` (io.Writer) - An `io.Writer` to capture the standard output of the Bazel process. - `stderr` (io.Writer) - An `io.Writer` to capture the standard error of the Bazel process. ### Returns - `int` - The exit code of the Bazel process. - `error` - An error if the Bazel process failed to run or encountered an issue. ``` -------------------------------- ### bazelisk --migrate Source: https://context7.com/bazelbuild/bazelisk/llms.txt Identifies which incompatible flags cause build failures by running multiple build attempts. ```APIDOC ## --migrate — Identify which incompatible flags cause failures ### Description Runs the build multiple times: once with no incompatible flags (sanity check), once with all of them, then once per flag individually. Prints a report of passing and failing flags. Exits with code `73` if any flags require migration. ### Usage ```sh bazelisk --migrate build //... ``` ### Output Example ``` --- Running Bazel with no incompatible flags → SUCCESS --- Running Bazel with all incompatible flags → FAILURE --- Running Bazel with --incompatible_foo → SUCCESS --- Running Bazel with --incompatible_bar → FAILURE +++ Result Command was successful with the following flags: --incompatible_foo Migration is needed for the following flags: --incompatible_bar ``` ``` -------------------------------- ### httputil.DownloadBinary Source: https://context7.com/bazelbuild/bazelisk/llms.txt Downloads a file from a URL to a local path, marks it executable, and optionally verifies a GPG detached signature. It also supports reading .netrc for credentials. ```APIDOC ## httputil.DownloadBinary — Download and cache an executable binary ### Description Downloads a file from a URL to a local path, marks it executable (`chmod 0755`), and optionally verifies a GPG detached signature (`.sig` file). Reads `~/.netrc` for Basic-auth credentials when the URL host matches a `netrc` entry. ### Parameters - **url** (string) - The URL to download the binary from. - **localPath** (string) - The local directory to save the downloaded binary. - **filename** (string) - The desired filename for the downloaded binary. - **cfg** (*config.Config) - Configuration object for Bazelisk. - **verifySignature** (bool) - Whether to verify the GPG detached signature. ### Returns - **string**: The full path to the downloaded binary. - **error**: An error if the download or verification fails. ``` -------------------------------- ### Repository API Source: https://context7.com/bazelbuild/bazelisk/llms.txt APIs for assembling and resolving repository configurations. ```APIDOC ## Repository API ### `core.CreateRepositories(ltsRepo, forkRepo, commitRepo, rollingRepo repositories.Repository, useGitHub bool) *core.Repositories` Assembles a `*core.Repositories` bundle by wiring together implementations of repository interfaces. Pass `nil` for any repository type not needed; a no-op implementation will be substituted. **Parameters:** - `ltsRepo` (repositories.Repository): Implementation for LTS repositories. - `forkRepo` (repositories.Repository): Implementation for fork repositories. - `commitRepo` (repositories.Repository): Implementation for commit-based repositories. - `rollingRepo` (repositories.Repository): Implementation for rolling release repositories. - `useGitHub` (bool): Whether to use GitHub for certain repository operations. **Returns:** - `*core.Repositories`: A struct containing the configured repositories. ### `repositories.CreateGitHubRepo(token string) repositories.Repository` Creates a GitHub repository implementation. If an empty token is provided, authentication is skipped. ### `*core.Repositories.ResolveVersion(bazeliskHome string, owner string, version string, cfg config.Config) (string, string, error)` Resolves a Bazel version using the configured repositories. This method determines the exact version string to use based on the provided configuration and version label. **Parameters:** - `bazeliskHome` (string): Path to the Bazelisk home directory. - `owner` (string): The owner of the repository. - `version` (string): The desired version label. - `cfg` (config.Config): The configuration object to use. **Returns:** - `string`: The resolved version string. - `string`: An additional string, potentially related to the resolution process. - `error`: An error if the version resolution fails. ``` -------------------------------- ### ws.FindWorkspaceRoot Source: https://context7.com/bazelbuild/bazelisk/llms.txt Locates the Bazel workspace root directory by searching for marker files. ```APIDOC ## ws.FindWorkspaceRoot — Locate the Bazel workspace root ### Description Walks up the directory tree from the given path until it finds a file named `MODULE.bazel`, `REPO.bazel`, `WORKSPACE.bazel`, or `WORKSPACE`. Returns the directory containing that file, or `""` if none is found. ### Parameters - **path** (string) - The starting directory path to search from. ### Returns - **string**: The path to the Bazel workspace root directory, or an empty string if not found. ``` -------------------------------- ### Bisect Bazel Versions for Build Failures Source: https://github.com/bazelbuild/bazelisk/blob/master/README.md Use the `--bisect` flag to find the Bazel version that introduced a build failure. Specify a range of versions (GOOD..BAD). The GOOD and BAD arguments can be reversed with '~' to find a version that fixes the build. ```shell # Bisect between 6.0.0 and Bazel at HEAD to find the first commit that breaks the build. bazelisk --bisect=6.0.0..HEAD test //foo:bar_test ``` ```shell # Bisect between 6.1.0 and the second release candidate of Bazel 6.2.0 bazelisk --bisect=6.1.0..release-6.2.0rc2 test //foo:bar_test ``` ```shell # Bisect between two commits on the main branch (or branches with `release-` prefix) of the Bazel GitHub repository. bazelisk --bisect=.. test //foo:bar_test ``` ```shell # Bisect between 6.0.0 and Bazel at HEAD to find the first commit that *fixes* the build. bazelisk --bisect=~6.0.0..HEAD test //foo:bar_test ``` -------------------------------- ### Bazelisk Wrapper Delegation Source: https://context7.com/bazelbuild/bazelisk/llms.txt Bazelisk can delegate to a local `tools/bazel` executable if it exists and is executable. This is controlled by the `BAZELISK_SKIP_WRAPPER` environment variable. ```bash #!/usr/bin/env bash # tools/bazel — ensure developers use Bazelisk, not a raw bazel install if [ -z "${BAZELISK_SKIP_WRAPPER:-}" ]; then echo "ERROR: Please install Bazelisk and invoke 'bazel' via Bazelisk." >&2 echo " brew install bazelisk # macOS" >&2 echo " npm install -g @bazel/bazelisk # all platforms" >&2 exit 1 fi exec "${BAZEL_REAL}" "$@" ``` -------------------------------- ### Generate Shell Completion Scripts with Bazelisk Source: https://context7.com/bazelbuild/bazelisk/llms.txt Use the `completion` command to generate shell completion scripts for bash and fish. These scripts help in autocompleting Bazelisk commands. ```bash # Enable bash completion immediately in the current shell source <(bazelisk completion bash) ``` ```bash # Install bash completion system-wide (Ubuntu/Debian) bazelisk completion bash > /etc/bash_completion.d/bazel ``` ```bash # Install fish completion bazelisk completion fish > ~/.config/fish/completions/bazel.fish ``` ```bash # The completion script is tied to the active Bazel version; # re-run after updating .bazelversion. ``` -------------------------------- ### Generate Fish Completion Script Source: https://github.com/bazelbuild/bazelisk/blob/master/README.md Generates a completion script for the fish shell and saves it to the appropriate directory. Note that the script is tied to the active Bazel version. ```shell bazelisk completion fish > ~/.config/fish/completions/bazel.fish ``` -------------------------------- ### repositories.GCSRepo Source: https://context7.com/bazelbuild/bazelisk/llms.txt Implements repository interfaces against Google Cloud Storage buckets for Bazel downloads, with GPG signature verification for LTS releases. ```APIDOC ## repositories.GCSRepo — Google Cloud Storage repository Implements `LTSRepo`, `CommitRepo`, and `RollingRepo` against the official GCS buckets. Downloads are GPG-signature verified for LTS releases. ### Methods #### `GetLTSVersions(basePath string, opts *core.FilterOpts) ([]string, error)` Lists the most recent LTS releases matching the provided filter options. - `basePath` (string) - Base directory for repository operations. - `opts` (*core.FilterOpts) - Filtering options (e.g., `MaxResults`, `Track`, `Filter`). ### Response Example ``` [7.4.1 7.3.2 7.2.1] ``` #### `DownloadLTS(version string, targetDir string, targetName string, cfg *config.Config) (string, error)` Downloads a specific LTS Bazel version. - `version` (string) - The LTS version to download. - `targetDir` (string) - The directory to save the downloaded file. - `targetName` (string) - The desired name for the downloaded file. - `cfg` (*config.Config) - Configuration object. ### Response Example ``` /tmp/bh/downloads/bazel_binary ``` #### `GetLastGreenCommit(basePath string) (string, error)` Retrieves the hash of the last green commit. - `basePath` (string) - Base directory for repository operations. ### Response Example ``` a3f9b2c1d4e5... ``` ``` -------------------------------- ### Resolve Bazel Version Source: https://context7.com/bazelbuild/bazelisk/llms.txt Use `GetBazelVersion` to determine the Bazel version string based on environment variables, workspace configuration, or a default. It implements the full priority chain without downloading. ```Go package main import ( "fmt" "log" "github.com/bazelbuild/bazelisk/config" "github.com/bazelbuild/bazelisk/core" ) func main() { // Scenario 1: env var wins cfg := config.Static(map[string]string{"USE_BAZEL_VERSION": "6.5.0"}) v, err := core.GetBazelVersion(cfg) if err != nil { log.Fatal(err) } fmt.Println(v) // 6.5.0 // Scenario 2: fallback with mode cfg2 := config.Static(map[string]string{"USE_BAZEL_FALLBACK_VERSION": "warn:latest"}) v2, _ := core.GetBazelVersion(cfg2) fmt.Println(v2) // latest (+ prints warning to stderr) // Scenario 3: no configuration → reads .bazelversion from workspace, then "latest" cfg3 := config.Null() v3, _ := core.GetBazelVersion(cfg3) fmt.Println(v3) // e.g. "9.x" if .bazelversion contains "9.x" } ``` -------------------------------- ### Config Factories Source: https://context7.com/bazelbuild/bazelisk/llms.txt Provides factory functions for creating configuration objects. These functions allow for creating configurations from static values, environment variables, files, or layered combinations. ```APIDOC ## Config Factories ### `config.Static` Creates a configuration object from a static map of key-value pairs. Useful for tests or hardcoded settings. ### `config.FromEnv` Creates a configuration object that reads values from environment variables. ### `config.FromFile` Creates a configuration object by reading key-value pairs from a specified file. It parses lines in the format `KEY=VALUE` and ignores comments. ### `config.Layered` Creates a configuration object that layers multiple configuration sources. The first non-empty value encountered wins when retrieving a configuration key. ### `config.Null` Creates an empty configuration object that always returns an empty string for any key. Useful for tests requiring no configuration. ### `config.Config.Get(name string) string` Retrieves the value for a given configuration key. This is the primary interface used throughout Bazelisk. ``` -------------------------------- ### Identify failing incompatible flags with --migrate Source: https://context7.com/bazelbuild/bazelisk/llms.txt Helps migrate to new Bazel versions by running builds with different combinations of incompatible flags and reporting which ones cause failures. Exits with code 73 if migration is needed. ```sh # Identify which incompatible flags break the build bazelisk --migrate build //... # Output example: # --- Running Bazel with no incompatible flags → SUCCESS # --- Running Bazel with all incompatible flags → FAILURE # --- Running Bazel with --incompatible_foo → SUCCESS # --- Running Bazel with --incompatible_bar → FAILURE # +++ Result # Command was successful with the following flags: # --incompatible_foo # Migration is needed for the following flags: # --incompatible_bar ``` -------------------------------- ### GitHub Fork Repository Operations Source: https://context7.com/bazelbuild/bazelisk/llms.txt Fetches release tags from a GitHub-hosted Bazel fork and provides download functionality. Authentication with a personal access token is recommended to avoid rate limits. ```go package main import ( "fmt" "log" "github.com/bazelbuild/bazelisk/config" "github.com/bazelbuild/bazelisk/repositories" ) func main() { gh := repositories.CreateGitHubRepo("ghp_myPersonalToken") // List all stable (non-prerelease) versions of a Bazel fork tags, err := gh.GetVersions("/tmp/bh", "my-org") // → https://api.github.com/repos/my-org/bazel/releases if err != nil { log.Fatal(err) } fmt.Println(tags) // ["1.0.0", "1.1.0", "2.0.0-beta"] filtered to non-prerelease // Download a specific fork version cfg := config.Null() path, err := gh.DownloadVersion("my-org", "1.1.0", "/tmp/bh/downloads", "bazel_fork_bin", cfg) if err != nil { log.Fatal(err) } fmt.Println(path) // /tmp/bh/downloads/bazel_fork_bin // URL used: https://github.com/my-org/bazel/releases/download/1.1.0/bazel-1.1.0-linux-x86_64 } ```