### Install Dependencies Source: https://github.com/actions/checkout/blob/main/CONTRIBUTING.md Run this command to install project dependencies. ```bash npm install ``` -------------------------------- ### GitVersion Usage Example Source: https://github.com/actions/checkout/blob/main/_autodocs/types.md Demonstrates how to create a GitVersion object and check if it meets a minimum requirement. ```typescript const version = new GitVersion('2.28.1') const minRequired = new GitVersion('2.18') if (version.checkMinimum(minRequired)) { console.log(`Git ${version.toString()} meets minimum requirement`) } ``` -------------------------------- ### Checkout Repository Usage Example Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-source-provider.md Example of how to use the gitSourceProvider to checkout a repository. Ensure necessary inputs are retrieved and handle potential errors during the checkout process. ```typescript import * as inputHelper from './input-helper.js' import * as gitSourceProvider from './git-source-provider.js' import * as core from '@actions/core' async function run(): Promise { try { const settings = await inputHelper.getInputs() await gitSourceProvider.getSource(settings) core.info('Repository checked out successfully') core.setOutput('ref', settings.ref) } catch (error) { core.setFailed(`Checkout failed: ${error.message}`) } } ``` -------------------------------- ### Usage Example for tryGetRepositoryObjectFormat Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/github-api-helper.md Demonstrates how to use the `tryGetRepositoryObjectFormat` function to get a repository's object format. Handles both success and failure cases. ```typescript import * as githubApiHelper from './github-api-helper.js' async function getFormat(): Promise { const result = await githubApiHelper.tryGetRepositoryObjectFormat( token, 'actions', 'checkout', 'https://github.com', 'abc123...' ) if (result.succeeded) { console.log(`Object format: ${result.format}`) } else { console.log('Could not determine object format') } } ``` -------------------------------- ### lfsInstall Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Installs the Git LFS hooks for the current repository. ```APIDOC ## lfsInstall ### Description Install Git LFS hooks. ### Method `lfsInstall(): Promise` ### Underlying Command `git lfs install` ``` -------------------------------- ### Side-by-Side Checkout Example Source: https://github.com/actions/checkout/blob/main/adrs/0153-checkout-v2.md Demonstrates checking out multiple repositories into different paths within the workspace for a side-by-side layout. ```yaml # Self repo - Checkout to $GITHUB_WORKSPACE/foo - uses: checkout@v2 with: path: foo # Other repo - Checkout to $GITHUB_WORKSPACE/myscripts - uses: checkout@v2 with: repository: myorg/myscripts path: myscripts ``` -------------------------------- ### Get Installed Git Version Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Retrieves the version of the installed Git executable. Returns a GitVersion object containing version details. ```typescript version(): Promise ``` -------------------------------- ### Git Version Detection Example Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-version.md Demonstrates how to obtain the Git version using `createCommandManager` and check if it meets the minimum requirements. ```typescript // In git-command-manager.ts const git = await createCommandManager(...) const version = await git.version() // Returns GitVersion if (version.checkMinimum(MinimumGitVersion)) { console.log('Git is sufficient') } ``` -------------------------------- ### Checkout Action Usage Example Source: https://github.com/actions/checkout/blob/main/_autodocs/configuration.md Demonstrates how to use the actions/checkout action in a GitHub Actions workflow and access its outputs. ```yaml - uses: actions/checkout@v7 id: checkout - run: echo "Checked out ${{ steps.checkout.outputs.commit }}" ``` -------------------------------- ### Checkout for GitHub Enterprise Source: https://github.com/actions/checkout/blob/main/_autodocs/INDEX.md This example demonstrates how to configure actions/checkout to work with a GitHub Enterprise instance. You need to provide the server URL and a token. ```yaml - uses: actions/checkout@v7 with: github-server-url: https://ghes.example.com token: ${{ secrets.GHES_TOKEN }} ``` -------------------------------- ### version Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Retrieves the installed Git version information. ```APIDOC ## version ### Description Get the installed Git version. ### Method `version(): Promise` ### Returns - GitVersion - A `GitVersion` object containing version details. ### Underlying Command `git --version` ``` -------------------------------- ### Install Git LFS Hooks Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Installs the necessary Git LFS hooks to manage large files during Git operations. This should be run once after setting up Git LFS. ```typescript lfsInstall(): Promise ``` -------------------------------- ### Checkout Branch Example Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Demonstrates how to use the Git command manager to checkout a specific branch. This includes initializing the manager, verifying the Git version against a minimum requirement, fetching the branch, and then checking it out. ```typescript import * as gitCommandManager from './git-command-manager.js' import {MinimumGitVersion} from './git-command-manager.js' async function checkoutBranch(dir: string, branch: string): Promise { const git = await gitCommandManager.createCommandManager(dir, false, false) const version = await git.version() if (!version.checkMinimum(MinimumGitVersion)) { throw new Error(`Git ${MinimumGitVersion} or higher required`) } await git.fetch([`+refs/heads/${branch}:refs/remotes/origin/${branch}`], {}) await git.checkout(branch, `refs/remotes/origin/${branch}`) } ``` -------------------------------- ### RetryHelper.execute Example: Successful on First Attempt Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/retry-helper.md Demonstrates a successful execution of the action on the very first try. The helper returns immediately without any retries. ```typescript const helper = new RetryHelper() const result = await helper.execute(async () => { return 'success' }) // Returns immediately without retry ``` -------------------------------- ### GHES API URL Example Source: https://github.com/actions/checkout/blob/main/_autodocs/configuration.md Illustrates the API URL format for GitHub Enterprise Server instances compared to GitHub.com. ```text API URL: https://api.github.com API URL: https://ghes.example.com/api/v3 ``` -------------------------------- ### Example: Nested Layout with Multiple Checkouts Source: https://github.com/actions/checkout/blob/main/adrs/0153-checkout-v2.md Demonstrates checking out two repositories with a nested layout, where the self repository is checked out to the default path within GITHUB_WORKSPACE. ```yaml # Self repo - Checkout to $GITHUB_WORKSPACE - uses: checkout@v2 ``` -------------------------------- ### Checkout with SSH and Custom Depth Source: https://github.com/actions/checkout/blob/main/_autodocs/INDEX.md This example shows how to use SSH for checkout and specify a custom fetch depth. Ensure your SSH key is stored as a secret. ```yaml - uses: actions/checkout@v7 with: ssh-key: ${{ secrets.SSH_KEY }} fetch-depth: 50 ``` -------------------------------- ### Usage Example for getDefaultBranch Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/github-api-helper.md Demonstrates how to import and use the `getDefaultBranch` function in a TypeScript project. It shows how to pass authentication token, owner, repository name, and optionally the base API URL. ```typescript import * as githubApiHelper from './github-api-helper.js' async function getDefault(): Promise { const branch = await githubApiHelper.getDefaultBranch( token, 'actions', 'checkout', 'https://github.com' ) console.log(`Default branch: ${branch}`) // refs/heads/main } ``` -------------------------------- ### Version Handling: GitVersion class and checkMinimum() Source: https://github.com/actions/checkout/blob/main/_autodocs/SUMMARY.txt Provides a GitVersion class for handling semantic versioning of Git and a utility function to check if the installed Git version meets a minimum requirement. ```APIDOC ## GitVersion Class ### Description Represents a Git version and provides methods for comparison and validation based on semantic versioning. ### Constructor ```typescript constructor(version: string) ``` ### Methods - `checkMinimum(minimumVersion: string): boolean`: Checks if this version is greater than or equal to the specified minimum version. - `isValid(): boolean`: Checks if the version string is valid. - `toString(): string`: Returns the version string. ``` ```APIDOC ## checkMinimum() (within GitVersion) ### Description Compares the current `GitVersion` instance against a specified minimum version string. ### Function Signature ```typescript checkMinimum(minimumVersion: string): boolean ``` ### Parameters - **minimumVersion** (`string`): The minimum version string to compare against. ### Returns - `boolean`: True if the current version is greater than or equal to the minimum version, false otherwise. ``` -------------------------------- ### Unsafe Fork PR Checkout (Not Recommended) Source: https://github.com/actions/checkout/blob/main/_autodocs/INDEX.md This example shows how to allow checkout of fork pull requests, which is not recommended due to security risks. Review the risks carefully before enabling. ```yaml - uses: actions/checkout@v7 with: allow-unsafe-pr-checkout: true # After reviewing risks! ``` -------------------------------- ### Push Commit with Built-in Token Source: https://github.com/actions/checkout/blob/main/README.md This example demonstrates how to push a commit using the built-in GitHub Actions token. It configures Git user information and adds a generated file before committing and pushing. ```yaml on: push jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - run: | date > generated.txt # Note: the following account information will not work on GHES git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git add . git commit -m "generated" git push ``` -------------------------------- ### RetryHelper.execute Example: All Attempts Fail Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/retry-helper.md Shows a case where the action fails on all allowed attempts. The helper will throw the error from the final attempt without suppression. ```typescript const helper = new RetryHelper() try { await helper.execute(async () => { throw new Error('Always fails') }) } catch (err) { console.error(err.message) // "Always fails" } // Attempts 3 times with waits, then throws from final attempt ``` -------------------------------- ### Get Repository Path Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/state-helper.md Retrieves the filesystem path to the repository, set by the PRE action. This is only populated in the POST action and is empty during the main action. ```typescript export const RepositoryPath = core.getState('repositoryPath') ``` ```typescript const path = stateHelper.RepositoryPath if (path) { console.log(`Cleaning up repository at ${path}`) } ``` -------------------------------- ### IGitAuthHelper Source: https://github.com/actions/checkout/blob/main/_autodocs/types.md Interface for managing Git authentication configurations, including SSH and HTTP token setup, submodule authentication, and temporary global configuration management. ```APIDOC ## IGitAuthHelper ### Description Interface for managing Git authentication configurations, including SSH and HTTP token setup, submodule authentication, and temporary global configuration management. ### Methods - **configureAuth()**: Promise Configure SSH and HTTP token auth. - **configureGlobalAuth()**: Promise Configure auth in temporary global config (for submodules). - **configureSubmoduleAuth()**: Promise Configure auth for all submodules. - **configureTempGlobalConfig()**: Promise Create temp global config in RUNNER_TEMP; returns path. - **removeAuth()**: Promise Remove all authentication. - **removeGlobalConfig()**: Promise Remove temp global config and restore HOME. ``` -------------------------------- ### Check Minimum Git Version Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-version.md Compare the current Git version against a required minimum version. Returns true if the installed version is greater than or equal to the minimum. ```typescript const installed = new GitVersion('2.28.1') const required = new GitVersion('2.18') installed.checkMinimum(required) // true (2.28 >= 2.18) const old = new GitVersion('2.10') old.checkMinimum(required) // false (2.10 < 2.18) const equal = new GitVersion('2.18') equal.checkMinimum(required) // true (2.18 >= 2.18) const patch = new GitVersion('2.18.1') const minPatch = new GitVersion('2.18.2') patch.checkMinimum(minPatch) // false (2.18.1 < 2.18.2) ``` -------------------------------- ### RetryHelper.execute Example: Succeeds on Third Attempt Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/retry-helper.md Illustrates a scenario where the action fails twice but succeeds on the third attempt. The helper waits between the first and second, and second and third attempts. ```typescript let attempt = 0 const result = await helper.execute(async () => { attempt++ if (attempt < 3) throw new Error('Transient failure') return 'success' }) // After attempt 1 fails: waits 10-20s, retries // After attempt 2 fails: waits 10-20s, retries // Attempt 3 succeeds ``` -------------------------------- ### Create Git Command Manager Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Factory function to create a Git command manager instance. It initializes the manager with the specified working directory, LFS mode, and sparse checkout setting. It also detects the Git installation and version. ```typescript export async function createCommandManager( workingDirectory: string, lfs: boolean, doSparseCheckout: boolean ): Promise ``` -------------------------------- ### Build the Project Source: https://github.com/actions/checkout/blob/main/CONTRIBUTING.md This command builds the project, creating a single JavaScript file for the action's entrypoint. ```bash npm run build ``` -------------------------------- ### init Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Initializes a bare Git repository. ```APIDOC ## init ### Description Initialize a bare repository: `git init`. If `objectFormat` is `'sha256'`, uses `git init --object-format=sha256`. ### Method ```typescript init(objectFormat?: string): Promise ``` ### Parameters - **objectFormat** (string) - Optional - The object format to use (e.g., `'sha256'`). ``` -------------------------------- ### Get Checkout Information for Various Git References Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/ref-helper.md Converts user-provided references (branches, tags, commits, PRs) into checkout-ready information. Use this function when you need to determine the exact Git ref and starting point for a checkout operation. ```typescript import * as gitCommandManager from './git-command-manager.js' import * as refHelper from './ref-helper.js' async function getCheckoutDetails(): Promise { const git = await gitCommandManager.createCommandManager('.', false, false) // For a branch let info = await refHelper.getCheckoutInfo(git, 'main', '') // → { ref: 'main', startPoint: 'refs/remotes/origin/main' } // For a tag info = await refHelper.getCheckoutInfo(git, 'refs/tags/v1.0', '') // → { ref: 'refs/tags/v1.0', startPoint: '' } // For a commit SHA info = await refHelper.getCheckoutInfo(git, '', 'abc123...') // → { ref: 'abc123...', startPoint: '' } // For a PR info = await refHelper.getCheckoutInfo(git, 'refs/pull/42/head', '') // → { ref: 'refs/remotes/pull/42/head', startPoint: '' } } ``` -------------------------------- ### createCommandManager Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Factory function to create a Git command manager instance. It handles Git installation and version detection. ```APIDOC ## createCommandManager ### Description Creates a Git command manager. Detects Git installation and version. ### Signature ```typescript export async function createCommandManager( workingDirectory: string, lfs: boolean, doSparseCheckout: boolean ): Promise ``` ### Parameters #### Path Parameters * **workingDirectory** (string) - Required - Directory to run git commands in * **lfs** (boolean) - Required - Whether to enable Git LFS mode * **doSparseCheckout** (boolean) - Required - Whether sparse checkout will be used ### Return Type `Promise` - A command manager instance. ### Throws * `Git not found in PATH` - Git executable not located * `Unexpected git version` - Git version doesn't match semantic versioning pattern ### Usage Example ```typescript import * as gitCommandManager from './git-command-manager.js' import {MinimumGitVersion} from './git-command-manager.js' async function checkoutBranch(dir: string, branch: string): Promise { const git = await gitCommandManager.createCommandManager(dir, false, false) const version = await git.version() if (!version.checkMinimum(MinimumGitVersion)) { throw new Error(`Git ${MinimumGitVersion} or higher required`) } await git.fetch([`+refs/heads/${branch}:refs/remotes/origin/${branch}`], {}) await git.checkout(branch, `refs/remotes/origin/${branch}`) } ``` ``` -------------------------------- ### URL & Server Handling: getFetchUrl(), getServerUrl(), getServerApiUrl(), isGhes() Source: https://github.com/actions/checkout/blob/main/_autodocs/SUMMARY.txt Utility functions for constructing Git fetch URLs, resolving server URLs, API endpoints, and detecting GitHub Enterprise Server instances. ```APIDOC ## getFetchUrl() ### Description Constructs the appropriate Git fetch URL based on repository and authentication settings. ### Function Signature ```typescript getFetchUrl(repository: string, authHelper: IGitAuthHelper): string ``` ### Parameters - **repository** (`string`): The repository identifier (e.g., owner/repo). - **authHelper** (`IGitAuthHelper`): The authentication helper instance. ### Returns - `string`: The constructed Git fetch URL. ``` ```APIDOC ## getServerUrl() ### Description Resolves the base URL for the GitHub server instance. ### Function Signature ```typescript getServerUrl(gitHost: string): string ``` ### Parameters - **gitHost** (`string`): The Git host name (e.g., 'github.com' or a GHE instance). ### Returns - `string`: The base server URL. ``` ```APIDOC ## getServerApiUrl() ### Description Constructs the base URL for the GitHub API endpoint. ### Function Signature ```typescript getServerApiUrl(gitHost: string): string ``` ### Parameters - **gitHost** (`string`): The Git host name. ### Returns - `string`: The base API URL. ``` ```APIDOC ## isGhes() ### Description Determines if the provided Git host is a GitHub Enterprise Server instance. ### Function Signature ```typescript isGhes(gitHost: string): boolean ``` ### Parameters - **gitHost** (`string`): The Git host name. ### Returns - `boolean`: True if the host is GHE, false otherwise. ``` -------------------------------- ### Run Tests Source: https://github.com/actions/checkout/blob/main/CONTRIBUTING.md Execute this command to run the project's tests. ```bash npm run test ``` -------------------------------- ### Input and Configuration Source: https://github.com/actions/checkout/blob/main/_autodocs/INDEX.md Functions for parsing action inputs and configuring the environment. ```APIDOC ## getInputs() ### Description Parse all 19 action inputs. ### Module input-helper ``` -------------------------------- ### ICheckoutInfo Interface Source: https://github.com/actions/checkout/blob/main/_autodocs/types.md Defines the structure for information required to perform a Git checkout operation, including the reference and starting point. ```APIDOC ## ICheckoutInfo ### Description Represents the information needed to perform a Git checkout. ### Fields - **ref** (string) - Required - The Git ref (branch, tag, commit SHA) to checkout. - **startPoint** (string) - Required - The starting point for the checkout, typically used for branches. ``` -------------------------------- ### Get Git Working Directory Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Returns the current working directory path for which the Git command manager was initialized. This is a synchronous operation. ```typescript getWorkingDirectory(): string ``` -------------------------------- ### Instantiate GitVersion Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-version.md Create a new GitVersion instance by providing a version string. Handles various formats and invalid inputs by setting version components to NaN. ```typescript new GitVersion('2.18') // major=2, minor=18, patch=NaN new GitVersion('2.28.1') // major=2, minor=28, patch=1 new GitVersion('1.2.3.4') // NaN, NaN, NaN (too many components) new GitVersion('abc') // NaN, NaN, NaN (non-numeric) new GitVersion() // NaN, NaN, NaN (no input) ``` -------------------------------- ### Get Submodule Config Paths Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Retrieves the file paths to the `.git/config` files for all submodules. Can recursively find paths in nested submodules. ```typescript getSubmoduleConfigPaths(recursive: boolean): Promise ``` -------------------------------- ### createAuthHelper() Source: https://github.com/actions/checkout/blob/main/_autodocs/README.md Creates an authentication configuration helper. ```APIDOC ## createAuthHelper() ### Description Creates an authentication configuration helper. ### Function Signature `createAuthHelper()` ### Returns An instance of `IGitAuthHelper`. ``` -------------------------------- ### Define ICheckoutInfo Interface Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/ref-helper.md Defines the structure for information required to perform a Git checkout operation, including the target ref and its starting point. ```typescript export interface ICheckoutInfo { ref: string // Ref to checkout (branch name, tag, or commit) startPoint: string // Ref to base checkout from (for branch setup) } ``` -------------------------------- ### Get Fetch URL from Repository Config Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Retrieves the fetch URL configured for the 'origin' remote of the current repository. Essential for understanding where to push/pull. ```typescript tryGetFetchUrl(): Promise ``` -------------------------------- ### Get Most Recent Commit Log Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Retrieves the log of the most recent commit. Can return the full commit message or a formatted string, such as the commit SHA. ```typescript log1(format?: string): Promise ``` ```typescript const message = await git.log1() // Full message ``` ```typescript const sha = await git.log1('--format=%H') // Just the SHA ``` -------------------------------- ### Format Code Source: https://github.com/actions/checkout/blob/main/CONTRIBUTING.md Run this command to ensure your code adheres to the project's formatting standards. ```bash npm run format ``` -------------------------------- ### Usage Example: Validate Checkout Safety Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/unsafe-pr-checkout-helper.md This TypeScript code demonstrates how to use the `assertSafePrCheckout` function from the `unsafe-pr-checkout-helper` module to validate if a checkout operation is safe. ```typescript import * as unsafePrCheckoutHelper from './unsafe-pr-checkout-helper.js' import * as inputHelper from './input-helper.js' async function validateCheckout(): Promise { const settings = await inputHelper.getInputs() unsafePrCheckoutHelper.assertSafePrCheckout({ qualifiedRepository: `${settings.repositoryOwner}/${settings.repositoryName}`, ref: settings.ref, commit: settings.commit, allowUnsafePrCheckout: settings.allowUnsafePrCheckout }) console.log('Checkout is safe to perform') } ``` -------------------------------- ### Authentication: IGitAuthHelper and createAuthHelper() Source: https://github.com/actions/checkout/blob/main/_autodocs/SUMMARY.txt Interface for Git authentication helper methods and a factory function to create an instance for setting up SSH and token authentication. ```APIDOC ## IGitAuthHelper Interface ### Description Interface for methods related to Git authentication setup. ### Methods (6 methods) - `setupSsh()`: Configures SSH authentication. - `setupToken(token: string, gitHost: string): Promise`: Sets up token-based authentication for a given Git host. - `configureGitCredentials(username: string, password: string, gitHost: string): Promise`: Configures Git with username and password. - `configureSshKey(sshKey: string, gitHost: string): Promise`: Configures an SSH key for a given Git host. - `configurePat(pat: string, gitHost: string): Promise`: Configures a Personal Access Token (PAT). - `configureAppKey(appId: string, privateKey: string, gitHost: string): Promise`: Configures an App Key for authentication. ``` ```APIDOC ## createAuthHelper() ### Description Factory function to create an instance of `IGitAuthHelper`. ### Function Signature ```typescript createAuthHelper(options: AuthHelperOptions): IGitAuthHelper ``` ### Parameters - **options** (`AuthHelperOptions`): Options for creating the auth helper, potentially including paths and configurations. ### Returns - `IGitAuthHelper`: An initialized Git authentication helper instance. ``` -------------------------------- ### Example Attack: Exfiltrate Secrets Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/unsafe-pr-checkout-helper.md An attacker's fork can modify workflow files to exfiltrate secrets by echoing them into a file and sending them to an external server. ```yaml # Attacker's fork modifies workflow - name: Exfiltrate secrets run: | echo "BASE_REPO_SECRETS=${{ secrets.PRIVATE_KEY }}" >> /tmp/exfil # Send to attacker's server ``` -------------------------------- ### Get Ref Spec for Specific Branch Commit Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/ref-helper.md Generates a refspec to fetch a specific branch commit. This is useful for pinpointing a particular commit on a branch. ```typescript import * as refHelper from './ref-helper.js' // Fetch a specific branch commit let specs = refHelper.getRefSpec('refs/heads/main', 'abc123') ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Initializes a new Git repository. Supports specifying a custom object format, such as 'sha256', for enhanced security or compatibility. ```typescript init(objectFormat?: string): Promise ``` -------------------------------- ### Get Default Git Branch Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Retrieves the default branch name for a given repository URL by querying the remote's symbolic ref for HEAD. ```typescript getDefaultBranch(repositoryUrl: string): Promise ``` -------------------------------- ### tryGetConfigKeys Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Lists all Git configuration keys that match a given pattern, optionally in the global configuration or a specific file. ```APIDOC ## tryGetConfigKeys ### Description List all config keys matching a pattern. ### Method `tryGetConfigKeys(pattern: string, globalConfig?: boolean, configFile?: string): Promise` ### Parameters #### Path Parameters - **pattern** (string) - Required - The pattern to match config keys against. - **globalConfig** (boolean) - Optional - Whether to search in the global Git configuration. - **configFile** (string) - Optional - The path to the configuration file to search within. ### Returns - string[] - An array of config keys matching the pattern. ``` -------------------------------- ### pull_request_target Event Payload Structure Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/unsafe-pr-checkout-helper.md Example JSON structure for a `pull_request_target` event payload. This structure is assumed by the `pushIfSha` function when processing pull request information. ```json { "repository": {"id": 12345}, "pull_request": { "head": { "repo": {"id": 67890, "full_name": "fork-user/fork"}, "sha": "abc123..." }, "merge_commit_sha": "def456..." } } ``` -------------------------------- ### Configure Git Authentication Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-auth-helper.md Sets up authentication for Git operations using the git-auth-helper. This involves creating a command manager, initializing the auth helper, configuring authentication, and later removing it during cleanup. ```typescript import * as gitCommandManager from './git-command-manager.js' import * as gitAuthHelper from './git-auth-helper.js' import * as inputHelper from './input-helper.js' async function setupAuth(): Promise { const settings = await inputHelper.getInputs() const git = await gitCommandManager.createCommandManager( settings.repositoryPath, settings.lfs, !!settings.sparseCheckout.length ) const authHelper = gitAuthHelper.createAuthHelper(git, settings) // Configure authentication await authHelper.configureAuth() // Later: remove auth in cleanup await authHelper.removeAuth() await authHelper.removeGlobalConfig() } ``` -------------------------------- ### Fetch LFS Objects for a Ref Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Fetches Git Large File Storage (LFS) objects associated with a specific reference. Ensure Git LFS is installed and configured. ```typescript lfsFetch(ref: string): Promise ``` -------------------------------- ### getSource(settings) Source: https://github.com/actions/checkout/blob/main/_autodocs/README.md Executes the main checkout workflow using the provided settings. ```APIDOC ## getSource(settings) ### Description Executes the main checkout workflow with the given settings. ### Function Signature `getSource(settings: IGitSourceSettings)` ### Parameters #### Request Body - **settings** (IGitSourceSettings) - Required - Complete configuration for the checkout operation. ### Returns Information about the checkout operation. ``` -------------------------------- ### Get Git Config Values for a Key Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Retrieves all values associated with a specific Git configuration key, handling multi-valued configurations. Can specify global config search. ```typescript tryGetConfigValues( configKey: string, globalConfig?: boolean, configFile?: string ): Promise ``` -------------------------------- ### Basic Checkout Source: https://github.com/actions/checkout/blob/main/_autodocs/INDEX.md This is the most basic usage of the actions/checkout action. It checks out the repository at the default depth. ```yaml - uses: actions/checkout@v7 ``` -------------------------------- ### checkout Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Executes `git checkout`. Creates a new branch if `startPoint` is provided. ```APIDOC ## checkout ### Description Executes `git checkout`. If `startPoint` is provided, uses `git checkout -B `; otherwise `git checkout `. ### Method ```typescript checkout(ref: string, startPoint?: string): Promise ``` ### Parameters - **ref** (string) - Required - The reference (branch or commit) to checkout. - **startPoint** (string) - Optional - The starting point for a new branch. ``` -------------------------------- ### toString Method Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-version.md Converts the Git version back to its string representation. ```APIDOC ## Method: toString ```typescript toString(): string ``` ### Description Convert version back to string format. ### Return Type `string` - Version string (e.g., `'2.18'`, `'2.28.1'`) or empty if invalid. ### Format - Valid: `'${major}.${minor}'` or `'${major}.${minor}.${patch}'` - Invalid: `''` (empty string) ### Examples ```typescript new GitVersion('2.18').toString() // '2.18' new GitVersion('2.28.1').toString() // '2.28.1' new GitVersion('invalid').toString() // '' ``` ``` -------------------------------- ### Checkout Submodules with LFS and Full History Source: https://github.com/actions/checkout/blob/main/_autodocs/configuration.md Configures the actions/checkout action to check out all history, recursively fetch submodules, and enable Git LFS support. ```yaml - uses: actions/checkout@v7 with: submodules: recursive lfs: true fetch-depth: 0 ``` -------------------------------- ### Get Ref Spec for Branch Pattern Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/ref-helper.md Generates refspecs to fetch a pattern of branches and tags. This is useful for fetching multiple related branches or tags that match a naming convention. ```typescript // Fetch a branch pattern specs = refHelper.getRefSpec('feature', '') ``` -------------------------------- ### Fetch specific folders with sparse checkout Source: https://github.com/actions/checkout/blob/main/README.md Use this snippet to fetch only specified directories, such as .github and src. This helps reduce the amount of data downloaded. ```yaml - uses: actions/checkout@v7 with: sparse-checkout: | .github src ``` -------------------------------- ### File Structure of actions/checkout Source: https://github.com/actions/checkout/blob/main/_autodocs/00-START-HERE.md Overview of the directory and file structure for the actions/checkout project. ```tree /workspace/home/output/ ├── 00-START-HERE.md ← You are here ├── README.md ← Project overview ├── INDEX.md ← Navigation and reference ├── types.md ← All types and interfaces ├── configuration.md ← Configuration reference ├── SUMMARY.txt ← Generation summary └── api-reference/ ├── input-helper.md ← Input parsing ├── git-source-provider.md ← Main orchestration ├── git-command-manager.md ← Git operations (22 methods) ├── git-auth-helper.md ← SSH & token auth ├── ref-helper.md ← Ref resolution ├── url-helper.md ← GitHub URLs ├── github-api-helper.md ← REST API fallback ├── retry-helper.md ← Retry logic ├── state-helper.md ← State management ├── unsafe-pr-checkout-helper.md ← Security validation └── git-version.md ← Version handling ``` -------------------------------- ### Check Git Version and Requirements Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-version.md This function checks the installed Git version, validates it, and ensures it meets the minimum required version for project features. It throws an error if the version is invalid or insufficient. ```typescript import {GitVersion} from './git-version.js' import {MinimumGitVersion} from './git-command-manager.js' async function checkGitVersion(git: IGitCommandManager): Promise { const installed = await git.version() if (!installed.isValid()) { throw new Error('Could not determine Git version') } console.log(`Git version: ${installed.toString()}`) if (!installed.checkMinimum(MinimumGitVersion)) { throw new Error(`Git ${MinimumGitVersion} or higher required`) } console.log('Git version meets requirements') } ``` -------------------------------- ### Fetch from Git Origin with Options Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Fetches references from the origin remote with advanced options like partial clone filters, shallow fetches, and progress display. ```typescript fetch( refSpec: string[], options: { filter?: string fetchDepth?: number showProgress?: boolean } ): Promise ``` -------------------------------- ### List Git Config Keys Matching Pattern Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Lists all Git configuration keys that match a given pattern. Can specify whether to search global configuration. ```typescript tryGetConfigKeys( pattern: string, globalConfig?: boolean, configFile?: string ): Promise ``` -------------------------------- ### Checkout with SSH Authentication Source: https://github.com/actions/checkout/blob/main/_autodocs/configuration.md Sets up SSH key authentication for the actions/checkout action. The `ssh-known-hosts` parameter should match the Git host. ```yaml - uses: actions/checkout@v7 with: ssh-key: ${{ secrets.SSH_KEY }} ssh-known-hosts: github.com ``` -------------------------------- ### getSubmoduleConfigPaths Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Retrieves the paths to all submodule `.git/config` files. ```APIDOC ## getSubmoduleConfigPaths ### Description Get paths to all submodule `.git/config` files. ### Method ```typescript getSubmoduleConfigPaths(recursive: boolean): Promise ``` ### Parameters - **recursive** (boolean) - Required - If true, recurses into nested submodules. ``` -------------------------------- ### workflow_run Event Payload Structure (PR-triggered) Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/unsafe-pr-checkout-helper.md Example JSON structure for a `workflow_run` event payload when triggered by a pull request. This structure is also assumed by the `pushIfSha` function for relevant event types. ```json { "repository": {"id": 12345}, "workflow_run": { "event": "pull_request", "head_repository": {"id": 67890, "full_name": "fork-user/fork"}, "head_commit": {"id": "abc123..."}, "head_sha": "def456..." } } ``` -------------------------------- ### Get Default Branch API Call Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/github-api-helper.md This snippet shows the core API call to fetch repository data, from which the default branch is extracted. It's part of the `getDefaultBranch` function's implementation. ```typescript const response = await octokit.rest.repos.get({owner, repo}) const defaultBranch = response.data.default_branch ``` -------------------------------- ### Enable Git Sparse Checkout (Cone Mode) Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-command-manager.md Enables sparse checkout using cone mode patterns. This is efficient for including specific directories or files. ```typescript sparseCheckout(sparseCheckout: string[]): Promise ``` -------------------------------- ### createAuthHelper Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-auth-helper.md Factory function to create an authentication helper for a given Git command manager. It configures authentication using HTTP tokens or SSH keys based on provided settings. ```APIDOC ## createAuthHelper ### Description Creates an authentication helper for the given Git command manager. This helper can configure HTTP token-based authentication or SSH key-based authentication for Git operations. ### Signature ```typescript export function createAuthHelper( git: IGitCommandManager, settings?: IGitSourceSettings ): IGitAuthHelper ``` ### Parameters #### Path Parameters * **git** (IGitCommandManager) - Required - The Git command manager instance to configure authentication for. * **settings** (IGitSourceSettings) - Optional - Settings object containing authentication credentials and configuration. All fields within settings are treated as optional. ### Return Type `IGitAuthHelper` - An object that provides configuration for the Git manager, enabling secure authentication for Git operations. ### Implementation Details **HTTP Token Configuration** Configures Git to use an HTTP token for authentication. This involves setting the `http./.extraheader` configuration key with an `AUTHORIZATION` header. ```typescript const serverUrl = urlHelper.getServerUrl(settings.githubServerUrl) // Config key: http.${serverUrl.origin}/.extraheader // Value: AUTHORIZATION: basic ${base64('x-access-token:')} ``` The token is masked in logs using `core.setSecret()` for security. **SSH Configuration** Sets up SSH authentication by building the `GIT_SSH_COMMAND`. This includes specifying the SSH key path, setting appropriate file permissions (0600), configuring the SSH known hosts file, and enabling strict host key checking if configured. ```typescript // Builds SSH command with: // - SSH key path and permissions (0600) // - SSH known hosts file // - Strict host key checking if enabled // Sets GIT_SSH_COMMAND for git operations ``` **URL Remapping (HTTPS instead of SSH)** Configures Git to use HTTPS URLs instead of SSH URLs for repository access. This is achieved by setting the `url./.insteadOf` configuration key. ```typescript // Config key: url.${serverUrl.origin}/.insteadOf // Maps: git@${serverUrl.hostname}: → https://... // Also maps: org-${organizationId}@github.com: (for GHES) ``` **Credentials File Location** A temporary credentials file is created to store the authentication token or SSH configuration. This file is used by submodules to reference shared credentials. ```typescript // ${RUNNER_TEMP}/actions-user---.credentials // Contains same token/SSH config as global config // Used by submodules to reference shared credentials ``` ``` -------------------------------- ### Get SSH Key Path Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/state-helper.md Retrieves the filesystem path where the SSH private key was written. This is only populated in the POST action if an SSH key was configured and is used by auth cleanup to delete the key file. ```typescript export const SshKeyPath = core.getState('sshKeyPath') ``` -------------------------------- ### Main Orchestration: getSource() and cleanup() Source: https://github.com/actions/checkout/blob/main/_autodocs/SUMMARY.txt Core functions for managing the checkout process: getSource() initiates the checkout, and cleanup() performs necessary post-checkout tasks. ```APIDOC ## getSource() ### Description Initiates the process of checking out source code for a GitHub Actions workflow. ### Function Signature ```typescript getSource(settings: IGitSourceSettings): Promise ``` ### Parameters - **settings** (`IGitSourceSettings`): Configuration object for the checkout process. ### Returns - `Promise`: A promise that resolves when the source code has been successfully checked out. ``` ```APIDOC ## cleanup() ### Description Performs cleanup operations after the source code has been checked out. ### Function Signature ```typescript cleanup(): Promise ``` ### Returns - `Promise`: A promise that resolves when the cleanup process is complete. ``` -------------------------------- ### Get Ref Spec for Tag with All Tags Fetch Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/ref-helper.md Generates refspecs to fetch a specific tag while also including all other tags. This is useful when you need a particular tag and want to ensure your local tag repository is up-to-date. ```typescript // Fetch a tag with all tags specs = refHelper.getRefSpec('refs/tags/v1.0', '', true) ``` -------------------------------- ### Git Fetch Options Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/git-source-provider.md Defines the available options for fetching Git repositories. Use 'filter' for sparse checkouts and 'fetchDepth' to control history. 'showProgress' enables progress display. ```typescript const fetchOptions = { filter?: string // e.g., 'blob:none' for sparse checkout fetchDepth?: number // 0 = all history showProgress?: boolean } ``` -------------------------------- ### Get SSH Known Hosts Path Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/state-helper.md Retrieves the filesystem path where SSH known hosts were written. This is only populated in the POST action if SSH was configured and is used by auth cleanup to delete the known hosts file. ```typescript export const SshKnownHostsPath = core.getState('sshKnownHostsPath') ``` -------------------------------- ### Checkout HEAD^ Source: https://github.com/actions/checkout/blob/main/README.md Fetch a depth of 2 to access the parent commit (HEAD^) and then use git checkout to switch to it. ```yaml - uses: actions/checkout@v7 with: fetch-depth: 2 - run: git checkout HEAD^ ``` -------------------------------- ### Get GitHub Server URL Source: https://github.com/actions/checkout/blob/main/_autodocs/api-reference/url-helper.md Resolves the GitHub server URL. Use the 'url' parameter to override, or rely on the GITHUB_SERVER_URL environment variable. Defaults to 'https://github.com' if neither is provided. Access URL components like hostname and origin. ```typescript import * as urlHelper from './url-helper.js' // From parameter let url = urlHelper.getServerUrl('https://ghes.example.com') // → URL { origin: 'https://ghes.example.com', hostname: 'ghes.example.com', ... } // From environment (default) process.env.GITHUB_SERVER_URL = 'https://github.com' url = urlHelper.getServerUrl() // → URL { origin: 'https://github.com', hostname: 'github.com', ... } // Access components console.log(url.hostname) // 'github.com' console.log(url.origin) // 'https://github.com' console.log(url.pathname) // '/' ```