Compare commits

..

7 Commits

Author SHA1 Message Date
Tingluo Huang ee0669bd1c
Add new public key for known_hosts (#1237) (#1238)
* Add new public key for known_hosts (#1237)

* Add new public key for known_hosts

* Fix the build!

* fix build.

---------

Co-authored-by: Cameron Booth <cdb@github.com>
2 years ago
Cory Miller dc323e67f1
Add backports to v2 branch (#1040)
* Update licensed version
* Backport for submodule command wrapping
* Update NPM packages
* Update dist/index.js
* Rebuild using Node 12
* Rebuild after a more aggressive cleanup of local files
* Backport change to replace datadog/squid with ubuntu/squid
2 years ago
Francesco Renzi e2f20e631a
Update CHANGELOG.md 2 years ago
Francesco Renzi b2eb13baee
Update @actions/core to 1.10.0 (#962)
* Update @actions/core to 1.10.0

* Backport state-helper updates
2 years ago
Tingluo Huang 7884fcad6b
Prepare changelog for v2.4.2. (#778) 3 years ago
Tingluo Huang f67ee5d622
Add set-safe-directory input to allow customers to take control. (#770) (#776)
* Add set-safe-directory input to allow customers to take control.
3 years ago
Thomas Boop f25a3a9f25
Safe Directory v2 update (#764)
* set safe directory when running checkout
3 years ago

@ -22,12 +22,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v2
- name: Set Node.js 16.x - name: Set Node.js 12.x
uses: actions/setup-node@v1 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 12.x
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci

@ -39,10 +39,10 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v2
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v2 uses: github/codeql-action/init@v1
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file. # If you wish to specify custom queries, you can do so here or in a config file.
@ -55,4 +55,4 @@ jobs:
- run: rm -rf dist # We want code scanning to analyze lib instead (individual .js files) - run: rm -rf dist # We want code scanning to analyze lib instead (individual .js files)
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2 uses: github/codeql-action/analyze@v1

@ -9,6 +9,6 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: Check licenses name: Check licenses
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v2
- run: npm ci - run: npm ci
- run: npm run licensed-check - run: npm run licensed-check

@ -13,8 +13,8 @@ jobs:
steps: steps:
- uses: actions/setup-node@v1 - uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 12.x
- uses: actions/checkout@v3 - uses: actions/checkout@v2
- run: npm ci - run: npm ci
- run: npm run build - run: npm run build
- run: npm run format-check - run: npm run format-check
@ -32,7 +32,7 @@ jobs:
steps: steps:
# Clone this repo # Clone this repo
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
# Basic checkout # Basic checkout
- name: Checkout basic - name: Checkout basic
@ -150,7 +150,7 @@ jobs:
steps: steps:
# Clone this repo # Clone this repo
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
# Basic checkout using git # Basic checkout using git
- name: Checkout basic - name: Checkout basic
@ -182,7 +182,7 @@ jobs:
steps: steps:
# Clone this repo # Clone this repo
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
# Basic checkout using git # Basic checkout using git
- name: Checkout basic - name: Checkout basic

@ -1,31 +0,0 @@
name: Update Main Version
run-name: Move ${{ github.event.inputs.major_version }} to ${{ github.event.inputs.target }}
on:
workflow_dispatch:
inputs:
target:
description: The tag or reference to use
required: true
major_version:
type: choice
description: The major version to update
options:
- v3
- v2
jobs:
tag:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Git config
run: |
git config user.name github-actions
git config user.email github-actions@github.com
- name: Tag new target
run: git tag -f ${{ github.event.inputs.major_version }} ${{ github.event.inputs.target }}
- name: Push new tag
run: git push origin ${{ github.event.inputs.major_version }} --force

3
.gitignore vendored

@ -1,5 +1,4 @@
__test__/_temp __test__/_temp
_temp/ _temp/
lib/ lib/
node_modules/ node_modules/
.vscode/

@ -1,6 +1,6 @@
--- ---
name: "@actions/io" name: "@actions/io"
version: 1.1.3 version: 1.1.2
type: npm type: npm
summary: Actions io lib summary: Actions io lib
homepage: https://github.com/actions/toolkit/tree/main/packages/io homepage: https://github.com/actions/toolkit/tree/main/packages/io

@ -3,7 +3,7 @@ name: uuid
version: 3.3.3 version: 3.3.3
type: npm type: npm
summary: RFC4122 (v1, v4, and v5) UUIDs summary: RFC4122 (v1, v4, and v5) UUIDs
homepage: https://github.com/kelektiv/node-uuid#readme homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE.md - sources: LICENSE.md

@ -3,7 +3,7 @@ name: uuid
version: 8.3.2 version: 8.3.2
type: npm type: npm
summary: RFC4122 (v1, v4, and v5) UUIDs summary: RFC4122 (v1, v4, and v5) UUIDs
homepage: https://github.com/uuidjs/uuid#readme homepage:
license: mit license: mit
licenses: licenses:
- sources: LICENSE.md - sources: LICENSE.md

@ -1,42 +1,19 @@
# Changelog # Changelog
## v3.4.0 ## v2.5.0
- [Upgrade codeql actions to v2](https://github.com/actions/checkout/pull/1209) - [Bump @actions/core to v1.10.0](https://github.com/actions/checkout/pull/962)
- [Upgrade dependencies](https://github.com/actions/checkout/pull/1210)
- [Upgrade @actions/io](https://github.com/actions/checkout/pull/1225)
## v3.3.0 ## v2.4.2
- [Implement branch list using callbacks from exec function](https://github.com/actions/checkout/pull/1045) - [Add input `set-safe-directory`](https://github.com/actions/checkout/pull/776)
- [Add in explicit reference to private checkout options](https://github.com/actions/checkout/pull/1050)
- [Fix comment typos (that got added in #770)](https://github.com/actions/checkout/pull/1057)
## v3.2.0 ## v2.4.1
- [Add GitHub Action to perform release](https://github.com/actions/checkout/pull/942) - [Set the safe directory option on git to prevent git commands failing when running in containers](https://github.com/actions/checkout/pull/762)
- [Fix status badge](https://github.com/actions/checkout/pull/967)
- [Replace datadog/squid with ubuntu/squid Docker image](https://github.com/actions/checkout/pull/1002)
- [Wrap pipeline commands for submoduleForeach in quotes](https://github.com/actions/checkout/pull/964)
- [Update @actions/io to 1.1.2](https://github.com/actions/checkout/pull/1029)
- [Upgrading version to 3.2.0](https://github.com/actions/checkout/pull/1039)
## v3.1.0
- [Use @actions/core `saveState` and `getState`](https://github.com/actions/checkout/pull/939)
- [Add `github-server-url` input](https://github.com/actions/checkout/pull/922)
## v3.0.2
- [Add input `set-safe-directory`](https://github.com/actions/checkout/pull/770)
## v3.0.1
- [Fixed an issue where checkout failed to run in container jobs due to the new git setting `safe.directory`](https://github.com/actions/checkout/pull/762)
- [Bumped various npm package versions](https://github.com/actions/checkout/pull/744)
## v3.0.0
- [Update to node 16](https://github.com/actions/checkout/pull/689)
## v2.3.1 ## v2.3.1
- [Fix default branch resolution for .wiki and when using SSH](https://github.com/actions/checkout/pull/284) - [Fix default branch resolution for .wiki and when using SSH](https://github.com/actions/checkout/pull/284)
## v2.3.0 ## v2.3.0
- [Fallback to the default branch](https://github.com/actions/checkout/pull/278) - [Fallback to the default branch](https://github.com/actions/checkout/pull/278)

@ -1,28 +0,0 @@
# Contributing
## Submitting a pull request
1. Fork and clone the repository
1. Configure and install the dependencies: `npm install`
1. Create a new branch: `git checkout -b my-branch-name`
1. Make your change, add tests, and make sure the tests still pass: `npm run test`
1. Make sure your code is correctly formatted: `npm run format`
1. Update `dist/index.js` using `npm run build`. This creates a single javascript file that is used as an entrypoint for the action
1. Push to your fork and submit a pull request
1. Pat yourself on the back and wait for your pull request to be reviewed and merged
Here are a few things you can do that will increase the likelihood of your pull request being accepted:
- Write tests.
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
## Resources
- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
- [Using Pull Requests](https://help.github.com/articles/about-pull-requests/)
- [GitHub Help](https://help.github.com)
- [Writing good commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
Thanks! :heart: :heart: :heart:
GitHub Actions Team :octocat:

@ -1,6 +1,8 @@
[![Build and Test](https://github.com/actions/checkout/actions/workflows/test.yml/badge.svg)](https://github.com/actions/checkout/actions/workflows/test.yml) <p align="center">
<a href="https://github.com/actions/checkout"><img alt="GitHub Actions status" src="https://github.com/actions/checkout/workflows/test-local/badge.svg"></a>
</p>
# Checkout V3 # Checkout V2
This action checks-out your repository under `$GITHUB_WORKSPACE`, so your workflow can access it. This action checks-out your repository under `$GITHUB_WORKSPACE`, so your workflow can access it.
@ -12,14 +14,27 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl
# What's new # What's new
- Updated to the node16 runtime by default - Improved performance
- This requires a minimum [Actions Runner](https://github.com/actions/runner/releases/tag/v2.285.0) version of v2.285.0 to run, which is by default available in GHES 3.4 or later. - Fetches only a single commit by default
- Script authenticated git commands
- Auth token persisted in the local git config
- Supports SSH
- Creates a local branch
- No longer detached HEAD when checking out a branch
- Improved layout
- The input `path` is always relative to $GITHUB_WORKSPACE
- Aligns better with container actions, where $GITHUB_WORKSPACE gets mapped in
- Fallback to REST API download
- When Git 2.18 or higher is not in the PATH, the REST API will be used to download the files
- When using a job container, the container's PATH is used
Refer [here](https://github.com/actions/checkout/blob/v1/README.md) for previous versions.
# Usage # Usage
<!-- start usage --> <!-- start usage -->
```yaml ```yaml
- uses: actions/checkout@v3 - uses: actions/checkout@v2
with: with:
# Repository name with owner. For example, actions/checkout # Repository name with owner. For example, actions/checkout
# Default: ${{ github.repository }} # Default: ${{ github.repository }}
@ -95,12 +110,6 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl
# config --global --add safe.directory <path>` # config --global --add safe.directory <path>`
# Default: true # Default: true
set-safe-directory: '' set-safe-directory: ''
# The base URL for the GitHub instance that you are trying to clone from, will use
# environment defaults to fetch from the same instance that the workflow is
# running from unless specified. Example URLs are https://github.com or
# https://my-ghes-server.example.com
github-server-url: ''
``` ```
<!-- end usage --> <!-- end usage -->
@ -119,7 +128,7 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl
## Fetch all history for all tags and branches ## Fetch all history for all tags and branches
```yaml ```yaml
- uses: actions/checkout@v3 - uses: actions/checkout@v2
with: with:
fetch-depth: 0 fetch-depth: 0
``` ```
@ -127,7 +136,7 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl
## Checkout a different branch ## Checkout a different branch
```yaml ```yaml
- uses: actions/checkout@v3 - uses: actions/checkout@v2
with: with:
ref: my-branch ref: my-branch
``` ```
@ -135,7 +144,7 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl
## Checkout HEAD^ ## Checkout HEAD^
```yaml ```yaml
- uses: actions/checkout@v3 - uses: actions/checkout@v2
with: with:
fetch-depth: 2 fetch-depth: 2
- run: git checkout HEAD^ - run: git checkout HEAD^
@ -145,42 +154,40 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl
```yaml ```yaml
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
with: with:
path: main path: main
- name: Checkout tools repo - name: Checkout tools repo
uses: actions/checkout@v3 uses: actions/checkout@v2
with: with:
repository: my-org/my-tools repository: my-org/my-tools
path: my-tools path: my-tools
``` ```
> - If your secondary repository is private you will need to add the option noted in [Checkout multiple repos (private)](#Checkout-multiple-repos-private)
## Checkout multiple repos (nested) ## Checkout multiple repos (nested)
```yaml ```yaml
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
- name: Checkout tools repo - name: Checkout tools repo
uses: actions/checkout@v3 uses: actions/checkout@v2
with: with:
repository: my-org/my-tools repository: my-org/my-tools
path: my-tools path: my-tools
``` ```
> - If your secondary repository is private you will need to add the option noted in [Checkout multiple repos (private)](#Checkout-multiple-repos-private)
## Checkout multiple repos (private) ## Checkout multiple repos (private)
```yaml ```yaml
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
with: with:
path: main path: main
- name: Checkout private tools - name: Checkout private tools
uses: actions/checkout@v3 uses: actions/checkout@v2
with: with:
repository: my-org/my-private-tools repository: my-org/my-private-tools
token: ${{ secrets.GH_PAT }} # `GH_PAT` is a secret that contains your PAT token: ${{ secrets.GH_PAT }} # `GH_PAT` is a secret that contains your PAT
@ -193,7 +200,7 @@ When Git 2.18 or higher is not in your PATH, falls back to the REST API to downl
## Checkout pull request HEAD commit instead of merge commit ## Checkout pull request HEAD commit instead of merge commit
```yaml ```yaml
- uses: actions/checkout@v3 - uses: actions/checkout@v2
with: with:
ref: ${{ github.event.pull_request.head.sha }} ref: ${{ github.event.pull_request.head.sha }}
``` ```
@ -209,7 +216,7 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v2
``` ```
## Push a commit using the built-in token ## Push a commit using the built-in token
@ -220,7 +227,7 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v2
- run: | - run: |
date > generated.txt date > generated.txt
git config user.name github-actions git config user.name github-actions

@ -20,7 +20,6 @@ let tempHomedir: string
let git: IGitCommandManager & {env: {[key: string]: string}} let git: IGitCommandManager & {env: {[key: string]: string}}
let settings: IGitSourceSettings let settings: IGitSourceSettings
let sshPath: string let sshPath: string
let githubServerUrl: string
describe('git-auth-helper tests', () => { describe('git-auth-helper tests', () => {
beforeAll(async () => { beforeAll(async () => {
@ -68,18 +67,11 @@ describe('git-auth-helper tests', () => {
} }
}) })
async function testAuthHeader( const configureAuth_configuresAuthHeader =
testName: string, 'configureAuth configures auth header'
serverUrl: string | undefined = undefined it(configureAuth_configuresAuthHeader, async () => {
) {
// Arrange // Arrange
let expectedServerUrl = 'https://github.com' await setup(configureAuth_configuresAuthHeader)
if (serverUrl) {
githubServerUrl = serverUrl
expectedServerUrl = githubServerUrl
}
await setup(testName)
expect(settings.authToken).toBeTruthy() // sanity check expect(settings.authToken).toBeTruthy() // sanity check
const authHelper = gitAuthHelper.createAuthHelper(git, settings) const authHelper = gitAuthHelper.createAuthHelper(git, settings)
@ -96,33 +88,9 @@ describe('git-auth-helper tests', () => {
).toString('base64') ).toString('base64')
expect( expect(
configContent.indexOf( configContent.indexOf(
`http.${expectedServerUrl}/.extraheader AUTHORIZATION: basic ${basicCredential}` `http.https://github.com/.extraheader AUTHORIZATION: basic ${basicCredential}`
) )
).toBeGreaterThanOrEqual(0) ).toBeGreaterThanOrEqual(0)
}
const configureAuth_configuresAuthHeader =
'configureAuth configures auth header'
it(configureAuth_configuresAuthHeader, async () => {
await testAuthHeader(configureAuth_configuresAuthHeader)
})
const configureAuth_AcceptsGitHubServerUrl =
'inject https://my-ghes-server.com as github server url'
it(configureAuth_AcceptsGitHubServerUrl, async () => {
await testAuthHeader(
configureAuth_AcceptsGitHubServerUrl,
'https://my-ghes-server.com'
)
})
const configureAuth_AcceptsGitHubServerUrlSetToGHEC =
'inject https://github.com as github server url'
it(configureAuth_AcceptsGitHubServerUrlSetToGHEC, async () => {
await testAuthHeader(
configureAuth_AcceptsGitHubServerUrl,
'https://github.com'
)
}) })
const configureAuth_configuresAuthHeaderEvenWhenPersistCredentialsFalse = const configureAuth_configuresAuthHeaderEvenWhenPersistCredentialsFalse =
@ -810,8 +778,7 @@ async function setup(testName: string): Promise<void> {
sshKnownHosts: '', sshKnownHosts: '',
sshStrict: true, sshStrict: true,
workflowOrganizationId: 123456, workflowOrganizationId: 123456,
setSafeDirectory: true, setSafeDirectory: true
githubServerUrl: githubServerUrl
} }
} }

@ -1,80 +0,0 @@
import * as exec from '@actions/exec'
import * as fshelper from '../lib/fs-helper'
import * as commandManager from '../lib/git-command-manager'
let git: commandManager.IGitCommandManager
let mockExec = jest.fn()
describe('git-auth-helper tests', () => {
beforeAll(async () => {})
beforeEach(async () => {
jest.spyOn(fshelper, 'fileExistsSync').mockImplementation(jest.fn())
jest.spyOn(fshelper, 'directoryExistsSync').mockImplementation(jest.fn())
})
afterEach(() => {
jest.restoreAllMocks()
})
afterAll(() => {})
it('branch list matches', async () => {
mockExec.mockImplementation((path, args, options) => {
console.log(args, options.listeners.stdout)
if (args.includes('version')) {
options.listeners.stdout(Buffer.from('2.18'))
return 0
}
if (args.includes('rev-parse')) {
options.listeners.stdline(Buffer.from('refs/heads/foo'))
options.listeners.stdline(Buffer.from('refs/heads/bar'))
return 0
}
return 1
})
jest.spyOn(exec, 'exec').mockImplementation(mockExec)
const workingDirectory = 'test'
const lfs = false
git = await commandManager.createCommandManager(workingDirectory, lfs)
let branches = await git.branchList(false)
expect(branches).toHaveLength(2)
expect(branches.sort()).toEqual(['foo', 'bar'].sort())
})
it('ambiguous ref name output is captured', async () => {
mockExec.mockImplementation((path, args, options) => {
console.log(args, options.listeners.stdout)
if (args.includes('version')) {
options.listeners.stdout(Buffer.from('2.18'))
return 0
}
if (args.includes('rev-parse')) {
options.listeners.stdline(Buffer.from('refs/heads/foo'))
// If refs/tags/v1 and refs/heads/tags/v1 existed on this repository
options.listeners.errline(
Buffer.from("error: refname 'tags/v1' is ambiguous")
)
return 0
}
return 1
})
jest.spyOn(exec, 'exec').mockImplementation(mockExec)
const workingDirectory = 'test'
const lfs = false
git = await commandManager.createCommandManager(workingDirectory, lfs)
let branches = await git.branchList(false)
expect(branches).toHaveLength(1)
expect(branches.sort()).toEqual(['foo'].sort())
})
})

@ -71,10 +71,7 @@ inputs:
set-safe-directory: set-safe-directory:
description: Add repository path as safe.directory for Git global config by running `git config --global --add safe.directory <path>` description: Add repository path as safe.directory for Git global config by running `git config --global --add safe.directory <path>`
default: true default: true
github-server-url:
description: The base URL for the GitHub instance that you are trying to clone from, will use environment defaults to fetch from the same instance that the workflow is running from unless specified. Example URLs are https://github.com or https://my-ghes-server.example.com
required: false
runs: runs:
using: node16 using: node12
main: dist/index.js main: dist/index.js
post: dist/index.js post: dist/index.js

72804
dist/index.js vendored

File diff suppressed because one or more lines are too long

18642
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -1,6 +1,6 @@
{ {
"name": "checkout", "name": "checkout",
"version": "3.2.0", "version": "2.6.0",
"description": "checkout action", "description": "checkout action",
"main": "lib/main.js", "main": "lib/main.js",
"scripts": { "scripts": {
@ -31,7 +31,7 @@
"@actions/core": "^1.10.0", "@actions/core": "^1.10.0",
"@actions/exec": "^1.0.1", "@actions/exec": "^1.0.1",
"@actions/github": "^2.2.0", "@actions/github": "^2.2.0",
"@actions/io": "^1.1.3", "@actions/io": "^1.1.2",
"@actions/tool-cache": "^1.1.2", "@actions/tool-cache": "^1.1.2",
"uuid": "^3.3.3" "uuid": "^3.3.3"
}, },
@ -41,7 +41,7 @@
"@types/uuid": "^3.4.6", "@types/uuid": "^3.4.6",
"@typescript-eslint/eslint-plugin": "^5.45.0", "@typescript-eslint/eslint-plugin": "^5.45.0",
"@typescript-eslint/parser": "^5.45.0", "@typescript-eslint/parser": "^5.45.0",
"@vercel/ncc": "^0.36.1", "@zeit/ncc": "^0.20.5",
"eslint": "^7.32.0", "eslint": "^7.32.0",
"eslint-plugin-github": "^4.3.2", "eslint-plugin-github": "^4.3.2",
"eslint-plugin-jest": "^25.7.0", "eslint-plugin-jest": "^25.7.0",

@ -52,7 +52,7 @@ class GitAuthHelper {
this.settings = gitSourceSettings || (({} as unknown) as IGitSourceSettings) this.settings = gitSourceSettings || (({} as unknown) as IGitSourceSettings)
// Token auth header // Token auth header
const serverUrl = urlHelper.getServerUrl(this.settings.githubServerUrl) const serverUrl = urlHelper.getServerUrl()
this.tokenConfigKey = `http.${serverUrl.origin}/.extraheader` // "origin" is SCHEME://HOSTNAME[:PORT] this.tokenConfigKey = `http.${serverUrl.origin}/.extraheader` // "origin" is SCHEME://HOSTNAME[:PORT]
const basicCredential = Buffer.from( const basicCredential = Buffer.from(
`x-access-token:${this.settings.authToken}`, `x-access-token:${this.settings.authToken}`,

@ -94,11 +94,8 @@ class GitCommandManager {
// Note, this implementation uses "rev-parse --symbolic-full-name" because the output from // Note, this implementation uses "rev-parse --symbolic-full-name" because the output from
// "branch --list" is more difficult when in a detached HEAD state. // "branch --list" is more difficult when in a detached HEAD state.
// Note, this implementation uses "rev-parse --symbolic-full-name" because there is a bug
// TODO(https://github.com/actions/checkout/issues/786): this implementation uses // in Git 2.18 that causes "rev-parse --symbolic" to output symbolic full names.
// "rev-parse --symbolic-full-name" because there is a bug
// in Git 2.18 that causes "rev-parse --symbolic" to output symbolic full names. When
// 2.18 is no longer supported, we can switch back to --symbolic.
const args = ['rev-parse', '--symbolic-full-name'] const args = ['rev-parse', '--symbolic-full-name']
if (remote) { if (remote) {
@ -107,47 +104,19 @@ class GitCommandManager {
args.push('--branches') args.push('--branches')
} }
const stderr: string[] = [] const output = await this.execGit(args)
const errline: string[] = []
const stdout: string[] = []
const stdline: string[] = []
const listeners = {
stderr: (data: Buffer) => {
stderr.push(data.toString())
},
errline: (data: Buffer) => {
errline.push(data.toString())
},
stdout: (data: Buffer) => {
stdout.push(data.toString())
},
stdline: (data: Buffer) => {
stdline.push(data.toString())
}
}
// Suppress the output in order to avoid flooding annotations with innocuous errors.
await this.execGit(args, false, true, listeners)
core.debug(`stderr callback is: ${stderr}`)
core.debug(`errline callback is: ${errline}`)
core.debug(`stdout callback is: ${stdout}`)
core.debug(`stdline callback is: ${stdline}`)
for (let branch of stdline) { for (let branch of output.stdout.trim().split('\n')) {
branch = branch.trim() branch = branch.trim()
if (!branch) { if (branch) {
continue if (branch.startsWith('refs/heads/')) {
} branch = branch.substr('refs/heads/'.length)
} else if (branch.startsWith('refs/remotes/')) {
branch = branch.substr('refs/remotes/'.length)
}
if (branch.startsWith('refs/heads/')) { result.push(branch)
branch = branch.substring('refs/heads/'.length)
} else if (branch.startsWith('refs/remotes/')) {
branch = branch.substring('refs/remotes/'.length)
} }
result.push(branch)
} }
return result return result
@ -426,8 +395,7 @@ class GitCommandManager {
private async execGit( private async execGit(
args: string[], args: string[],
allowAllExitCodes = false, allowAllExitCodes = false,
silent = false, silent = false
customListeners = {}
): Promise<GitOutput> { ): Promise<GitOutput> {
fshelper.directoryExistsSync(this.workingDirectory, true) fshelper.directoryExistsSync(this.workingDirectory, true)
@ -441,29 +409,22 @@ class GitCommandManager {
env[key] = this.gitEnv[key] env[key] = this.gitEnv[key]
} }
const defaultListener = {
stdout: (data: Buffer) => {
stdout.push(data.toString())
}
}
const mergedListeners = {...defaultListener, ...customListeners}
const stdout: string[] = [] const stdout: string[] = []
const options = { const options = {
cwd: this.workingDirectory, cwd: this.workingDirectory,
env, env,
silent, silent,
ignoreReturnCode: allowAllExitCodes, ignoreReturnCode: allowAllExitCodes,
listeners: mergedListeners listeners: {
stdout: (data: Buffer) => {
stdout.push(data.toString())
}
}
} }
result.exitCode = await exec.exec(`"${this.gitPath}"`, args, options) result.exitCode = await exec.exec(`"${this.gitPath}"`, args, options)
result.stdout = stdout.join('') result.stdout = stdout.join('')
core.debug(result.exitCode.toString())
core.debug(result.stdout)
return result return result
} }

@ -93,8 +93,7 @@ export async function getSource(settings: IGitSourceSettings): Promise<void> {
settings.repositoryName, settings.repositoryName,
settings.ref, settings.ref,
settings.commit, settings.commit,
settings.repositoryPath, settings.repositoryPath
settings.githubServerUrl
) )
return return
} }
@ -139,8 +138,7 @@ export async function getSource(settings: IGitSourceSettings): Promise<void> {
settings.ref = await githubApiHelper.getDefaultBranch( settings.ref = await githubApiHelper.getDefaultBranch(
settings.authToken, settings.authToken,
settings.repositoryOwner, settings.repositoryOwner,
settings.repositoryName, settings.repositoryName
settings.githubServerUrl
) )
} }
core.endGroup() core.endGroup()
@ -234,8 +232,7 @@ export async function getSource(settings: IGitSourceSettings): Promise<void> {
settings.repositoryOwner, settings.repositoryOwner,
settings.repositoryName, settings.repositoryName,
settings.ref, settings.ref,
settings.commit, settings.commit
settings.githubServerUrl
) )
} finally { } finally {
// Remove auth // Remove auth

@ -83,9 +83,4 @@ export interface IGitSourceSettings {
* Indicates whether to add repositoryPath as safe.directory in git global config * Indicates whether to add repositoryPath as safe.directory in git global config
*/ */
setSafeDirectory: boolean setSafeDirectory: boolean
/**
* User override on the GitHub Server/Host URL that hosts the repository to be cloned
*/
githubServerUrl: string | undefined
} }

@ -1,12 +1,13 @@
import * as assert from 'assert' import * as assert from 'assert'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as fs from 'fs' import * as fs from 'fs'
import * as github from '@actions/github'
import * as io from '@actions/io' import * as io from '@actions/io'
import * as path from 'path' import * as path from 'path'
import * as retryHelper from './retry-helper' import * as retryHelper from './retry-helper'
import * as toolCache from '@actions/tool-cache' import * as toolCache from '@actions/tool-cache'
import {default as uuid} from 'uuid/v4' import {default as uuid} from 'uuid/v4'
import {getOctokit, Octokit} from './octokit-provider' import {Octokit} from '@octokit/rest'
const IS_WINDOWS = process.platform === 'win32' const IS_WINDOWS = process.platform === 'win32'
@ -16,19 +17,18 @@ export async function downloadRepository(
repo: string, repo: string,
ref: string, ref: string,
commit: string, commit: string,
repositoryPath: string, repositoryPath: string
baseUrl?: string
): Promise<void> { ): Promise<void> {
// Determine the default branch // Determine the default branch
if (!ref && !commit) { if (!ref && !commit) {
core.info('Determining the default branch') core.info('Determining the default branch')
ref = await getDefaultBranch(authToken, owner, repo, baseUrl) ref = await getDefaultBranch(authToken, owner, repo)
} }
// Download the archive // Download the archive
let archiveData = await retryHelper.execute(async () => { let archiveData = await retryHelper.execute(async () => {
core.info('Downloading the archive') core.info('Downloading the archive')
return await downloadArchive(authToken, owner, repo, ref, commit, baseUrl) return await downloadArchive(authToken, owner, repo, ref, commit)
}) })
// Write archive to disk // Write archive to disk
@ -79,12 +79,11 @@ export async function downloadRepository(
export async function getDefaultBranch( export async function getDefaultBranch(
authToken: string, authToken: string,
owner: string, owner: string,
repo: string, repo: string
baseUrl?: string
): Promise<string> { ): Promise<string> {
return await retryHelper.execute(async () => { return await retryHelper.execute(async () => {
core.info('Retrieving the default branch name') core.info('Retrieving the default branch name')
const octokit = getOctokit(authToken, {baseUrl: baseUrl}) const octokit = new github.GitHub(authToken)
let result: string let result: string
try { try {
// Get the default branch from the repo info // Get the default branch from the repo info
@ -122,10 +121,9 @@ async function downloadArchive(
owner: string, owner: string,
repo: string, repo: string,
ref: string, ref: string,
commit: string, commit: string
baseUrl?: string
): Promise<Buffer> { ): Promise<Buffer> {
const octokit = getOctokit(authToken, {baseUrl: baseUrl}) const octokit = new github.GitHub(authToken)
const params: Octokit.ReposGetArchiveLinkParams = { const params: Octokit.ReposGetArchiveLinkParams = {
owner: owner, owner: owner,
repo: repo, repo: repo,

@ -125,10 +125,5 @@ export async function getInputs(): Promise<IGitSourceSettings> {
// Set safe.directory in git global config. // Set safe.directory in git global config.
result.setSafeDirectory = result.setSafeDirectory =
(core.getInput('set-safe-directory') || 'true').toUpperCase() === 'TRUE' (core.getInput('set-safe-directory') || 'true').toUpperCase() === 'TRUE'
// Determine the GitHub URL that the repository is being hosted from
result.githubServerUrl = core.getInput('github-server-url')
core.debug(`GitHub Host URL = ${result.githubServerUrl}`)
return result return result
} }

@ -120,7 +120,7 @@ function updateUsage(
} }
updateUsage( updateUsage(
'actions/checkout@v3', 'actions/checkout@v2',
path.join(__dirname, '..', '..', 'action.yml'), path.join(__dirname, '..', '..', 'action.yml'),
path.join(__dirname, '..', '..', 'README.md') path.join(__dirname, '..', '..', 'README.md')
) )

@ -1,23 +0,0 @@
import * as github from '@actions/github'
import {Octokit} from '@octokit/rest'
import {getServerApiUrl} from './url-helper'
// Centralize all Octokit references by re-exporting
export {Octokit} from '@octokit/rest'
export type OctokitOptions = {
baseUrl?: string
userAgent?: string
}
export function getOctokit(authToken: string, opts: OctokitOptions) {
const options: Octokit.Options = {
baseUrl: getServerApiUrl(opts.baseUrl)
}
if (opts.userAgent) {
options.userAgent = opts.userAgent
}
return new github.GitHub(authToken, options)
}

@ -1,8 +1,7 @@
import {URL} from 'url'
import {IGitCommandManager} from './git-command-manager' import {IGitCommandManager} from './git-command-manager'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as github from '@actions/github' import * as github from '@actions/github'
import {getOctokit} from './octokit-provider'
import {isGhes} from './url-helper'
export const tagsRefSpec = '+refs/tags/*:refs/tags/*' export const tagsRefSpec = '+refs/tags/*:refs/tags/*'
@ -184,12 +183,11 @@ export async function checkCommitInfo(
repositoryOwner: string, repositoryOwner: string,
repositoryName: string, repositoryName: string,
ref: string, ref: string,
commit: string, commit: string
baseUrl?: string
): Promise<void> { ): Promise<void> {
try { try {
// GHES? // GHES?
if (isGhes(baseUrl)) { if (isGhes()) {
return return
} }
@ -245,8 +243,7 @@ export async function checkCommitInfo(
core.debug( core.debug(
`Expected head sha ${expectedHeadSha}; actual head sha ${actualHeadSha}` `Expected head sha ${expectedHeadSha}; actual head sha ${actualHeadSha}`
) )
const octokit = getOctokit(token, { const octokit = new github.GitHub(token, {
baseUrl: baseUrl,
userAgent: `actions-checkout-tracepoint/1.0 (code=STALE_MERGE;owner=${repositoryOwner};repo=${repositoryName};pr=${fromPayload( userAgent: `actions-checkout-tracepoint/1.0 (code=STALE_MERGE;owner=${repositoryOwner};repo=${repositoryName};pr=${fromPayload(
'number' 'number'
)};run_id=${ )};run_id=${
@ -279,3 +276,10 @@ function select(obj: any, path: string): any {
const key = path.substr(0, i) const key = path.substr(0, i)
return select(obj[key], path.substr(i + 1)) return select(obj[key], path.substr(i + 1))
} }
function isGhes(): boolean {
const ghUrl = new URL(
process.env['GITHUB_SERVER_URL'] || 'https://github.com'
)
return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'
}

@ -47,7 +47,7 @@ export function setSshKnownHostsPath(sshKnownHostsPath: string) {
} }
/** /**
* Save the set-safe-directory input so the POST action can retrieve the value. * Save the sef-safe-directory input so the POST action can retrieve the value.
*/ */
export function setSafeDirectory() { export function setSafeDirectory() {
core.saveState('setSafeDirectory', 'true') core.saveState('setSafeDirectory', 'true')

@ -1,6 +1,6 @@
import * as assert from 'assert' import * as assert from 'assert'
import {URL} from 'url'
import {IGitSourceSettings} from './git-source-settings' import {IGitSourceSettings} from './git-source-settings'
import {URL} from 'url'
export function getFetchUrl(settings: IGitSourceSettings): string { export function getFetchUrl(settings: IGitSourceSettings): string {
assert.ok( assert.ok(
@ -8,7 +8,7 @@ export function getFetchUrl(settings: IGitSourceSettings): string {
'settings.repositoryOwner must be defined' 'settings.repositoryOwner must be defined'
) )
assert.ok(settings.repositoryName, 'settings.repositoryName must be defined') assert.ok(settings.repositoryName, 'settings.repositoryName must be defined')
const serviceUrl = getServerUrl(settings.githubServerUrl) const serviceUrl = getServerUrl()
const encodedOwner = encodeURIComponent(settings.repositoryOwner) const encodedOwner = encodeURIComponent(settings.repositoryOwner)
const encodedName = encodeURIComponent(settings.repositoryName) const encodedName = encodeURIComponent(settings.repositoryName)
if (settings.sshKey) { if (settings.sshKey) {
@ -19,27 +19,11 @@ export function getFetchUrl(settings: IGitSourceSettings): string {
return `${serviceUrl.origin}/${encodedOwner}/${encodedName}` return `${serviceUrl.origin}/${encodedOwner}/${encodedName}`
} }
export function getServerUrl(url?: string): URL { export function getServerUrl(): URL {
let urlValue = // todo: remove GITHUB_URL after support for GHES Alpha is no longer needed
url && url.trim().length > 0 return new URL(
? url process.env['GITHUB_SERVER_URL'] ||
: process.env['GITHUB_SERVER_URL'] || 'https://github.com' process.env['GITHUB_URL'] ||
return new URL(urlValue) 'https://github.com'
} )
export function getServerApiUrl(url?: string): string {
let apiUrl = 'https://api.github.com'
if (isGhes(url)) {
const serverUrl = getServerUrl(url)
apiUrl = new URL(`${serverUrl.origin}/api/v3`).toString()
}
return apiUrl
}
export function isGhes(url?: string): boolean {
const ghUrl = getServerUrl(url)
return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'
} }

Loading…
Cancel
Save