### Setup Go Action Usage Example Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/package-managers.md Example of how to use the actions/setup-go action with caching enabled, referencing the Go package manager configuration. ```yaml - uses: actions/setup-go@v6 with: cache: true # Uses: dependencyFilePattern='go.mod' # cacheFolderCommandList=['go env GOMODCACHE', 'go env GOCACHE'] ``` -------------------------------- ### Basic Go Environment Setup Source: https://github.com/actions/setup-go/blob/main/README.md A minimal example demonstrating how to set up a specific Go version for a workflow. Ensure the Go version is quoted to avoid YAML parsing issues. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: '1.25' # The Go version to download (if necessary) and use. ``` -------------------------------- ### Example Usage of IGoVersionInfo Source: https://github.com/actions/setup-go/blob/main/_autodocs/types.md Shows how to retrieve installation information for a Go version and access details like the download URL and resolved version. ```typescript const info = await getInfoFromDist('1.25', 'amd64'); if (info) { console.log(info.type); // 'dist' console.log(info.downloadUrl); // 'https://go.dev/dl/go1.25.0.linux-amd64.tar.gz' console.log(info.resolvedVersion); // '1.25.0' console.log(info.fileName); // 'go1.25.0.linux-amd64.tar.gz' } ``` -------------------------------- ### Download & Installation Functions Summary Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Summarizes functions for downloading and installing Go. ```typescript installer.getVersionsDist(dlUrl): Promise installer.getInfoFromManifest(versionSpec, stable, auth, arch?, manifest?): Promise installer.getInfoFromDirectDownload(versionSpec, arch, baseUrl): IGoVersionInfo ``` -------------------------------- ### Install Go Version Source: https://github.com/actions/setup-go/blob/main/_autodocs/README.md Installs a specified Go version. Use this to set up the Go environment for your project. Requires the `installer` module. ```typescript import * as installer from './installer'; const versionSpec = '1.25.0'; const checkLatest = false; const auth = 'token ghp_xxx'; const arch = 'x64'; const installDir = await installer.getGo( versionSpec, checkLatest, auth, arch ); console.log(`Go installed at: ${installDir}`); ``` -------------------------------- ### Get Go Installation Path Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/installer.md Acquires a Go installation by version specification, checking for newer versions if requested. Requires authentication for version resolution and supports specifying architecture and a custom download base URL. ```typescript export async function getGo( versionSpec: string, checkLatest: boolean, auth: string | undefined, arch?: Architecture, goDownloadBaseUrl?: string ): Promise ``` ```typescript const installPath = await getGo( '1.25.0', false, 'token ghp_xxx', 'x64' ); console.log(`Go installed at: ${installPath}`); ``` -------------------------------- ### Installer Functions Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Provides functions for downloading, installing, and resolving Go versions. ```typescript export async function getGo( versionSpec: string, checkLatest: boolean, auth: string | undefined, arch?: Architecture, goDownloadBaseUrl?: string ): Promise export async function extractGoArchive(archivePath: string): Promise export async function getManifest(auth: string | undefined): Promise export async function getInfoFromManifest( versionSpec: string, stable: boolean, auth: string | undefined, arch?: Architecture, manifest?: tc.IToolRelease[] | undefined ): Promise export function getInfoFromDirectDownload( versionSpec: string, arch: Architecture, goDownloadBaseUrl: string ): IGoVersionInfo export async function findMatch( versionSpec: string, arch?: Architecture, dlUrl?: string ): Promise export async function getVersionsDist(dlUrl: string): Promise export function parseGoVersionFile(versionFilePath: string): string export function makeSemver(version: string): string export function customToolCacheName(baseUrl: string): string export async function resolveStableVersionInput( versionSpec: string, arch: string, platform: string, manifest: tc.IToolRelease[] | IGoVersion[] ): Promise ``` -------------------------------- ### Installation & Caching Flow Source: https://github.com/actions/setup-go/blob/main/_autodocs/ARCHITECTURE.md Outlines the process for installing a Go version and managing it within the tool cache. ```text installGoVersion(info) ↓ tc.downloadTool(downloadUrl) → Downloads to temp directory ↓ extractGoArchive() → Extracts to temp ├─ Windows: tc.extractZip() └─ Others: tc.extractTar() ↓ [Custom URL?] ├─ Yes: detectInstalledGoVersion() → Get actual version │ └─ No: Use specified version ↓ addExecutablesToToolCache() ├─ Windows: cacheWindowsDir() → Symlink to D: drive └─ Others: tc.cacheDir() → Copy to cache ↓ Return cached directory path ↓ addPath(bin directory) → Add to PATH ``` -------------------------------- ### Setup Go with Custom Mirror/Air-Gapped Environment Source: https://github.com/actions/setup-go/blob/main/_autodocs/README.md Configure the Go environment using a custom download base URL for internal mirrors or air-gapped setups. Specify Go version and architecture. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: '1.25.0' go-download-base-url: 'https://internal-mirror.company.com/go' architecture: 'amd64' ``` -------------------------------- ### Recommended Permissions for Setup-Go Source: https://github.com/actions/setup-go/blob/main/README.md This snippet outlines the recommended permissions for the setup-go action to ensure it can access code and install dependencies correctly. ```yaml permissions: contents: read # access to check out code and install dependencies ``` -------------------------------- ### Example Package Manager Info for Go Source: https://github.com/actions/setup-go/blob/main/_autodocs/types.md Provides an example configuration for the Go package manager, specifying 'go.mod' as the dependency file and commands to find module and build cache directories. ```typescript const info: PackageManagerInfo = { dependencyFilePattern: 'go.mod', cacheFolderCommandList: [ 'go env GOMODCACHE', 'go env GOCACHE' ] }; ``` -------------------------------- ### Type for Installation Type Source: https://github.com/actions/setup-go/blob/main/_autodocs/types.md Defines the possible sources for Go installation: direct download from distribution ('dist') or from a repository manifest ('manifest'). ```typescript type InstallationType = 'dist' | 'manifest' ``` -------------------------------- ### Get Exact Go Version Installed Source: https://github.com/actions/setup-go/blob/main/docs/advanced-usage.md Use the `go-version` output to obtain the precise Go version installed by the action. This is useful for operating with the exact version in conditional statements. ```yaml jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 id: go124 with: go-version: '^1.24' - run: echo "Installed Go version: ${{ steps.go124.outputs.go-version }}" ``` -------------------------------- ### Installer Interfaces Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Defines the structure for Go version information. ```typescript export interface IGoVersionFile { filename: string os: string arch: string } export interface IGoVersion { version: string stable: boolean files: IGoVersionFile[] } export interface IGoVersionInfo { type: InstallationType downloadUrl: string resolvedVersion: string fileName: string } ``` -------------------------------- ### Complete Workflow Example Source: https://github.com/actions/setup-go/blob/main/_autodocs/configuration.md A full GitHub Actions workflow demonstrating the setup-go action. It checks out code, sets up Go with specific version and caching configurations, and then runs build and test commands. ```yaml name: Test on: push jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 id: setup with: go-version: '1.25' go-version-file: 'go.mod' cache: true cache-dependency-path: 'go.sum' check-latest: false architecture: 'x64' - name: Show Go version run: go version - name: Build run: go build ./... - name: Test run: go test ./... - name: Check cache hit run: | if [ "${{ steps.setup.outputs.cache-hit }}" == "true" ]; then echo "Cache hit - modules restored from cache" else echo "Cache miss - modules downloaded fresh" fi ``` -------------------------------- ### Example Usage of IGoVersion Source: https://github.com/actions/setup-go/blob/main/_autodocs/types.md Demonstrates how to fetch Go version distribution information and access details like the version string and filenames. ```typescript const versions = await getVersionsDist('https://go.dev/dl/?mode=json&include=all'); const version = versions[0]; // Most recent version console.log(version.version); // '1.25.0' console.log(version.stable); // true console.log(version.files[0].filename); // 'go1.25.0.linux-amd64.tar.gz' ``` -------------------------------- ### run() Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/main.md The main entry point for the setup-go action. It handles resolving the Go version, downloading Go if necessary, configuring the environment (PATH, GOROOT), and managing caching of modules and build outputs. It also sets action outputs for the installed Go version and cache status. ```APIDOC ## `run()` ### Description Entry point for the setup-go action. Resolves Go version, downloads if needed, configures PATH, sets GOROOT, and restores cache. ### Method `export async function run(): Promise` ### Behavior 1. Resolves version from `go-version` input or `go-version-file` 2. Sets `GOTOOLCHAIN=local` to prevent automatic toolchain downloads 3. Downloads Go if version is specified 4. Adds Go binary directory to PATH 5. Sets GOROOT for Go < 1.9 compatibility 6. Adds $GOPATH/bin to PATH 7. Registers error/warning problem matchers 8. Restores cached Go modules and build outputs 9. Sets action outputs: `go-version` and `cache-hit` 10. Displays Go environment summary ### Configuration Inputs - `go-version`: Specific version or range (e.g., `'1.25'`, `'^1.24.0'`) - `go-version-file`: Path to version file (go.mod, go.work, .go-version, .tool-versions) - `check-latest`: Boolean to check for newer matching versions - `token`: GitHub token for API authentication - `cache`: Boolean to enable/disable module caching (default: true) - `cache-dependency-path`: Path(s) to dependency files (glob patterns supported) - `architecture`: Target architecture (auto-detected if not specified) - `go-download-base-url`: Custom base URL for Go distributions ### Action Outputs | Output | Type | Description | |--------|------|-------------| | `go-version` | string | Installed Go version (useful when version range was specified) | | `cache-hit` | boolean | Whether cached modules were restored | ### Throws Marks action as failed if any step fails. ### Example Typical usage in a GitHub Actions workflow: ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: '1.25' cache: true - run: go build ./cmd/myapp ``` ``` -------------------------------- ### getGo() Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/installer.md Main entry point for acquiring a Go installation. It handles version resolution, downloading, extraction, and caching. ```APIDOC ## getGo() ### Description Main entry point for acquiring a Go installation. It handles version resolution, downloading, extraction, and caching. ### Method async ### Parameters #### Path Parameters - **versionSpec** (string) - Required - Version specification (e.g., `'1.25'`, `'^1.24.0'`, `'stable'`, `'1.x'`) - **checkLatest** (boolean) - Required - Check if a newer version matching the spec is available - **auth** (string | undefined) - Required - GitHub token for API authentication (format: `token {token}`) - **arch** (Architecture) - Optional - Target architecture (`'x64'`, `'x32'`, `'arm'`, or other Node.js arch strings). Defaults to `os.arch()`. - **goDownloadBaseUrl** (string) - Optional - Custom base URL for Go distributions (e.g., for mirrors) ### Return Type Promise resolving to the path of the installed Go directory (e.g., `/home/runner/tool-cache/go/1.25.0/x64`). ### Throws Throws error if: - Version specification is invalid or unsupported - Version cannot be resolved from any source - Download fails or checksum validation fails - Custom base URL is used with version aliases (`'stable'`, `'oldstable'`) - Custom base URL without version listing is used with non-exact version specs ### Example ```typescript const installPath = await getGo( '1.25.0', false, 'token ghp_xxx', 'x64' ); console.log(`Go installed at: ${installPath}`); ``` ``` -------------------------------- ### Example GitHub Actions Workflow Usage Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/main.md Demonstrates typical usage of the setup-go action in a GitHub Actions workflow. This snippet shows how to specify the Go version and enable caching. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: '1.25' cache: true - run: go build ./cmd/myapp ``` -------------------------------- ### Environment Setup and Go Version Parsing Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Use `main.addBinToPath` to add the Go binary directory to the system's PATH. `main.parseGoVersion` parses a Go version string. ```typescript main.addBinToPath(): Promise main.parseGoVersion(versionString): string ``` -------------------------------- ### Setup Go with Caching Source: https://github.com/actions/setup-go/blob/main/_autodocs/README.md Configure the Go environment with caching enabled. Specify the cache dependency path for accurate caching. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: 'stable' cache: true cache-dependency-path: 'go.sum' ``` -------------------------------- ### Build Action from Source Source: https://github.com/actions/setup-go/blob/main/_autodocs/README.md Install dependencies and build the TypeScript action into JavaScript files for distribution. ```bash npm install npm run build ``` -------------------------------- ### Retrieve Installed Go Version Source: https://github.com/actions/setup-go/blob/main/_autodocs/configuration.md The 'go-version' output provides the concrete version number of the installed Go, which is useful when a version range was specified in the 'go-version' input. ```yaml - uses: actions/setup-go@v6 id: setup with: go-version: '1.25.x' - run: echo "Installed ${{ steps.setup.outputs.go-version }}" # Outputs: Installed 1.25.0 ``` ```yaml - uses: actions/setup-go@v6 id: go with: go-version: '^1.24' - name: Show version run: go version # Already executed by action, output: go version go1.25.0 linux/amd64 - name: Use output run: echo "Version is ${{ steps.go.outputs.go-version }}" ``` -------------------------------- ### Get Info From Direct Download Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Gets Go version information directly from a download URL. ```APIDOC ## installer.getInfoFromDirectDownload ### Description Retrieves Go version information by directly processing a download URL for a specific version and architecture. ### Method sync ### Parameters #### Path Parameters None #### Query Parameters - **versionSpec** (string) - Required - The Go version specification. - **arch** (Architecture) - Required - The target architecture. - **goDownloadBaseUrl** (string) - Required - The base URL for Go downloads. ### Returns - IGoVersionInfo - An object containing Go version information. ``` -------------------------------- ### Basic Usage of isSelfHosted Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/utils.md A simple example demonstrating how to call the isSelfHosted function and log whether the current environment is self-hosted or GitHub-hosted. ```typescript if (isSelfHosted()) { console.log('Running on self-hosted runner'); } else { console.log('Running on GitHub-hosted runner'); } ``` -------------------------------- ### Configure Go Environment Setup Source: https://github.com/actions/setup-go/blob/main/README.md This snippet shows the full configuration options for setting up the Go environment. It includes specifying the Go version, Go module cache path, architecture, and download URL. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: # Version or version range of Go to use go-version: '1.23' # Path to go.mod, go.work, .go-version, or .tool-versions file # Note: if both go-version and go-version-file are provided, go-version takes precedence. go-version-file: 'go.mod' # Set this option if you want the action to check for the latest available version # Default: false check-latest: false # GitHub token for authentication token: ${{ github.token }} # Used to specify whether caching is needed. # Default: true cache: true # Path to dependency files for caching cache-dependency-path: 'go.sum' # Architecture to install (auto-detected if not specified) architecture: 'x64' # Custom base URL for Go downloads (e.g., for mirrors) go-download-base-url: '' ``` -------------------------------- ### Setup Go for Monorepo with Multiple go.mod Files Source: https://github.com/actions/setup-go/blob/main/_autodocs/README.md Configure the Go environment for a monorepo structure. Supports caching with multiple dependency files. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version-file: 'go.mod' cache: true cache-dependency-path: | go.sum tools/go.sum internal/go.sum ``` -------------------------------- ### Main Action Entry Point Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md The primary function to execute the Go Action. It orchestrates the setup and configuration of Go for the workflow. ```APIDOC ## main.run ### Description This function is the main entry point for the Go Action. It handles the setup and configuration of Go within the workflow environment. ### Method async ### Signature run(): Promise ``` -------------------------------- ### Get Info From Manifest Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Retrieves detailed information about a Go version from a manifest. ```APIDOC ## installer.getInfoFromManifest ### Description Obtains detailed information for a specific Go version (`versionSpec`) by querying a provided manifest (`manifest`). It can filter by stability and target architecture. ### Method async ### Parameters #### Path Parameters None #### Query Parameters - **versionSpec** (string) - Required - The Go version specification. - **stable** (boolean) - Required - Whether to look for a stable version. - **auth** (string | undefined) - Optional - Authentication token for accessing the manifest. - **arch** (Architecture) - Optional - The target architecture. - **manifest** (tc.IToolRelease[] | undefined) - Optional - The manifest data to search within. ### Returns - Promise - A promise that resolves to `IGoVersionInfo` if found, otherwise null. ``` -------------------------------- ### Get Arch Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Retrieves the system architecture. ```APIDOC ## system.getArch ### Description Returns the system architecture (e.g., 'x64', 'arm64'). ### Method `system.getArch(arch): string` ### Parameters - **arch** (string) - Required - The architecture to query. ``` -------------------------------- ### Cache Restore and Get Directory Path Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Use `cache-restore.restoreCache` to restore a Go build cache. Use `cache-utils.getCacheDirectoryPath` to get the path to the cache directory based on package manager information. ```typescript cache-restore.restoreCache(versionSpec, packageManager, cacheDependencyPath?): Promise cache-utils.getCacheDirectoryPath(packageManagerInfo): Promise ``` -------------------------------- ### Basic Go Setup in GitHub Actions Workflow Source: https://github.com/actions/setup-go/blob/main/_autodocs/README.md Configures the Go environment within a GitHub Actions workflow. Specify the desired Go version using the `go-version` input. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: '1.25' - run: go build ./... ``` -------------------------------- ### IGoVersionInfo Interface Fields Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Defines the structure for Go version download information, including installation type, download URL, resolved version, and filename. ```typescript type: InstallationType // 'dist' or 'manifest' downloadUrl: string // Full URL to archive resolvedVersion: string // Concrete version fileName: string // Archive filename ``` -------------------------------- ### Get Architecture Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Retrieves the system architecture, potentially normalizing it. ```APIDOC ## system.getArch ### Description Normalizes and returns a string representing the system architecture, based on the provided `Architecture` type. ### Method sync ### Parameters #### Path Parameters None #### Query Parameters - **arch** (Architecture) - Required - The architecture value to normalize. ### Returns - string - The normalized architecture string. ``` -------------------------------- ### Get Platform Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Retrieves the current operating system platform. ```APIDOC ## system.getPlatform ### Description Returns a string representing the current operating system platform (e.g., 'linux', 'win32', 'darwin'). ### Method sync ### Returns - string - The name of the current platform. ``` -------------------------------- ### Matrix Testing with Multiple Go Versions Source: https://github.com/actions/setup-go/blob/main/docs/advanced-usage.md Utilize GitHub Actions matrix strategy to install and test against multiple Go versions simultaneously. Each Go version is defined in the matrix. ```yaml jobs: build: runs-on: ubuntu-latest strategy: matrix: go: [ '1.24', '1.25' ] name: Go ${{ matrix.go }} sample steps: - uses: actions/checkout@v6 - name: Setup go uses: actions/setup-go@v6 with: go-version: ${{ matrix.go }} - run: go run hello.go ``` -------------------------------- ### Get Command Output Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Executes a tool command and returns its standard output. ```APIDOC ## cache-utils.getCommandOutput ### Description Executes a specified command in the system shell and captures its standard output. ### Method async ### Parameters #### Path Parameters None #### Query Parameters - **toolCommand** (string) - Required - The command to execute. ### Returns - Promise - A promise that resolves with the command's standard output as a string. ``` -------------------------------- ### Interface for Go Version Info Source: https://github.com/actions/setup-go/blob/main/_autodocs/types.md Defines the structure for download information of a specific Go version and platform, including the installation type and download URL. ```typescript interface IGoVersionInfo { type: InstallationType downloadUrl: string resolvedVersion: string fileName: string } ``` -------------------------------- ### addBinToPath() Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/main.md Adds the GOPATH/bin directory to the system's PATH, making installed Go tools accessible from the command line. It checks for the existence of the Go command and GOPATH, creates necessary directories if they don't exist, and then updates the PATH environment variable. ```APIDOC ## `addBinToPath()` ### Description Adds the GOPATH/bin directory to the PATH to make installed Go tools available. ### Method `export async function addBinToPath(): Promise` ### Return Type Boolean: true if GOPATH/bin was found and added to PATH, false otherwise. ### Behavior 1. Checks if `go` command exists in PATH 2. Retrieves GOPATH via `go env GOPATH` 3. Creates GOPATH if it doesn't exist 4. Creates GOPATH/bin if it doesn't exist 5. Adds GOPATH/bin to PATH ### Example ```typescript const added = await addBinToPath(); if (added) { console.log('GOPATH/bin added to PATH'); } else { console.log('Go not found or GOPATH unavailable'); } ``` ``` -------------------------------- ### Specify Go Major and Minor Version Source: https://github.com/actions/setup-go/blob/main/docs/advanced-usage.md Specify only the major and minor version to use the latest available patch version. This speeds up setup as the version is likely pre-installed. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: '1.25' - run: go run hello.go ``` -------------------------------- ### Go Environment Variables Example Source: https://github.com/actions/setup-go/blob/main/_autodocs/ARCHITECTURE.md Demonstrates setting GOTOOLCHAIN to 'local' to prevent automatic Go toolchain downloads. This is exported in both process.env and runner env for Go versions 1.9 and later. For Go versions prior to 1.9, GOROOT is also explicitly set. ```bash GOTOOLCHAIN = 'local' └─ Prevents automatic Go toolchain downloads Set in both process.env and runner env See: https://go.dev/doc/toolchain [Go < 1.9?] ├─ Yes: GOROOT = /path/to/go │ └─ Exported via core.exportVariable() │ └─ No: Don't set GOROOT (Go 1.9+ auto-detects) ``` -------------------------------- ### Getting Cache Directory Paths Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/package-managers.md Shows how to obtain cache directory paths by executing a list of commands using Promise.allSettled for concurrent execution. ```typescript const pathOutputs = await Promise.allSettled( packageManagerInfo.cacheFolderCommandList.map(async command => getCommandOutput(command) ) ); // Returns: ['/home/user/go/pkg/mod', '/home/user/.cache/go-build'] ``` -------------------------------- ### Installer and Custom Cache Name Functions Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Use `installer.getManifest` to retrieve a list of available tool releases. `installer.customToolCacheName` generates a unique cache name based on a base URL. ```typescript installer.getManifest(auth): Promise installer.customToolCacheName(baseUrl): string ``` -------------------------------- ### Get Go Version Info from Direct Download Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/installer.md Constructs download URL information for a specific Go version, architecture, and download base URL. Use this when you need to directly specify all download parameters. ```typescript const info = getInfoFromDirectDownload( '1.25.0', 'x64', 'https://mirrors.example.com/go' ); console.log(info.downloadUrl); // https://mirrors.example.com/go/go1.25.0.linux-amd64.tar.gz ``` -------------------------------- ### Parse Go Version from File Source: https://github.com/actions/setup-go/blob/main/_autodocs/README.md Parses the Go version from a specified file, such as 'go.mod'. Useful for automatically detecting the Go version required by your project. Requires the `installer` module. ```typescript import * as installer from './installer'; const version = installer.parseGoVersionFile('go.mod'); console.log(version); // '1.25.0' or '1.24' ``` -------------------------------- ### Get Go Version Info from Direct Download Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/installer.md Constructs download information for direct download URLs when version listing is unavailable. Requires version specification, architecture, and the Go download base URL. ```typescript export function getInfoFromDirectDownload( versionSpec: string, arch: Architecture, goDownloadBaseUrl: string ): IGoVersionInfo ``` -------------------------------- ### Convert Version String to SemVer Source: https://github.com/actions/setup-go/blob/main/_autodocs/README.md Converts a Go version string into a SemVer-compatible format. Handles various version formats, including pre-release tags. Requires the `installer` module. ```typescript import * as installer from './installer'; console.log(installer.makeSemver('1.25')); // '1.25.0' console.log(installer.makeSemver('1.20beta1')); // '1.20.0-beta.1' ``` -------------------------------- ### Save and Get State in Action Phases Source: https://github.com/actions/setup-go/blob/main/_autodocs/types.md Use core.saveState() to store a value and core.getState() to retrieve it between different phases of an action. This is useful for passing information from a setup phase to a subsequent execution or cleanup phase. ```typescript // In cache-restore.ts core.saveState(State.CachePrimaryKey, primaryKey); // In cache-save.ts const primaryKey = core.getState(State.CachePrimaryKey); const matchedKey = core.getState(State.CacheMatchedKey); ``` -------------------------------- ### Module Dependency Graph Source: https://github.com/actions/setup-go/blob/main/_autodocs/ARCHITECTURE.md Illustrates the module dependencies within the setup-go action, showing the entry points and their relationships. ```text setup-go.ts (entry point) └─ main.ts (main action logic) ├─ installer.ts (version resolution & download) │ ├─ system.ts (platform/arch conversion) │ ├─ utils.ts (stable version aliases) │ └─ @actions/tool-cache (caching & extraction) ├─ cache-restore.ts (cache restore) │ ├─ cache-utils.ts (cache helpers) │ │ └─ package-managers.ts (package manager config) │ └─ @actions/cache (cache API) └─ @actions/core (action APIs) cache-save.ts (post-action) ├─ cache-utils.ts (cache helpers) │ └─ package-managers.ts (package manager config) └─ @actions/cache (cache API) types.ts (type definitions) constants.ts (enums) ``` -------------------------------- ### Fetch Go Versions Distribution List Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/installer.md Fetches the complete list of available Go versions from a specified download endpoint. Use this to get the latest versions or to check available releases. ```typescript const versions = await getVersionsDist('https://go.dev/dl/?mode=json&include=all'); console.log(`Latest version: ${versions?.[0].version}`); ``` -------------------------------- ### Main Action Entry Points Source: https://github.com/actions/setup-go/blob/main/_autodocs/INDEX.md These functions represent the primary entry points for the setup-go action's core logic and utility operations. ```APIDOC ## Main Entry Points ### `run()` **Description**: The primary entry point for the action's main logic. ### `addBinToPath()` **Description**: Adds the Go binary directory (GOPATH/bin) to the system's PATH environment variable. ### `parseGoVersion()` **Description**: Parses and extracts the Go version information from command output. ``` -------------------------------- ### Get Package Manager Information Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/cache-utils.md Retrieves configuration details for a given package manager. Use this to get patterns for dependency files and commands to find cache folders. ```typescript export const getPackageManagerInfo = async (packageManager: string): Promise ``` ```typescript const info = await getPackageManagerInfo('default'); console.log(info.dependencyFilePattern); // 'go.mod' console.log(info.cacheFolderCommandList); // ['go env GOMODCACHE', 'go env GOCACHE'] ``` -------------------------------- ### Sequential Action Execution Flow Source: https://github.com/actions/setup-go/blob/main/_autodocs/ARCHITECTURE.md Illustrates the sequential execution order of core tasks within the main.run() function of the setup-go action. Each step depends on the successful completion of the preceding one, ensuring a stable environment is built progressively. ```plaintext main.run() ├─ resolveVersionInput() ─┐ ├─ installer.getGo() ────┼─ Sequential ├─ addPath() ────────────┤ (each depends on previous) └─ restoreCache() ───────┘ ``` -------------------------------- ### Use Go Pre-release Version (Beta) Source: https://github.com/actions/setup-go/blob/main/docs/advanced-usage.md Download and use beta versions of Go by specifying the version string, such as '1.19.0-beta.1'. ```yaml # Beta version steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: '1.19.0-beta.1' - run: go version ``` -------------------------------- ### Get Manifest Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Retrieves the tool release manifest, optionally using authentication. ```APIDOC ## installer.getManifest ### Description Fetches the manifest of available tool releases. ### Method `installer.getManifest(auth): Promise` ### Parameters - **auth** (string) - Optional - Authentication token or credentials. ``` -------------------------------- ### Version Management Functions Source: https://github.com/actions/setup-go/blob/main/_autodocs/INDEX.md Functions related to resolving, installing, and managing Go versions. ```APIDOC ## Version Management ### `getGo()` **Description**: Handles the main logic for resolving and downloading the specified Go version. ### `makeSemver()` **Description**: Converts a given version string into a semantic versioning format. ### `parseGoVersionFile()` **Description**: Reads and parses the Go version information from a version file. ### `findMatch()` **Description**: Finds a matching Go version from a list based on input criteria. ### `getVersionsDist()` **Description**: Fetches the list of available Go versions from the distribution source. ### `getManifest()` **Description**: Fetches the tool manifest, likely containing version details and checksums. ### `resolveStableVersionInput()` **Description**: Resolves stable version aliases (e.g., 'stable', 'latest') to specific version numbers. ``` -------------------------------- ### Get Versions Distribution Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Retrieves a list of available Go versions from a distribution URL. ```APIDOC ## installer.getVersionsDist ### Description Fetches and parses the Go version information from a given distribution URL (`dlUrl`). This provides a list of available Go versions. ### Method async ### Parameters #### Path Parameters None #### Query Parameters - **dlUrl** (string) - Required - The URL of the Go version distribution file. ### Returns - Promise - A promise that resolves to an array of `IGoVersion` objects, or null if fetching fails. ``` -------------------------------- ### Get Cache Directory Path Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Determines the cache directory path for a given package manager. ```APIDOC ## cache-utils.getCacheDirectoryPath ### Description Calculates and returns the path(s) to the cache directory used by the specified package manager, based on its configuration. ### Method async ### Parameters #### Path Parameters None #### Query Parameters - **packageManagerInfo** (PackageManagerInfo) - Required - Information about the package manager, typically obtained from `getPackageManagerInfo`. ### Returns - Promise - A promise that resolves with an array of strings, each representing a cache directory path. ``` -------------------------------- ### run() Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/cache-save.md Entry point for the post-action cache save. Saves Go module and build cache if caching is enabled and dependencies were modified. ```APIDOC ## run() ### Description Entry point for the post-action cache save. Saves Go module and build cache if caching is enabled and dependencies were modified. ### Method N/A (Function Signature) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **earlyExit** (boolean) - Optional - If true, calls `process.exit(0)` after completion (optimization for slow post-action steps) ### Behavior 1. Checks if `cache` input is enabled. 2. Retrieves saved cache state from prior cache-restore phase. 3. Gets package manager configuration. 4. Retrieves cache paths from `go env GOMODCACHE` and `go env GOCACHE`. 5. Verifies cache paths exist on disk. 6. Compares current cache key against previously restored cache key. 7. Skips save if cache was already a hit (no modifications). 8. Saves new cache if dependencies changed. 9. Logs cache save result or reasons for skipping. ### Warnings Logs warnings for: Cache input disabled, No cache folders found, Cache folder path retrieved but doesn't exist, Primary cache key generation failed. ### Early Exit Optimization Resolves slow post-action issue by optionally exiting immediately after cache save. ### Error Handling All errors are caught and logged as warnings (never fails the action). ### State Dependencies - `State.CachePrimaryKey`: Cache key to save under - `State.CacheMatchedKey`: Previous cache key (skips save if matched) ### Example ```yaml - uses: actions/setup-go@v6 with: cache: true ``` ``` -------------------------------- ### @actions/core Functions Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Provides utility functions for interacting with the GitHub Actions environment, such as getting inputs, managing state, and logging. ```APIDOC ## @actions/core ### Description Provides utility functions for interacting with the GitHub Actions environment, such as getting inputs, managing state, and logging. ### Functions - **getInput(name)**: (string) - Gets the value of an input. - **getBooleanInput(name)**: (boolean) - Gets the boolean value of an input. - **getState(name)**: (string) - Gets the value of a state. - **saveState(name, value)**: (void) - Saves a state. - **setOutput(name, value)**: (void) - Sets an output. - **setFailed(message)**: (void) - Sets the action to failed. - **addPath(path)**: (void) - Adds a path to the system PATH. - **exportVariable(name, value)**: (void) - Exports an environment variable. - **info(message)**: (void) - Logs an informational message. - **debug(message)**: (void) - Logs a debug message. - **warning(message)**: (void) - Logs a warning message. - **startGroup(name)**: (void) - Starts a group for logging. - **endGroup()**: (void) - Ends a group for logging. ``` -------------------------------- ### Go Version Not Specified Warning Source: https://github.com/actions/setup-go/blob/main/_autodocs/errors.md Logs a warning when the 'go-version' input is not specified, indicating that the action will attempt to use a pre-installed Go version. ```text [warning]go-version input was not specified. The action will try to use pre-installed version. ``` -------------------------------- ### Use Go Pre-release Version (RC) Source: https://github.com/actions/setup-go/blob/main/docs/advanced-usage.md Download and use release candidate (RC) versions of Go by specifying the version string, such as '1.25.0-rc.2'. ```yaml # RC version steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version: '1.25.0-rc.2' - run: go version ``` -------------------------------- ### Setting 'go-version' Output Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/constants.md Demonstrates setting the 'go-version' output variable in the main action. This output is useful when a version range is specified for Go. ```typescript // go-version output (set in main.ts) core.setOutput('go-version', parseGoVersion(goVersion)); ``` -------------------------------- ### Specify Go Version from .go-version File Source: https://github.com/actions/setup-go/blob/main/docs/advanced-usage.md Use the 'go-version-file' input to specify the path to a .go-version file. The action will read the Go version from this file. Ensure the file exists in the repository. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version-file: '.go-version' # Read Go version from .go-version - run: go version ``` -------------------------------- ### Get Package Manager Info Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Retrieves information about a specific package manager, including its cache directory command and dependency file pattern. ```APIDOC ## cache-utils.getPackageManagerInfo ### Description Fetches configuration details for a given package manager, such as the command to find its cache directory and the typical pattern for dependency files. ### Method async ### Parameters #### Path Parameters None #### Query Parameters - **packageManager** (string) - Required - The name of the package manager (e.g., 'npm', 'yarn', 'go'). ### Returns - Promise - A promise that resolves with `PackageManagerInfo` containing details about the package manager. ``` -------------------------------- ### Construct Go Download Filename Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/system.md Demonstrates how to use `getPlatform()` and `getArch()` to construct a Go download filename. This is useful for dynamically fetching the correct Go distribution tarball. ```typescript const platform = getPlatform(); // 'linux' const arch = getArch('x64'); // 'amd64' const filename = `go1.25.0.${platform}-${arch}.tar.gz`; // 'go1.25.0.linux-amd64.tar.gz' ``` -------------------------------- ### Get Go Version Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Retrieves a Go version based on the specified version string, with options to check for the latest version and provide authentication. ```APIDOC ## installer.getGo ### Description Fetches a specific Go version matching the `versionSpec`. It can optionally check for the latest available version and use provided authentication. Supports specifying architecture and a custom download base URL. ### Method async ### Parameters #### Path Parameters None #### Query Parameters - **versionSpec** (string) - Required - The Go version to install (e.g., '1.x', '1.x.x', 'latest'). - **checkLatest** (boolean) - Required - Whether to check for the latest available version matching the spec. - **auth** (string | undefined) - Optional - Authentication token for downloading Go. - **arch** (Architecture) - Optional - The target architecture for the Go installation. - **goDownloadBaseUrl** (string | undefined) - Optional - A custom base URL for downloading Go binaries. ### Returns - Promise - A promise that resolves to the path where Go was installed. ``` -------------------------------- ### Specify Go Version from .tool-versions File Source: https://github.com/actions/setup-go/blob/main/docs/advanced-usage.md Use the 'go-version-file' input to specify the path to a .tool-versions file. The action will read the Go version from this file, supporting asdf standards. Ensure the file exists in the repository. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version-file: '.tool-versions' # Read Go version from .tool-versions - run: go version ``` -------------------------------- ### Action Outputs Type Definition Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Defines the structure for the action's output values, including the installed Go version and cache hit status. ```typescript type ActionOutputs = { 'go-version': string // Installed version 'cache-hit': boolean // Cache was restored } ``` -------------------------------- ### Specify Go Version from go.mod File Source: https://github.com/actions/setup-go/blob/main/docs/advanced-usage.md Use the 'go-version-file' input to specify the path to a go.mod file. The action will read the Go version from this file. Ensure the file exists in the repository. ```yaml steps: - uses: actions/checkout@v6 - uses: actions/setup-go@v6 with: go-version-file: 'path/to/go.mod' # Read Go version from go.mod - run: go version ``` -------------------------------- ### Entry Points Summary Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Summarizes the main action and post-action entry points. ```typescript // Main action main.run(): Promise // Post-action cache-save.run(earlyExit?: boolean): Promise ``` -------------------------------- ### Using StableReleaseAlias in GitHub Actions Workflow Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/utils.md Demonstrates how to use 'stable' and 'oldstable' aliases to specify the Go version in the actions/setup-go action. ```yaml # Use latest stable Go - uses: actions/setup-go@v6 with: go-version: 'stable' # Use previous stable line (support multiple versions) - uses: actions/setup-go@v6 with: go-version: 'oldstable' ``` -------------------------------- ### PackageManagerInfo Interface Definition Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/package-managers.md Defines the structure for package manager information, including the dependency file pattern and commands to get cache directory paths. ```typescript export interface PackageManagerInfo { dependencyFilePattern: string cacheFolderCommandList: string[] } ``` -------------------------------- ### Enable Caching with Multiple Dependency Paths Source: https://github.com/actions/setup-go/blob/main/docs/adrs/0000-caching-dependencies.md Enable caching for Go dependencies and specify multiple dependency files using a multi-line 'cache-dependency-path'. The action will calculate a common hash for all specified files. ```yaml steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v3 with: go-version: '18' cache: true cache-dependency-path: | **/go.sum **/go.mod ``` -------------------------------- ### Saving and Getting State Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/constants.md Demonstrates how to save state in one action phase and retrieve it in another. This is crucial for inter-phase communication, like cache hit detection. ```typescript // In cache-restore.ts (main phase) core.saveState(State.CachePrimaryKey, primaryKey); core.saveState(State.CacheMatchedKey, cacheKey); // In cache-save.ts (post phase) const primaryKey = core.getState(State.CachePrimaryKey); const matchedKey = core.getState(State.CacheMatchedKey); ``` -------------------------------- ### Core Actions Module Functions Source: https://github.com/actions/setup-go/blob/main/_autodocs/API-SURFACE.md Provides essential functions for interacting with the GitHub Actions environment, such as getting inputs, managing state, setting outputs, and logging messages. ```typescript core.getInput(name): string core.getBooleanInput(name): boolean core.getState(name): string core.saveState(name, value): void core.setOutput(name, value): void core.setFailed(message): void core.addPath(path): void core.exportVariable(name, value): void core.info(message): void core.debug(message): void core.warning(message): void core.startGroup(name): void core.endGroup(): void ``` -------------------------------- ### Cache Restore Phase Source: https://github.com/actions/setup-go/blob/main/_autodocs/ARCHITECTURE.md Details the steps taken by the main action to restore the Go module and build cache. ```text Main action (src/main.ts) ↓ [cache input = true?] ├─ No: Skip caching │ └─ Yes: restoreCache() ├─ getPackageManagerInfo('default') │ └─ Returns: {dependencyFilePattern: 'go.mod', cacheFolderCommandList: [...]} │ ├─ findDependencyFile() │ └─ Locate go.mod in GITHUB_WORKSPACE │ ├─ glob.hashFiles() → SHA256(go.mod or specified file) │ ├─ Generate cache key: │ setup-go-{OS}-{arch}-{linuxImageOS}-go-{version}-{fileHash} │ ├─ saveState(State.CachePrimaryKey, primaryKey) │ ├─ cache.restoreCache(paths, primaryKey) │ └─ Restores GOMODCACHE and GOCACHE │ └─ setOutput('cache-hit', Boolean(restoredKey)) ``` -------------------------------- ### Get Go Version Info from Manifest Source: https://github.com/actions/setup-go/blob/main/_autodocs/api-reference/installer.md Resolves a Go version specification using a manifest. It can optionally use a pre-fetched manifest and supports specifying architecture and stability. ```typescript export async function getInfoFromManifest( versionSpec: string, stable: boolean, auth: string | undefined, arch?: Architecture, manifest?: tc.IToolRelease[] | undefined ): Promise ``` ```typescript const info = await getInfoFromManifest('1.2x', true, 'token ghp_xxx', 'x64'); if (info) { console.log(`Resolved to: ${info.resolvedVersion}`); console.log(`Download URL: ${info.downloadUrl}`); } ```