Compare commits

...

8 Commits

Author SHA1 Message Date
Nicolas Schweitzer
7897d7b5db Merge ab5d862ce8 into 85e6279cec 2025-01-22 10:55:19 +00:00
Nicolas Schweitzer
ab5d862ce8 fix tests and update index.js 2025-01-22 11:55:00 +01:00
Nicolas Schweitzer
5fba9eb899 codereview: define a git-user slug instead of a true/false config 2025-01-21 18:50:25 +01:00
Josh Gross
85e6279cec Adjust positioning of user email note and permissions heading (#2044)
Some checks failed
CodeQL / Analyze (javascript) (push) Failing after 3m16s
Build and Test / build (push) Failing after 25s
Build and Test / test (ubuntu-latest) (push) Failing after 25s
Build and Test / test-proxy (push) Failing after 1m24s
Build and Test / test-bypass-proxy (push) Failing after 25s
Build and Test / test-git-container (push) Failing after 1m13s
Build and Test / test-output (push) Failing after 25s
Build and Test / test (macos-latest) (push) Has been cancelled
Build and Test / test (windows-latest) (push) Has been cancelled
2025-01-16 15:56:18 -05:00
Ben Wells
009b9ae9e4 Documentation update - add recommended permissions to Readme (#2043)
* Update README.md

* Update README.md

Co-authored-by: Josh Gross <joshmgross@github.com>

---------

Co-authored-by: Josh Gross <joshmgross@github.com>
2025-01-16 14:14:48 -05:00
Nicolas Schweitzer
f3b199b7ed feat(git config): Set default user.name and user.email in git config 2024-12-19 16:24:48 +01:00
Mohammad Ismail
cbb722410c Update README.md (#1977) 2024-11-14 10:41:00 -05:00
The web walker
3b9b8c884f docs: update README.md (#1971)
Add a scenario where it is necessary to push a commit to a pull request.
2024-11-08 10:32:54 -05:00
14 changed files with 131 additions and 27 deletions

View File

@@ -41,6 +41,12 @@ Please refer to the [release page](https://github.com/actions/checkout/releases/
# Default: ${{ github.token }} # Default: ${{ github.token }}
token: '' token: ''
# Github slug used to configure local user.name and user.email for git. This is
# required to push a commit from a Github Action Workflow. Set to '' to disable
# this configuration.
# Default: github-action[bot]
git-user: ''
# SSH key used to fetch the repository. The SSH key is configured with the local # SSH key used to fetch the repository. The SSH key is configured with the local
# git config, which enables your scripts to run authenticated git commands. The # git config, which enables your scripts to run authenticated git commands. The
# post-job step removes the SSH key. # post-job step removes the SSH key.
@@ -143,6 +149,7 @@ Please refer to the [release page](https://github.com/actions/checkout/releases/
- [Checkout pull request HEAD commit instead of merge commit](#Checkout-pull-request-HEAD-commit-instead-of-merge-commit) - [Checkout pull request HEAD commit instead of merge commit](#Checkout-pull-request-HEAD-commit-instead-of-merge-commit)
- [Checkout pull request on closed event](#Checkout-pull-request-on-closed-event) - [Checkout pull request on closed event](#Checkout-pull-request-on-closed-event)
- [Push a commit using the built-in token](#Push-a-commit-using-the-built-in-token) - [Push a commit using the built-in token](#Push-a-commit-using-the-built-in-token)
- [Push a commit to a PR using the built-in token](#Push-a-commit-to-a-PR-using-the-built-in-token)
## Fetch only the root files ## Fetch only the root files
@@ -211,7 +218,7 @@ Please refer to the [release page](https://github.com/actions/checkout/releases/
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) > - If your secondary repository is private or internal 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)
@@ -225,7 +232,7 @@ Please refer to the [release page](https://github.com/actions/checkout/releases/
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) > - If your secondary repository is private or internal 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)
@@ -280,14 +287,44 @@ jobs:
- run: | - run: |
date > generated.txt date > generated.txt
# Note: the following account information will not work on GHES # 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 add .
git commit -m "generated" git commit -m "generated"
git push git push
``` ```
*NOTE:* The user email is `{user.id}+{user.login}@users.noreply.github.com`. See users API: https://api.github.com/users/github-actions%5Bbot%5D *NOTE:* The user email is `{user.id}+{user.login}@users.noreply.github.com`. See users API: https://api.github.com/users/github-actions%5Bbot%5D
## Push a commit to a PR using the built-in token
In a pull request trigger, `ref` is required as GitHub Actions checks out in detached HEAD mode, meaning it doesnt check out your branch by default.
```yaml
on: pull_request
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.head_ref }}
- run: |
date > generated.txt
# Note: the following account information will not work on GHES
git add .
git commit -m "generated"
git push
```
*NOTE:* The user email is `{user.id}+{user.login}@users.noreply.github.com`. See users API: https://api.github.com/users/github-actions%5Bbot%5D
# Recommended permissions
When using the `checkout` action in your GitHub Actions workflow, it is recommended to set the following `GITHUB_TOKEN` permissions to ensure proper functionality, unless alternative auth is provided via the `token` or `ssh-key` inputs:
```yaml
permissions:
contents: read
```
# License # License
The scripts and documentation in this project are released under the [MIT License](LICENSE) The scripts and documentation in this project are released under the [MIT License](LICENSE)

View File

@@ -1,12 +1,12 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import * as fs from 'fs' import * as fs from 'fs'
import * as gitAuthHelper from '../lib/git-auth-helper' import * as gitAuthHelper from '../src/git-auth-helper'
import * as io from '@actions/io' import * as io from '@actions/io'
import * as os from 'os' import * as os from 'os'
import * as path from 'path' import * as path from 'path'
import * as stateHelper from '../lib/state-helper' import * as stateHelper from '../src/state-helper'
import {IGitCommandManager} from '../lib/git-command-manager' import {IGitCommandManager} from '../src/git-command-manager'
import {IGitSourceSettings} from '../lib/git-source-settings' import {IGitSourceSettings} from '../src/git-source-settings'
const isWindows = process.platform === 'win32' const isWindows = process.platform === 'win32'
const testWorkspace = path.join(__dirname, '_temp', 'git-auth-helper') const testWorkspace = path.join(__dirname, '_temp', 'git-auth-helper')
@@ -824,7 +824,8 @@ async function setup(testName: string): Promise<void> {
sshUser: '', sshUser: '',
workflowOrganizationId: 123456, workflowOrganizationId: 123456,
setSafeDirectory: true, setSafeDirectory: true,
githubServerUrl: githubServerUrl githubServerUrl: githubServerUrl,
gitUser: 'github-action[bot]'
} }
} }

View File

@@ -1,6 +1,6 @@
import * as exec from '@actions/exec' import * as exec from '@actions/exec'
import * as fshelper from '../lib/fs-helper' import * as fshelper from '../src/fs-helper'
import * as commandManager from '../lib/git-command-manager' import * as commandManager from '../src/git-command-manager'
let git: commandManager.IGitCommandManager let git: commandManager.IGitCommandManager
let mockExec = jest.fn() let mockExec = jest.fn()

View File

@@ -1,9 +1,9 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import * as fs from 'fs' import * as fs from 'fs'
import * as gitDirectoryHelper from '../lib/git-directory-helper' import * as gitDirectoryHelper from '../src/git-directory-helper'
import * as io from '@actions/io' import * as io from '@actions/io'
import * as path from 'path' import * as path from 'path'
import {IGitCommandManager} from '../lib/git-command-manager' import {IGitCommandManager} from '../src/git-command-manager'
const testWorkspace = path.join(__dirname, '_temp', 'git-directory-helper') const testWorkspace = path.join(__dirname, '_temp', 'git-directory-helper')
let repositoryPath: string let repositoryPath: string

View File

@@ -1,10 +1,10 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import * as fsHelper from '../lib/fs-helper' import * as fsHelper from '../src/fs-helper'
import * as github from '@actions/github' import * as github from '@actions/github'
import * as inputHelper from '../lib/input-helper' import * as inputHelper from '../src/input-helper'
import * as path from 'path' import * as path from 'path'
import * as workflowContextHelper from '../lib/workflow-context-helper' import * as workflowContextHelper from '../src/workflow-context-helper'
import {IGitSourceSettings} from '../lib/git-source-settings' import {IGitSourceSettings} from '../src/git-source-settings'
const originalGitHubWorkspace = process.env['GITHUB_WORKSPACE'] const originalGitHubWorkspace = process.env['GITHUB_WORKSPACE']
const gitHubWorkspace = path.resolve('/checkout-tests/workspace') const gitHubWorkspace = path.resolve('/checkout-tests/workspace')

View File

@@ -1,6 +1,6 @@
import * as assert from 'assert' import * as assert from 'assert'
import * as refHelper from '../lib/ref-helper' import * as refHelper from '../src/ref-helper'
import {IGitCommandManager} from '../lib/git-command-manager' import {IGitCommandManager} from '../src/git-command-manager'
const commit = '1234567890123456789012345678901234567890' const commit = '1234567890123456789012345678901234567890'
let git: IGitCommandManager let git: IGitCommandManager

View File

@@ -1,5 +1,5 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import {RetryHelper} from '../lib/retry-helper' import {RetryHelper} from '../src/retry-helper'
let info: string[] let info: string[]
let retryHelper: any let retryHelper: any

View File

@@ -22,6 +22,12 @@ inputs:
[Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets)
default: ${{ github.token }} default: ${{ github.token }}
git-user:
description: >
Github slug used to configure local user.name and user.email for git.
This is required to push a commit from a Github Action Workflow.
Set to '' to disable this configuration.
default: "github-action[bot]"
ssh-key: ssh-key:
description: > description: >
SSH key used to fetch the repository. The SSH key is configured with the local SSH key used to fetch the repository. The SSH key is configured with the local

21
dist/index.js vendored
View File

@@ -1357,6 +1357,15 @@ function getSource(settings) {
core.setOutput('commit', commitSHA.trim()); core.setOutput('commit', commitSHA.trim());
// Check for incorrect pull request merge commit // Check for incorrect pull request merge commit
yield refHelper.checkCommitInfo(settings.authToken, commitInfo, settings.repositoryOwner, settings.repositoryName, settings.ref, settings.commit, settings.githubServerUrl); yield refHelper.checkCommitInfo(settings.authToken, commitInfo, settings.repositoryOwner, settings.repositoryName, settings.ref, settings.commit, settings.githubServerUrl);
if (settings.gitUser) {
if (!(yield git.configExists('user.name', true))) {
yield git.config('user.name', settings.gitUser, true);
}
if (!(yield git.configExists('user.email', true))) {
const userId = yield githubApiHelper.getUserId(settings.gitUser, settings.authToken, settings.githubServerUrl);
yield git.config('user.email', `${userId}+${settings.gitUser}@users.noreply.github.com`, true);
}
}
} }
finally { finally {
// Remove auth // Remove auth
@@ -1546,6 +1555,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.downloadRepository = downloadRepository; exports.downloadRepository = downloadRepository;
exports.getDefaultBranch = getDefaultBranch; exports.getDefaultBranch = getDefaultBranch;
exports.getUserId = getUserId;
const assert = __importStar(__nccwpck_require__(9491)); const assert = __importStar(__nccwpck_require__(9491));
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const fs = __importStar(__nccwpck_require__(7147)); const fs = __importStar(__nccwpck_require__(7147));
@@ -1663,6 +1673,15 @@ function downloadArchive(authToken, owner, repo, ref, commit, baseUrl) {
return Buffer.from(response.data); // response.data is ArrayBuffer return Buffer.from(response.data); // response.data is ArrayBuffer
}); });
} }
function getUserId(username, authToken, baseUrl) {
return __awaiter(this, void 0, void 0, function* () {
const octokit = github.getOctokit(authToken, {
baseUrl: (0, url_helper_1.getServerApiUrl)(baseUrl)
});
const user = yield octokit.rest.users.getByUsername({ username, });
return user.data.id;
});
}
/***/ }), /***/ }),
@@ -1813,6 +1832,8 @@ function getInputs() {
core.debug(`recursive submodules = ${result.nestedSubmodules}`); core.debug(`recursive submodules = ${result.nestedSubmodules}`);
// Auth token // Auth token
result.authToken = core.getInput('token', { required: true }); result.authToken = core.getInput('token', { required: true });
// Git user
result.gitUser = core.getInput('git-user') || 'github-action[bot]';
// SSH // SSH
result.sshKey = core.getInput('ssh-key'); result.sshKey = core.getInput('ssh-key');
result.sshKnownHosts = core.getInput('ssh-known-hosts'); result.sshKnownHosts = core.getInput('ssh-known-hosts');

16
package-lock.json generated
View File

@@ -2502,10 +2502,11 @@
} }
}, },
"node_modules/cross-spawn": { "node_modules/cross-spawn": {
"version": "7.0.3", "version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"path-key": "^3.1.0", "path-key": "^3.1.0",
"shebang-command": "^2.0.0", "shebang-command": "^2.0.0",
@@ -5528,12 +5529,13 @@
} }
}, },
"node_modules/micromatch": { "node_modules/micromatch": {
"version": "4.0.5", "version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"braces": "^3.0.2", "braces": "^3.0.3",
"picomatch": "^2.3.1" "picomatch": "^2.3.1"
}, },
"engines": { "engines": {

View File

@@ -274,6 +274,23 @@ export async function getSource(settings: IGitSourceSettings): Promise<void> {
settings.commit, settings.commit,
settings.githubServerUrl settings.githubServerUrl
) )
if (settings.gitUser) {
if (!(await git.configExists('user.name', true))) {
await git.config('user.name', settings.gitUser, true)
}
if (!(await git.configExists('user.email', true))) {
const userId = await githubApiHelper.getUserId(
settings.gitUser,
settings.authToken,
settings.githubServerUrl
)
await git.config(
'user.email',
`${userId}+${settings.gitUser}@users.noreply.github.com`,
true
)
}
}
} finally { } finally {
// Remove auth // Remove auth
if (authHelper) { if (authHelper) {

View File

@@ -79,6 +79,11 @@ export interface IGitSourceSettings {
*/ */
authToken: string authToken: string
/**
* A github user slug to set a default user name and email in the local git config
*/
gitUser: string
/** /**
* The SSH key to configure * The SSH key to configure
*/ */

View File

@@ -143,3 +143,15 @@ async function downloadArchive(
}) })
return Buffer.from(response.data as ArrayBuffer) // response.data is ArrayBuffer return Buffer.from(response.data as ArrayBuffer) // response.data is ArrayBuffer
} }
export async function getUserId(
username: string,
authToken: string,
baseUrl?: string
): Promise<number> {
const octokit = github.getOctokit(authToken, {
baseUrl: getServerApiUrl(baseUrl)
})
const user = await octokit.rest.users.getByUsername({username})
return user.data.id
}

View File

@@ -138,6 +138,9 @@ export async function getInputs(): Promise<IGitSourceSettings> {
// Auth token // Auth token
result.authToken = core.getInput('token', {required: true}) result.authToken = core.getInput('token', {required: true})
// Git user
result.gitUser = core.getInput('git-user') || 'github-action[bot]'
// SSH // SSH
result.sshKey = core.getInput('ssh-key') result.sshKey = core.getInput('ssh-key')
result.sshKnownHosts = core.getInput('ssh-known-hosts') result.sshKnownHosts = core.getInput('ssh-known-hosts')