├── .eslintignore ├── .eslintrc.json ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE.md ├── dependabot.yml └── workflows │ ├── automerge-dependabot.yml │ ├── ci.yml │ ├── cpr-example-command.yml │ ├── slash-command-dispatch.yml │ └── update-major-version.yml ├── .gitignore ├── .prettierignore ├── .prettierrc.json ├── LICENSE ├── README.md ├── __test__ ├── create-or-update-branch.int.test.ts ├── entrypoint.sh ├── git-command-manager.int.test.ts ├── git-config-helper.int.test.ts ├── git-config-helper.unit.test.ts ├── integration-tests.sh └── utils.unit.test.ts ├── action.yml ├── dist ├── 790.index.js └── index.js ├── docs ├── assets │ ├── cpr-gitgraph.htm │ ├── cpr-gitgraph.png │ ├── logo.svg │ └── pull-request-example.png ├── common-issues.md ├── concepts-guidelines.md ├── examples.md └── updating.md ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── create-or-update-branch.ts ├── create-pull-request.ts ├── git-command-manager.ts ├── git-config-helper.ts ├── github-helper.ts ├── main.ts ├── octokit-client.ts └── utils.ts └── tsconfig.json /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | lib/ 3 | node_modules/ 4 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { "node": true, "jest": true }, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { "ecmaVersion": 9, "sourceType": "module" }, 5 | "extends": [ 6 | "eslint:recommended", 7 | "plugin:@typescript-eslint/eslint-recommended", 8 | "plugin:@typescript-eslint/recommended", 9 | "plugin:import/errors", 10 | "plugin:import/warnings", 11 | "plugin:import/typescript", 12 | "plugin:prettier/recommended" 13 | ], 14 | "plugins": ["@typescript-eslint"], 15 | "rules": { 16 | "@typescript-eslint/camelcase": "off" 17 | }, 18 | "settings": { 19 | "import/resolver": { 20 | "typescript": {} 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: peter-evans -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Subject of the issue 2 | 3 | Describe your issue here. 4 | 5 | ### Steps to reproduce 6 | 7 | If this issue is describing a possible bug please provide (or link to) your GitHub Actions workflow. 8 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | day: "tuesday" 8 | labels: 9 | - "dependencies" 10 | 11 | - package-ecosystem: "npm" 12 | directory: "/" 13 | schedule: 14 | interval: "weekly" 15 | day: "tuesday" 16 | ignore: 17 | - dependency-name: "*" 18 | update-types: ["version-update:semver-major"] 19 | labels: 20 | - "dependencies" 21 | -------------------------------------------------------------------------------- /.github/workflows/automerge-dependabot.yml: -------------------------------------------------------------------------------- 1 | name: Auto-merge Dependabot 2 | on: pull_request 3 | 4 | jobs: 5 | automerge: 6 | runs-on: ubuntu-latest 7 | if: github.actor == 'dependabot[bot]' 8 | steps: 9 | - uses: peter-evans/enable-pull-request-automerge@v3 10 | with: 11 | token: ${{ secrets.ACTIONS_BOT_TOKEN }} 12 | pull-request-number: ${{ github.event.pull_request.number }} 13 | merge-method: squash 14 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: [main] 5 | paths-ignore: 6 | - 'README.md' 7 | - 'docs/**' 8 | pull_request: 9 | branches: [main] 10 | paths-ignore: 11 | - 'README.md' 12 | - 'docs/**' 13 | 14 | permissions: 15 | pull-requests: write 16 | contents: write 17 | 18 | jobs: 19 | build: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@v4 23 | - uses: actions/setup-node@v4 24 | with: 25 | node-version: 20.x 26 | cache: npm 27 | - run: npm ci 28 | - run: npm run build 29 | - run: npm run format-check 30 | - run: npm run lint 31 | - run: npm run test 32 | - uses: actions/upload-artifact@v4 33 | with: 34 | name: dist 35 | path: dist 36 | - uses: actions/upload-artifact@v4 37 | with: 38 | name: action.yml 39 | path: action.yml 40 | 41 | test: 42 | if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository 43 | needs: [build] 44 | runs-on: ubuntu-latest 45 | strategy: 46 | matrix: 47 | target: [built, committed] 48 | steps: 49 | - uses: actions/checkout@v4 50 | with: 51 | ref: main 52 | - if: matrix.target == 'built' || github.event_name == 'pull_request' 53 | uses: actions/download-artifact@v4 54 | with: 55 | name: dist 56 | path: dist 57 | - if: matrix.target == 'built' || github.event_name == 'pull_request' 58 | uses: actions/download-artifact@v4 59 | with: 60 | name: action.yml 61 | path: . 62 | 63 | - name: Create change 64 | run: date +%s > report.txt 65 | 66 | - name: Create Pull Request 67 | id: cpr 68 | uses: ./ 69 | with: 70 | commit-message: '[CI] test ${{ matrix.target }}' 71 | committer: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 72 | author: ${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com> 73 | title: '[CI] test ${{ matrix.target }}' 74 | body: | 75 | - CI test case for target '${{ matrix.target }}' 76 | 77 | Auto-generated by [create-pull-request][1] 78 | 79 | [1]: https://github.com/peter-evans/create-pull-request 80 | branch: ci-test-${{ matrix.target }}-${{ github.sha }} 81 | 82 | - name: Close Pull 83 | uses: peter-evans/close-pull@v3 84 | with: 85 | pull-request-number: ${{ steps.cpr.outputs.pull-request-number }} 86 | comment: '[CI] test ${{ matrix.target }}' 87 | delete-branch: true 88 | 89 | commentTestSuiteHelp: 90 | if: github.event_name == 'pull_request' 91 | needs: [test] 92 | runs-on: ubuntu-latest 93 | steps: 94 | - name: Find Comment 95 | uses: peter-evans/find-comment@v3 96 | id: fc 97 | with: 98 | issue-number: ${{ github.event.number }} 99 | comment-author: 'github-actions[bot]' 100 | body-includes: Full test suite slash command 101 | 102 | - if: steps.fc.outputs.comment-id == '' 103 | name: Create comment 104 | uses: peter-evans/create-or-update-comment@v4 105 | with: 106 | issue-number: ${{ github.event.number }} 107 | body: | 108 | Full test suite slash command (repository admin only) 109 | ``` 110 | /test repository=${{ github.event.pull_request.head.repo.full_name }} ref=${{ github.event.pull_request.head.ref }} build=true 111 | ``` 112 | ``` 113 | /test repository=${{ github.event.pull_request.head.repo.full_name }} ref=${{ github.event.pull_request.head.ref }} build=true sign-commits=true 114 | ``` 115 | 116 | package: 117 | if: github.event_name == 'push' && github.ref == 'refs/heads/main' 118 | needs: [test] 119 | runs-on: ubuntu-latest 120 | steps: 121 | - uses: actions/checkout@v4 122 | - uses: actions/download-artifact@v4 123 | with: 124 | name: dist 125 | path: dist 126 | - name: Create Pull Request 127 | uses: peter-evans/create-pull-request@v7 128 | with: 129 | token: ${{ secrets.ACTIONS_BOT_TOKEN }} 130 | commit-message: 'build: update distribution' 131 | title: Update distribution 132 | body: | 133 | - Updates the distribution for changes on `main` 134 | 135 | Auto-generated by [create-pull-request][1] 136 | 137 | [1]: https://github.com/peter-evans/create-pull-request 138 | branch: update-distribution 139 | -------------------------------------------------------------------------------- /.github/workflows/cpr-example-command.yml: -------------------------------------------------------------------------------- 1 | name: Create Pull Request Example Command 2 | on: 3 | repository_dispatch: 4 | types: [cpr-example-command] 5 | jobs: 6 | createPullRequest: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | 11 | - name: Make changes to pull request 12 | run: date +%s > report.txt 13 | 14 | - name: Create Pull Request 15 | id: cpr 16 | uses: ./ 17 | with: 18 | commit-message: Update report 19 | committer: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 20 | author: ${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com> 21 | signoff: false 22 | title: '[Example] Update report' 23 | body: | 24 | Update report 25 | - Updated with *today's* date 26 | - Auto-generated by [create-pull-request][1] 27 | 28 | [1]: https://github.com/peter-evans/create-pull-request 29 | labels: | 30 | report 31 | automated pr 32 | assignees: retepsnave 33 | reviewers: retepsnave 34 | milestone: 1 35 | draft: false 36 | branch: example-patches 37 | delete-branch: true 38 | 39 | - name: Check output 40 | run: | 41 | echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}" 42 | echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}" 43 | 44 | - name: Add reaction 45 | uses: peter-evans/create-or-update-comment@v4 46 | with: 47 | repository: ${{ github.event.client_payload.github.payload.repository.full_name }} 48 | comment-id: ${{ github.event.client_payload.github.payload.comment.id }} 49 | reaction-type: hooray 50 | -------------------------------------------------------------------------------- /.github/workflows/slash-command-dispatch.yml: -------------------------------------------------------------------------------- 1 | name: Slash Command Dispatch 2 | on: 3 | issue_comment: 4 | types: [created] 5 | jobs: 6 | slashCommandDispatch: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Slash Command Dispatch 10 | uses: peter-evans/slash-command-dispatch@v4 11 | with: 12 | token: ${{ secrets.ACTIONS_BOT_TOKEN }} 13 | config: > 14 | [ 15 | { 16 | "command": "test", 17 | "permission": "admin", 18 | "repository": "peter-evans/create-pull-request-tests", 19 | "named_args": true 20 | }, 21 | { 22 | "command": "clean", 23 | "permission": "admin", 24 | "repository": "peter-evans/create-pull-request-tests" 25 | }, 26 | { 27 | "command": "cpr-example", 28 | "permission": "admin", 29 | "issue_type": "issue" 30 | }, 31 | { 32 | "command": "rebase", 33 | "permission": "admin", 34 | "repository": "peter-evans/slash-command-dispatch-processor", 35 | "issue_type": "pull-request" 36 | } 37 | ] 38 | -------------------------------------------------------------------------------- /.github/workflows/update-major-version.yml: -------------------------------------------------------------------------------- 1 | name: Update Major Version 2 | run-name: Update ${{ github.event.inputs.main_version }} to ${{ github.event.inputs.target }} 3 | 4 | on: 5 | workflow_dispatch: 6 | inputs: 7 | target: 8 | description: The target tag or reference 9 | required: true 10 | main_version: 11 | type: choice 12 | description: The major version tag to update 13 | options: 14 | - v6 15 | - v7 16 | 17 | jobs: 18 | tag: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v4 22 | with: 23 | token: ${{ secrets.ACTIONS_BOT_TOKEN }} 24 | fetch-depth: 0 25 | - name: Git config 26 | run: | 27 | git config user.name actions-bot 28 | git config user.email actions-bot@users.noreply.github.com 29 | - name: Tag new target 30 | run: git tag -f ${{ github.event.inputs.main_version }} ${{ github.event.inputs.target }} 31 | - name: Push new tag 32 | run: git push origin ${{ github.event.inputs.main_version }} --force 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | lib/ 2 | node_modules/ 3 | 4 | .DS_Store 5 | .idea 6 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | lib/ 3 | node_modules/ 4 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "tabWidth": 2, 4 | "useTabs": false, 5 | "semi": false, 6 | "singleQuote": true, 7 | "trailingComma": "none", 8 | "bracketSpacing": false, 9 | "arrowParens": "avoid", 10 | "parser": "typescript" 11 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Peter Evans 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Create Pull Request 2 | [![CI](https://github.com/peter-evans/create-pull-request/workflows/CI/badge.svg)](https://github.com/peter-evans/create-pull-request/actions?query=workflow%3ACI) 3 | [![GitHub Marketplace](https://img.shields.io/badge/Marketplace-Create%20Pull%20Request-blue.svg?colorA=24292e&colorB=0366d6&style=flat&longCache=true&logo=github)](https://github.com/marketplace/actions/create-pull-request) 4 | 5 | A GitHub action to create a pull request for changes to your repository in the actions workspace. 6 | 7 | Changes to a repository in the Actions workspace persist between steps in a workflow. 8 | This action is designed to be used in conjunction with other steps that modify or add files to your repository. 9 | The changes will be automatically committed to a new branch and a pull request created. 10 | 11 | Create Pull Request action will: 12 | 13 | 1. Check for repository changes in the Actions workspace. This includes: 14 | - untracked (new) files 15 | - tracked (modified) files 16 | - commits made during the workflow that have not been pushed 17 | 2. Commit all changes to a new branch, or update an existing pull request branch. 18 | 3. Create or update a pull request to merge the branch into the base—the branch checked out in the workflow. 19 | 20 | ## Documentation 21 | 22 | - [Concepts, guidelines and advanced usage](docs/concepts-guidelines.md) 23 | - [Examples](docs/examples.md) 24 | - [Updating to v7](docs/updating.md) 25 | - [Common issues](docs/common-issues.md) 26 | 27 | ## Usage 28 | 29 | ```yml 30 | - uses: actions/checkout@v4 31 | 32 | # Make changes to pull request here 33 | 34 | - name: Create Pull Request 35 | uses: peter-evans/create-pull-request@v7 36 | ``` 37 | 38 | You can also pin to a [specific release](https://github.com/peter-evans/create-pull-request/releases) version in the format `@v7.x.x` 39 | 40 | ### Workflow permissions 41 | 42 | For this action to work you must explicitly allow GitHub Actions to create pull requests. 43 | This setting can be found in a repository's settings under Actions > General > Workflow permissions. 44 | 45 | For repositories belonging to an organization, this setting can be managed by admins in organization settings under Actions > General > Workflow permissions. 46 | 47 | ### Action inputs 48 | 49 | All inputs are **optional**. If not set, sensible defaults will be used. 50 | 51 | | Name | Description | Default | 52 | | --- | --- | --- | 53 | | `token` | The token that the action will use to create and update the pull request. See [token](#token). | `GITHUB_TOKEN` | 54 | | `branch-token` | The token that the action will use to create and update the branch. See [branch-token](#branch-token). | Defaults to the value of `token` | 55 | | `path` | Relative path under `GITHUB_WORKSPACE` to the repository. | `GITHUB_WORKSPACE` | 56 | | `add-paths` | A comma or newline-separated list of file paths to commit. Paths should follow git's [pathspec](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec) syntax. See [Add specific paths](#add-specific-paths). | If no paths are specified, all new and modified files are added. | 57 | | `commit-message` | The message to use when committing changes. See [commit-message](#commit-message). | `[create-pull-request] automated change` | 58 | | `committer` | The committer name and email address in the format `Display Name `. Defaults to the GitHub Actions bot user on github.com. | `github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>` | 59 | | `author` | The author name and email address in the format `Display Name `. Defaults to the user who triggered the workflow run. | `${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com>` | 60 | | `signoff` | Add [`Signed-off-by`](https://git-scm.com/docs/git-commit#Documentation/git-commit.txt---signoff) line by the committer at the end of the commit log message. | `false` | 61 | | `branch` | The pull request branch name. | `create-pull-request/patch` | 62 | | `delete-branch` | Delete the `branch` if it doesn't have an active pull request associated with it. See [delete-branch](#delete-branch). | `false` | 63 | | `branch-suffix` | The branch suffix type when using the alternative branching strategy. Valid values are `random`, `timestamp` and `short-commit-hash`. See [Alternative strategy](#alternative-strategy---always-create-a-new-pull-request-branch) for details. | | 64 | | `base` | Sets the pull request base branch. | Defaults to the branch checked out in the workflow. | 65 | | `push-to-fork` | A fork of the checked-out parent repository to which the pull request branch will be pushed. e.g. `owner/repo-fork`. The pull request will be created to merge the fork's branch into the parent's base. See [push pull request branches to a fork](docs/concepts-guidelines.md#push-pull-request-branches-to-a-fork) for details. | | 66 | | `sign-commits` | Sign commits as `github-actions[bot]` when using `GITHUB_TOKEN`, or your own bot when using [GitHub App tokens](docs/concepts-guidelines.md#authenticating-with-github-app-generated-tokens). See [commit signing](docs/concepts-guidelines.md#commit-signature-verification-for-bots) for details. | `false` | 67 | | `title` | The title of the pull request. | `Changes by create-pull-request action` | 68 | | `body` | The body of the pull request. | `Automated changes by [create-pull-request](https://github.com/peter-evans/create-pull-request) GitHub action` | 69 | | `body-path` | The path to a file containing the pull request body. Takes precedence over `body`. | | 70 | | `labels` | A comma or newline-separated list of labels. | | 71 | | `assignees` | A comma or newline-separated list of assignees (GitHub usernames). | | 72 | | `reviewers` | A comma or newline-separated list of reviewers (GitHub usernames) to request a review from. | | 73 | | `team-reviewers` | A comma or newline-separated list of GitHub teams to request a review from. Note that a `repo` scoped [PAT](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token), or equivalent [GitHub App permissions](docs/concepts-guidelines.md#authenticating-with-github-app-generated-tokens), are required. | | 74 | | `milestone` | The number of the milestone to associate this pull request with. | | 75 | | `draft` | Create a [draft pull request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests#draft-pull-requests). Valid values are `true` (only on create), `always-true` (on create and update), and `false`. | `false` | 76 | | `maintainer-can-modify` | Indicates whether [maintainers can modify](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) the pull request. | `true` | 77 | 78 | #### token 79 | 80 | The token input defaults to the repository's `GITHUB_TOKEN`. 81 | 82 | > [!IMPORTANT] 83 | > - If you want pull requests created by this action to trigger an `on: push` or `on: pull_request` workflow then you cannot use the default `GITHUB_TOKEN`. See the [documentation here](docs/concepts-guidelines.md#triggering-further-workflow-runs) for further details. 84 | > - If using the repository's `GITHUB_TOKEN` and your repository was created after 2nd February 2023, the [default permission is read-only](https://github.blog/changelog/2023-02-02-github-actions-updating-the-default-github_token-permissions-to-read-only/). Elevate the [permissions](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/controlling-permissions-for-github_token#defining-access-for-the-github_token-permissions) in your workflow. 85 | > ```yml 86 | > permissions: 87 | > contents: write 88 | > pull-requests: write 89 | > ``` 90 | 91 | Other token options: 92 | - Classic [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) with `repo` scope. 93 | - Fine-grained [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) with `contents: write` and `pull-requests: write` scopes. 94 | - [GitHub App tokens](docs/concepts-guidelines.md#authenticating-with-github-app-generated-tokens) with `contents: write` and `pull-requests: write` scopes. 95 | 96 | > [!TIP] 97 | > If pull requests could contain changes to Actions workflows you may also need the `workflows` scope. 98 | 99 | #### branch-token 100 | 101 | The action first creates a branch, and then creates a pull request for the branch. 102 | For some rare use cases it can be useful, or even necessary, to use different tokens for these operations. 103 | It is not advisable to use this input unless you know you need to. 104 | 105 | #### commit-message 106 | 107 | In addition to a message, the `commit-message` input can also be used to populate the commit description. Leave a single blank line between the message and description. 108 | 109 | ```yml 110 | commit-message: | 111 | the first line is the commit message 112 | 113 | the commit description starts 114 | after a blank line and can be 115 | multiple lines 116 | ``` 117 | 118 | #### delete-branch 119 | 120 | The `delete-branch` feature doesn't delete branches immediately on merge. (It can't do that because it would require the merge to somehow trigger the action.) 121 | The intention of the feature is that when the action next runs it will delete the `branch` if there is no diff. 122 | 123 | Enabling this feature leads to the following behaviour: 124 | 1. If a pull request was merged and the branch is left undeleted, when the action next runs it will delete the branch if there is no further diff. 125 | 2. If a pull request is open, but there is now no longer a diff and the PR is unnecessary, the action will delete the branch causing the PR to close. 126 | 127 | If you want branches to be deleted immediately on merge then you should use GitHub's `Automatically delete head branches` feature in your repository settings. 128 | 129 | #### Proxy support 130 | 131 | For self-hosted runners behind a corporate proxy set the `https_proxy` environment variable. 132 | ```yml 133 | - name: Create Pull Request 134 | uses: peter-evans/create-pull-request@v7 135 | env: 136 | https_proxy: http://: 137 | ``` 138 | 139 | ### Action outputs 140 | 141 | The following outputs can be used by subsequent workflow steps. 142 | 143 | - `pull-request-number` - The pull request number. 144 | - `pull-request-url` - The URL of the pull request. 145 | - `pull-request-operation` - The pull request operation performed by the action, `created`, `updated`, `closed` or `none`. 146 | - `pull-request-head-sha` - The commit SHA of the pull request branch. 147 | - `pull-request-branch` - The branch name of the pull request. 148 | - `pull-request-commits-verified` - Whether GitHub considers the signature of the branch's commits to be verified; `true` or `false`. 149 | 150 | Step outputs can be accessed as in the following example. 151 | Note that in order to read the step outputs the action step must have an id. 152 | 153 | ```yml 154 | - name: Create Pull Request 155 | id: cpr 156 | uses: peter-evans/create-pull-request@v7 157 | - name: Check outputs 158 | if: ${{ steps.cpr.outputs.pull-request-number }} 159 | run: | 160 | echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}" 161 | echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}" 162 | ``` 163 | 164 | ### Action behaviour 165 | 166 | The default behaviour of the action is to create a pull request that will be continually updated with new changes until it is merged or closed. 167 | Changes are committed and pushed to a fixed-name branch, the name of which can be configured with the `branch` input. 168 | Any subsequent changes will be committed to the *same* branch and reflected in the open pull request. 169 | 170 | How the action behaves: 171 | 172 | - If there are changes (i.e. a diff exists with the checked-out base branch), the changes will be pushed to a new `branch` and a pull request created. 173 | - If there are no changes (i.e. no diff exists with the checked-out base branch), no pull request will be created and the action exits silently. 174 | - If a pull request already exists it will be updated if necessary. Local changes in the Actions workspace, or changes on the base branch, can cause an update. If no update is required the action exits silently. 175 | - If a pull request exists and new changes on the base branch make the pull request unnecessary (i.e. there is no longer a diff between the pull request branch and the base), the pull request is automatically closed. Additionally, if [`delete-branch`](#delete-branch) is set to `true` the `branch` will be deleted. 176 | 177 | For further details about how the action works and usage guidelines, see [Concepts, guidelines and advanced usage](docs/concepts-guidelines.md). 178 | 179 | #### Alternative strategy - Always create a new pull request branch 180 | 181 | For some use cases it may be desirable to always create a new unique branch each time there are changes to be committed. 182 | This strategy is *not recommended* because if not used carefully it could result in multiple pull requests being created unnecessarily. If in doubt, use the [default strategy](#action-behaviour) of creating an updating a fixed-name branch. 183 | 184 | To use this strategy, set input `branch-suffix` with one of the following options. 185 | 186 | - `random` - Commits will be made to a branch suffixed with a random alpha-numeric string. e.g. `create-pull-request/patch-6qj97jr`, `create-pull-request/patch-5jrjhvd` 187 | 188 | - `timestamp` - Commits will be made to a branch suffixed by a timestamp. e.g. `create-pull-request/patch-1569322532`, `create-pull-request/patch-1569322552` 189 | 190 | - `short-commit-hash` - Commits will be made to a branch suffixed with the short SHA1 commit hash. e.g. `create-pull-request/patch-fcdfb59`, `create-pull-request/patch-394710b` 191 | 192 | ### Controlling committed files 193 | 194 | The action defaults to adding all new and modified files. 195 | If there are files that should not be included in the pull request, you can use the following methods to control the committed content. 196 | 197 | #### Remove files 198 | 199 | The most straightforward way to handle unwanted files is simply to remove them in a step before the action runs. 200 | 201 | ```yml 202 | - run: | 203 | rm -rf temp-dir 204 | rm temp-file.txt 205 | ``` 206 | 207 | #### Ignore files 208 | 209 | If there are files or directories you want to ignore you can simply add them to a `.gitignore` file at the root of your repository. The action will respect this file. 210 | 211 | #### Add specific paths 212 | 213 | You can control which files are committed with the `add-paths` input. 214 | Paths should follow git's [pathspec](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec) syntax. 215 | File changes that do not match one of the paths will be stashed and restored after the action has completed. 216 | 217 | ```yml 218 | - name: Create Pull Request 219 | uses: peter-evans/create-pull-request@v7 220 | with: 221 | add-paths: | 222 | *.java 223 | docs/*.md 224 | ``` 225 | 226 | #### Create your own commits 227 | 228 | As well as relying on the action to handle uncommitted changes, you can additionally make your own commits before the action runs. 229 | Note that the repository must be checked out on a branch with a remote, it won't work for [events which checkout a commit](docs/concepts-guidelines.md#events-which-checkout-a-commit). 230 | 231 | ```yml 232 | steps: 233 | - uses: actions/checkout@v4 234 | - name: Create commits 235 | run: | 236 | git config user.name 'Peter Evans' 237 | git config user.email 'peter-evans@users.noreply.github.com' 238 | date +%s > report.txt 239 | git commit -am "Modify tracked file during workflow" 240 | date +%s > new-report.txt 241 | git add -A 242 | git commit -m "Add untracked file during workflow" 243 | - name: Uncommitted change 244 | run: date +%s > report.txt 245 | - name: Create Pull Request 246 | uses: peter-evans/create-pull-request@v7 247 | ``` 248 | 249 | ### Auto-merge 250 | 251 | Auto-merge can be enabled on a pull request allowing it to be automatically merged once requirements have been satisfied. 252 | See [enable-pull-request-automerge](https://github.com/peter-evans/enable-pull-request-automerge) action for usage details. 253 | 254 | ## Reference Example 255 | 256 | The following workflow sets many of the action's inputs for reference purposes. 257 | Check the [defaults](#action-inputs) to avoid setting inputs unnecessarily. 258 | 259 | See [examples](docs/examples.md) for more realistic use cases. 260 | 261 | ```yml 262 | jobs: 263 | createPullRequest: 264 | runs-on: ubuntu-latest 265 | steps: 266 | - uses: actions/checkout@v4 267 | 268 | - name: Make changes to pull request 269 | run: date +%s > report.txt 270 | 271 | - name: Create Pull Request 272 | id: cpr 273 | uses: peter-evans/create-pull-request@v7 274 | with: 275 | token: ${{ secrets.PAT }} 276 | commit-message: Update report 277 | committer: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 278 | author: ${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com> 279 | signoff: false 280 | branch: example-patches 281 | delete-branch: true 282 | title: '[Example] Update report' 283 | body: | 284 | Update report 285 | - Updated with *today's* date 286 | - Auto-generated by [create-pull-request][1] 287 | 288 | [1]: https://github.com/peter-evans/create-pull-request 289 | labels: | 290 | report 291 | automated pr 292 | assignees: peter-evans 293 | reviewers: peter-evans 294 | team-reviewers: | 295 | developers 296 | qa-team 297 | milestone: 1 298 | draft: false 299 | ``` 300 | 301 | An example based on the above reference configuration creates pull requests that look like this: 302 | 303 | ![Pull Request Example](docs/assets/pull-request-example.png) 304 | 305 | ## License 306 | 307 | [MIT](LICENSE) 308 | -------------------------------------------------------------------------------- /__test__/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -l 2 | set -euo pipefail 3 | 4 | # Save the working directory 5 | WORKINGDIR=$PWD 6 | 7 | # Create and serve a remote repo 8 | mkdir -p /git/remote/repos 9 | git config --global init.defaultBranch main 10 | git init --bare /git/remote/repos/test-base.git 11 | git daemon --verbose --enable=receive-pack --base-path=/git/remote --export-all /git/remote &>/dev/null & 12 | 13 | # Give the daemon time to start 14 | sleep 2 15 | 16 | # Create a local clone and make initial commits 17 | mkdir -p /git/local/repos 18 | git clone git://127.0.0.1/repos/test-base.git /git/local/repos/test-base 19 | cd /git/local/repos/test-base 20 | git config --global user.email "you@example.com" 21 | git config --global user.name "Your Name" 22 | echo "#test-base" > README→TEMP.md 23 | git add . 24 | git commit -m "initial commit" 25 | git commit --allow-empty -m "empty commit for tests" 26 | echo "#test-base :sparkles:" > README→TEMP.md 27 | git add . 28 | git commit -m "add sparkles" -m "Change description: 29 | - updates README→TEMP.md to add sparkles to the title" 30 | mv README→TEMP.md README.md 31 | git add . 32 | git commit -m "rename readme" 33 | git push -u 34 | git log -1 --pretty=oneline 35 | git config --global --unset user.email 36 | git config --global --unset user.name 37 | git config -l 38 | 39 | # Clone a server-side fork of the base repo 40 | cd $WORKINGDIR 41 | git clone --mirror git://127.0.0.1/repos/test-base.git /git/remote/repos/test-fork.git 42 | cd /git/remote/repos/test-fork.git 43 | git log -1 --pretty=oneline 44 | 45 | # Restore the working directory 46 | cd $WORKINGDIR 47 | 48 | # Execute integration tests 49 | jest int --runInBand 50 | -------------------------------------------------------------------------------- /__test__/git-command-manager.int.test.ts: -------------------------------------------------------------------------------- 1 | import {GitCommandManager} from '../lib/git-command-manager' 2 | 3 | const REPO_PATH = '/git/local/repos/test-base' 4 | 5 | describe('git-command-manager integration tests', () => { 6 | let git: GitCommandManager 7 | 8 | beforeAll(async () => { 9 | git = await GitCommandManager.create(REPO_PATH) 10 | await git.checkout('main') 11 | }) 12 | 13 | it('tests getCommit', async () => { 14 | const initialCommit = await git.getCommit('HEAD^^^') 15 | const emptyCommit = await git.getCommit('HEAD^^') 16 | const modifiedCommit = await git.getCommit('HEAD^') 17 | const headCommit = await git.getCommit('HEAD') 18 | 19 | expect(initialCommit.subject).toEqual('initial commit') 20 | expect(initialCommit.signed).toBeFalsy() 21 | expect(initialCommit.changes[0].mode).toEqual('100644') 22 | expect(initialCommit.changes[0].status).toEqual('A') 23 | expect(initialCommit.changes[0].path).toEqual('README→TEMP.md') // filename contains unicode 24 | 25 | expect(emptyCommit.subject).toEqual('empty commit for tests') 26 | expect(emptyCommit.tree).toEqual(initialCommit.tree) // empty commits have no tree and reference the parent's 27 | expect(emptyCommit.parents[0]).toEqual(initialCommit.sha) 28 | expect(emptyCommit.signed).toBeFalsy() 29 | expect(emptyCommit.changes).toEqual([]) 30 | 31 | expect(modifiedCommit.subject).toEqual('add sparkles') 32 | expect(modifiedCommit.parents[0]).toEqual(emptyCommit.sha) 33 | expect(modifiedCommit.signed).toBeFalsy() 34 | expect(modifiedCommit.changes[0].mode).toEqual('100644') 35 | expect(modifiedCommit.changes[0].status).toEqual('M') 36 | expect(modifiedCommit.changes[0].path).toEqual('README→TEMP.md') 37 | 38 | expect(headCommit.subject).toEqual('rename readme') 39 | expect(headCommit.parents[0]).toEqual(modifiedCommit.sha) 40 | expect(headCommit.signed).toBeFalsy() 41 | expect(headCommit.changes[0].mode).toEqual('100644') 42 | expect(headCommit.changes[0].status).toEqual('A') 43 | expect(headCommit.changes[0].path).toEqual('README.md') 44 | expect(headCommit.changes[1].mode).toEqual('100644') 45 | expect(headCommit.changes[1].status).toEqual('D') 46 | expect(headCommit.changes[1].path).toEqual('README→TEMP.md') 47 | }) 48 | }) 49 | -------------------------------------------------------------------------------- /__test__/git-config-helper.int.test.ts: -------------------------------------------------------------------------------- 1 | import {GitCommandManager} from '../lib/git-command-manager' 2 | import {GitConfigHelper} from '../lib/git-config-helper' 3 | 4 | const REPO_PATH = '/git/local/repos/test-base' 5 | 6 | const extraheaderConfigKey = 'http.https://127.0.0.1/.extraheader' 7 | 8 | describe('git-config-helper integration tests', () => { 9 | let git: GitCommandManager 10 | 11 | beforeAll(async () => { 12 | git = await GitCommandManager.create(REPO_PATH) 13 | }) 14 | 15 | it('tests save and restore with no persisted auth', async () => { 16 | const gitConfigHelper = await GitConfigHelper.create(git) 17 | await gitConfigHelper.close() 18 | }) 19 | 20 | it('tests configure and removal of auth', async () => { 21 | const gitConfigHelper = await GitConfigHelper.create(git) 22 | await gitConfigHelper.configureToken('github-token') 23 | expect(await git.configExists(extraheaderConfigKey)).toBeTruthy() 24 | expect(await git.getConfigValue(extraheaderConfigKey)).toEqual( 25 | 'AUTHORIZATION: basic eC1hY2Nlc3MtdG9rZW46Z2l0aHViLXRva2Vu' 26 | ) 27 | 28 | await gitConfigHelper.close() 29 | expect(await git.configExists(extraheaderConfigKey)).toBeFalsy() 30 | }) 31 | 32 | it('tests save and restore of persisted auth', async () => { 33 | const extraheaderConfigValue = 'AUTHORIZATION: basic ***persisted-auth***' 34 | await git.config(extraheaderConfigKey, extraheaderConfigValue) 35 | 36 | const gitConfigHelper = await GitConfigHelper.create(git) 37 | 38 | const exists = await git.configExists(extraheaderConfigKey) 39 | expect(exists).toBeFalsy() 40 | 41 | await gitConfigHelper.close() 42 | 43 | const configValue = await git.getConfigValue(extraheaderConfigKey) 44 | expect(configValue).toEqual(extraheaderConfigValue) 45 | 46 | const unset = await git.tryConfigUnset( 47 | extraheaderConfigKey, 48 | '^AUTHORIZATION:' 49 | ) 50 | expect(unset).toBeTruthy() 51 | }) 52 | 53 | it('tests not adding/removing the safe.directory config when it already exists', async () => { 54 | await git.config('safe.directory', '/another-value', true, true) 55 | 56 | const gitConfigHelper = await GitConfigHelper.create(git) 57 | 58 | expect( 59 | await git.configExists('safe.directory', '/another-value', true) 60 | ).toBeTruthy() 61 | 62 | await gitConfigHelper.close() 63 | 64 | const unset = await git.tryConfigUnset( 65 | 'safe.directory', 66 | '/another-value', 67 | true 68 | ) 69 | expect(unset).toBeTruthy() 70 | }) 71 | 72 | it('tests adding and removing the safe.directory config', async () => { 73 | const gitConfigHelper = await GitConfigHelper.create(git) 74 | 75 | expect( 76 | await git.configExists('safe.directory', REPO_PATH, true) 77 | ).toBeTruthy() 78 | 79 | await gitConfigHelper.close() 80 | 81 | expect( 82 | await git.configExists('safe.directory', REPO_PATH, true) 83 | ).toBeFalsy() 84 | }) 85 | }) 86 | -------------------------------------------------------------------------------- /__test__/git-config-helper.unit.test.ts: -------------------------------------------------------------------------------- 1 | import {GitConfigHelper} from '../lib/git-config-helper' 2 | 3 | describe('git-config-helper unit tests', () => { 4 | test('parseGitRemote successfully parses HTTPS remote URLs', async () => { 5 | const remote1 = GitConfigHelper.parseGitRemote( 6 | 'https://github.com/peter-evans/create-pull-request' 7 | ) 8 | expect(remote1.hostname).toEqual('github.com') 9 | expect(remote1.protocol).toEqual('HTTPS') 10 | expect(remote1.repository).toEqual('peter-evans/create-pull-request') 11 | 12 | const remote2 = GitConfigHelper.parseGitRemote( 13 | 'https://xxx:x-oauth-basic@github.com/peter-evans/create-pull-request' 14 | ) 15 | expect(remote2.hostname).toEqual('github.com') 16 | expect(remote2.protocol).toEqual('HTTPS') 17 | expect(remote2.repository).toEqual('peter-evans/create-pull-request') 18 | 19 | const remote3 = GitConfigHelper.parseGitRemote( 20 | 'https://github.com/peter-evans/create-pull-request.git' 21 | ) 22 | expect(remote3.hostname).toEqual('github.com') 23 | expect(remote3.protocol).toEqual('HTTPS') 24 | expect(remote3.repository).toEqual('peter-evans/create-pull-request') 25 | 26 | const remote4 = GitConfigHelper.parseGitRemote( 27 | 'https://github.com/peter-evans/ungit' 28 | ) 29 | expect(remote4.hostname).toEqual('github.com') 30 | expect(remote4.protocol).toEqual('HTTPS') 31 | expect(remote4.repository).toEqual('peter-evans/ungit') 32 | 33 | const remote5 = GitConfigHelper.parseGitRemote( 34 | 'https://github.com/peter-evans/ungit.git' 35 | ) 36 | expect(remote5.hostname).toEqual('github.com') 37 | expect(remote5.protocol).toEqual('HTTPS') 38 | expect(remote5.repository).toEqual('peter-evans/ungit') 39 | 40 | const remote6 = GitConfigHelper.parseGitRemote( 41 | 'https://github.internal.company/peter-evans/create-pull-request' 42 | ) 43 | expect(remote6.hostname).toEqual('github.internal.company') 44 | expect(remote6.protocol).toEqual('HTTPS') 45 | expect(remote6.repository).toEqual('peter-evans/create-pull-request') 46 | }) 47 | 48 | test('parseGitRemote successfully parses SSH remote URLs', async () => { 49 | const remote1 = GitConfigHelper.parseGitRemote( 50 | 'git@github.com:peter-evans/create-pull-request.git' 51 | ) 52 | expect(remote1.hostname).toEqual('github.com') 53 | expect(remote1.protocol).toEqual('SSH') 54 | expect(remote1.repository).toEqual('peter-evans/create-pull-request') 55 | 56 | const remote2 = GitConfigHelper.parseGitRemote( 57 | 'git@github.com:peter-evans/ungit.git' 58 | ) 59 | expect(remote2.hostname).toEqual('github.com') 60 | expect(remote2.protocol).toEqual('SSH') 61 | expect(remote2.repository).toEqual('peter-evans/ungit') 62 | 63 | const remote3 = GitConfigHelper.parseGitRemote( 64 | 'git@github.internal.company:peter-evans/create-pull-request.git' 65 | ) 66 | expect(remote3.hostname).toEqual('github.internal.company') 67 | expect(remote3.protocol).toEqual('SSH') 68 | expect(remote3.repository).toEqual('peter-evans/create-pull-request') 69 | }) 70 | 71 | test('parseGitRemote successfully parses GIT remote URLs', async () => { 72 | // Unauthenticated git protocol for integration tests only 73 | const remote1 = GitConfigHelper.parseGitRemote( 74 | 'git://127.0.0.1/repos/test-base.git' 75 | ) 76 | expect(remote1.hostname).toEqual('127.0.0.1') 77 | expect(remote1.protocol).toEqual('GIT') 78 | expect(remote1.repository).toEqual('repos/test-base') 79 | }) 80 | 81 | test('parseGitRemote fails to parse a remote URL', async () => { 82 | const remoteUrl = 'https://github.com/peter-evans' 83 | try { 84 | GitConfigHelper.parseGitRemote(remoteUrl) 85 | // Fail the test if an error wasn't thrown 86 | expect(true).toEqual(false) 87 | } catch (e: any) { 88 | expect(e.message).toEqual( 89 | `The format of '${remoteUrl}' is not a valid GitHub repository URL` 90 | ) 91 | } 92 | }) 93 | }) 94 | -------------------------------------------------------------------------------- /__test__/integration-tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | IMAGE="cpr-integration-tests:latest" 5 | ARG1=${1:-} 6 | 7 | if [[ "$(docker images -q $IMAGE 2> /dev/null)" == "" || $ARG1 == "build" ]]; then 8 | echo "Building Docker image $IMAGE ..." 9 | 10 | cat > Dockerfile << EOF 11 | FROM node:20-alpine 12 | RUN apk --no-cache add git git-daemon 13 | RUN npm install jest jest-environment-jsdom --global 14 | WORKDIR /cpr 15 | COPY __test__/entrypoint.sh /entrypoint.sh 16 | ENTRYPOINT ["/entrypoint.sh"] 17 | EOF 18 | 19 | docker build --no-cache -t $IMAGE . 20 | rm Dockerfile 21 | fi 22 | 23 | docker run -v $PWD:/cpr $IMAGE 24 | -------------------------------------------------------------------------------- /__test__/utils.unit.test.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path' 2 | import * as utils from '../lib/utils' 3 | 4 | const originalGitHubWorkspace = process.env['GITHUB_WORKSPACE'] 5 | 6 | describe('utils tests', () => { 7 | beforeAll(() => { 8 | // GitHub workspace 9 | process.env['GITHUB_WORKSPACE'] = __dirname 10 | }) 11 | 12 | afterAll(() => { 13 | // Restore GitHub workspace 14 | delete process.env['GITHUB_WORKSPACE'] 15 | if (originalGitHubWorkspace) { 16 | process.env['GITHUB_WORKSPACE'] = originalGitHubWorkspace 17 | } 18 | }) 19 | 20 | test('getStringAsArray splits string input by newlines and commas', async () => { 21 | const array = utils.getStringAsArray('1, 2, 3\n4, 5, 6') 22 | expect(array.length).toEqual(6) 23 | 24 | const array2 = utils.getStringAsArray('') 25 | expect(array2.length).toEqual(0) 26 | }) 27 | 28 | test('stripOrgPrefixFromTeams strips org prefixes correctly', async () => { 29 | const array = utils.stripOrgPrefixFromTeams([ 30 | 'org/team1', 31 | 'org/team2', 32 | 'team3' 33 | ]) 34 | expect(array.length).toEqual(3) 35 | expect(array[0]).toEqual('team1') 36 | expect(array[1]).toEqual('team2') 37 | expect(array[2]).toEqual('team3') 38 | }) 39 | 40 | test('getRepoPath successfully returns the path to the repository', async () => { 41 | expect(utils.getRepoPath()).toEqual(process.env['GITHUB_WORKSPACE']) 42 | expect(utils.getRepoPath('foo')).toEqual( 43 | path.resolve(process.env['GITHUB_WORKSPACE'] || '', 'foo') 44 | ) 45 | }) 46 | 47 | test('getRemoteUrl successfully returns remote URLs', async () => { 48 | const url1 = utils.getRemoteUrl( 49 | 'HTTPS', 50 | 'github.com', 51 | 'peter-evans/create-pull-request' 52 | ) 53 | expect(url1).toEqual('https://github.com/peter-evans/create-pull-request') 54 | 55 | const url2 = utils.getRemoteUrl( 56 | 'SSH', 57 | 'github.com', 58 | 'peter-evans/create-pull-request' 59 | ) 60 | expect(url2).toEqual('git@github.com:peter-evans/create-pull-request.git') 61 | 62 | const url3 = utils.getRemoteUrl( 63 | 'HTTPS', 64 | 'mygithubserver.com', 65 | 'peter-evans/create-pull-request' 66 | ) 67 | expect(url3).toEqual( 68 | 'https://mygithubserver.com/peter-evans/create-pull-request' 69 | ) 70 | }) 71 | 72 | test('secondsSinceEpoch returns the number of seconds since the Epoch', async () => { 73 | const seconds = `${utils.secondsSinceEpoch()}` 74 | expect(seconds.length).toEqual(10) 75 | }) 76 | 77 | test('randomString returns strings of length 7', async () => { 78 | for (let i = 0; i < 1000; i++) { 79 | expect(utils.randomString().length).toEqual(7) 80 | } 81 | }) 82 | 83 | test('parseDisplayNameEmail successfully parses display name email formats', async () => { 84 | const parsed1 = utils.parseDisplayNameEmail('abc def ') 85 | expect(parsed1.name).toEqual('abc def') 86 | expect(parsed1.email).toEqual('abc@def.com') 87 | 88 | const parsed2 = utils.parseDisplayNameEmail( 89 | 'github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>' 90 | ) 91 | expect(parsed2.name).toEqual('github-actions[bot]') 92 | expect(parsed2.email).toEqual( 93 | '41898282+github-actions[bot]@users.noreply.github.com' 94 | ) 95 | }) 96 | 97 | test('parseDisplayNameEmail fails to parse display name email formats', async () => { 98 | const displayNameEmail1 = 'abc@def.com' 99 | try { 100 | utils.parseDisplayNameEmail(displayNameEmail1) 101 | // Fail the test if an error wasn't thrown 102 | expect(true).toEqual(false) 103 | } catch (e: any) { 104 | expect(e.message).toEqual( 105 | `The format of '${displayNameEmail1}' is not a valid email address with display name` 106 | ) 107 | } 108 | 109 | const displayNameEmail2 = ' < >' 110 | try { 111 | utils.parseDisplayNameEmail(displayNameEmail2) 112 | // Fail the test if an error wasn't thrown 113 | expect(true).toEqual(false) 114 | } catch (e: any) { 115 | expect(e.message).toEqual( 116 | `The format of '${displayNameEmail2}' is not a valid email address with display name` 117 | ) 118 | } 119 | }) 120 | }) 121 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | name: 'Create Pull Request' 2 | description: 'Creates a pull request for changes to your repository in the actions workspace' 3 | inputs: 4 | token: 5 | description: 'The token that the action will use to create and update the pull request.' 6 | default: ${{ github.token }} 7 | branch-token: 8 | description: > 9 | The token that the action will use to create and update the branch. 10 | Defaults to the value of `token`. 11 | path: 12 | description: > 13 | Relative path under $GITHUB_WORKSPACE to the repository. 14 | Defaults to $GITHUB_WORKSPACE. 15 | add-paths: 16 | description: > 17 | A comma or newline-separated list of file paths to commit. 18 | Paths should follow git's pathspec syntax. 19 | Defaults to adding all new and modified files. 20 | commit-message: 21 | description: 'The message to use when committing changes.' 22 | default: '[create-pull-request] automated change' 23 | committer: 24 | description: > 25 | The committer name and email address in the format `Display Name `. 26 | Defaults to the GitHub Actions bot user. 27 | default: 'github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>' 28 | author: 29 | description: > 30 | The author name and email address in the format `Display Name `. 31 | Defaults to the user who triggered the workflow run. 32 | default: '${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com>' 33 | signoff: 34 | description: 'Add `Signed-off-by` line by the committer at the end of the commit log message.' 35 | default: false 36 | branch: 37 | description: 'The pull request branch name.' 38 | default: 'create-pull-request/patch' 39 | delete-branch: 40 | description: > 41 | Delete the `branch` if it doesn't have an active pull request associated with it. 42 | default: false 43 | branch-suffix: 44 | description: 'The branch suffix type when using the alternative branching strategy.' 45 | base: 46 | description: > 47 | The pull request base branch. 48 | Defaults to the branch checked out in the workflow. 49 | push-to-fork: 50 | description: > 51 | A fork of the checked out parent repository to which the pull request branch will be pushed. 52 | e.g. `owner/repo-fork`. 53 | The pull request will be created to merge the fork's branch into the parent's base. 54 | sign-commits: 55 | description: 'Sign commits as `github-actions[bot]` when using `GITHUB_TOKEN`, or your own bot when using GitHub App tokens.' 56 | default: false 57 | title: 58 | description: 'The title of the pull request.' 59 | default: 'Changes by create-pull-request action' 60 | body: 61 | description: 'The body of the pull request.' 62 | default: 'Automated changes by [create-pull-request](https://github.com/peter-evans/create-pull-request) GitHub action' 63 | body-path: 64 | description: 'The path to a file containing the pull request body. Takes precedence over `body`.' 65 | labels: 66 | description: 'A comma or newline separated list of labels.' 67 | assignees: 68 | description: 'A comma or newline separated list of assignees (GitHub usernames).' 69 | reviewers: 70 | description: 'A comma or newline separated list of reviewers (GitHub usernames) to request a review from.' 71 | team-reviewers: 72 | description: > 73 | A comma or newline separated list of GitHub teams to request a review from. 74 | Note that a `repo` scoped Personal Access Token (PAT) may be required. 75 | milestone: 76 | description: 'The number of the milestone to associate the pull request with.' 77 | draft: 78 | description: > 79 | Create a draft pull request. 80 | Valid values are `true` (only on create), `always-true` (on create and update), and `false`. 81 | default: false 82 | maintainer-can-modify: 83 | description: 'Indicates whether maintainers can modify the pull request.' 84 | default: true 85 | outputs: 86 | pull-request-number: 87 | description: 'The pull request number' 88 | pull-request-url: 89 | description: 'The URL of the pull request.' 90 | pull-request-operation: 91 | description: 'The pull request operation performed by the action, `created`, `updated` or `closed`.' 92 | pull-request-head-sha: 93 | description: 'The commit SHA of the pull request branch.' 94 | pull-request-branch: 95 | description: 'The pull request branch name' 96 | runs: 97 | using: 'node20' 98 | main: 'dist/index.js' 99 | branding: 100 | icon: 'git-pull-request' 101 | color: 'gray-dark' 102 | -------------------------------------------------------------------------------- /dist/790.index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.id = 790; 3 | exports.ids = [790]; 4 | exports.modules = { 5 | 6 | /***/ 790: 7 | /***/ ((__unused_webpack_module, exports, __webpack_require__) => { 8 | 9 | var N=Object.defineProperty;var c=(_,a)=>N(_,"name",{value:a,configurable:!0});__webpack_require__(3024),__webpack_require__(6760);const node=__webpack_require__(117);__webpack_require__(7067),__webpack_require__(4708),__webpack_require__(8522),__webpack_require__(7075),__webpack_require__(4573),__webpack_require__(7975),__webpack_require__(3465),__webpack_require__(3136),__webpack_require__(7030);let s=0;const S={START_BOUNDARY:s++,HEADER_FIELD_START:s++,HEADER_FIELD:s++,HEADER_VALUE_START:s++,HEADER_VALUE:s++,HEADER_VALUE_ALMOST_DONE:s++,HEADERS_ALMOST_DONE:s++,PART_DATA_START:s++,PART_DATA:s++,END:s++};let f=1;const F={PART_BOUNDARY:f,LAST_BOUNDARY:f*=2},LF=10,CR=13,SPACE=32,HYPHEN=45,COLON=58,A=97,Z=122,lower=c(_=>_|32,"lower"),noop=c(()=>{},"noop");class MultipartParser{static{c(this,"MultipartParser")}constructor(a){this.index=0,this.flags=0,this.onHeaderEnd=noop,this.onHeaderField=noop,this.onHeadersEnd=noop,this.onHeaderValue=noop,this.onPartBegin=noop,this.onPartData=noop,this.onPartEnd=noop,this.boundaryChars={},a=`\r 10 | --`+a;const t=new Uint8Array(a.length);for(let n=0;n{this[D+"Mark"]=t},"mark"),i=c(D=>{delete this[D+"Mark"]},"clear"),T=c((D,p,R,g)=>{(p===void 0||p!==R)&&this[D](g&&g.subarray(p,R))},"callback"),L=c((D,p)=>{const R=D+"Mark";R in this&&(p?(T(D,this[R],t,a),delete this[R]):(T(D,this[R],a.length,a),this[R]=0))},"dataCallback");for(t=0;tZ)return;break;case S.HEADER_VALUE_START:if(r===SPACE)break;u("onHeaderValue"),o=S.HEADER_VALUE;case S.HEADER_VALUE:r===CR&&(L("onHeaderValue",!0),T("onHeaderEnd"),o=S.HEADER_VALUE_ALMOST_DONE);break;case S.HEADER_VALUE_ALMOST_DONE:if(r!==LF)return;o=S.HEADER_FIELD_START;break;case S.HEADERS_ALMOST_DONE:if(r!==LF)return;T("onHeadersEnd"),o=S.PART_DATA_START;break;case S.PART_DATA_START:o=S.PART_DATA,u("onPartData");case S.PART_DATA:if(E=e,e===0){for(t+=m;t0)d[e-1]=r;else if(E>0){const D=new Uint8Array(d.buffer,d.byteOffset,d.byteLength);T("onPartData",0,E,D),E=0,u("onPartData"),t--}break;case S.END:break;default:throw new Error(`Unexpected state entered: ${o}`)}L("onHeaderField"),L("onHeaderValue"),L("onPartData"),this.index=e,this.state=o,this.flags=l}end(){if(this.state===S.HEADER_FIELD_START&&this.index===0||this.state===S.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==S.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}function _fileName(_){const a=_.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!a)return;const t=a[2]||a[3]||"";let n=t.slice(t.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(E,d)=>String.fromCharCode(d)),n}c(_fileName,"_fileName");async function toFormData(_,a){if(!/multipart/i.test(a))throw new TypeError("Failed to fetch");const t=a.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");const n=new MultipartParser(t[1]||t[2]);let E,d,h,H,e,o;const l=[],b=new node.FormData,m=c(i=>{h+=u.decode(i,{stream:!0})},"onPartData"),O=c(i=>{l.push(i)},"appendToFile"),r=c(()=>{const i=new node.File(l,o,{type:e});b.append(H,i)},"appendFileToFormData"),P=c(()=>{b.append(H,h)},"appendEntryToFormData"),u=new TextDecoder("utf-8");u.decode(),n.onPartBegin=function(){n.onPartData=m,n.onPartEnd=P,E="",d="",h="",H="",e="",o=null,l.length=0},n.onHeaderField=function(i){E+=u.decode(i,{stream:!0})},n.onHeaderValue=function(i){d+=u.decode(i,{stream:!0})},n.onHeaderEnd=function(){if(d+=u.decode(),E=E.toLowerCase(),E==="content-disposition"){const i=d.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);i&&(H=i[2]||i[3]||""),o=_fileName(d),o&&(n.onPartData=O,n.onPartEnd=r)}else E==="content-type"&&(e=d);d="",E=""};for await(const i of _)n.write(i);return n.end(),b}c(toFormData,"toFormData"),exports.toFormData=toFormData; 11 | 12 | 13 | /***/ }) 14 | 15 | }; 16 | ; -------------------------------------------------------------------------------- /docs/assets/cpr-gitgraph.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | create-pull-request GitHub action 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /docs/assets/cpr-gitgraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peter-evans/create-pull-request/88ed63ce144f5372efe9f999d8bb224f582d98d9/docs/assets/cpr-gitgraph.png -------------------------------------------------------------------------------- /docs/assets/logo.svg: -------------------------------------------------------------------------------- 1 | git-pull-request 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /docs/assets/pull-request-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peter-evans/create-pull-request/88ed63ce144f5372efe9f999d8bb224f582d98d9/docs/assets/pull-request-example.png -------------------------------------------------------------------------------- /docs/common-issues.md: -------------------------------------------------------------------------------- 1 | # Common issues 2 | 3 | - [Troubleshooting](#troubleshooting) 4 | - [Create using an existing branch as the PR branch](#create-using-an-existing-branch-as-the-pr-branch) 5 | - [Frequently requested features](#use-case-create-a-pull-request-to-update-x-on-release) 6 | - [Disable force updates to existing PR branches](#disable-force-updates-to-existing-pr-branches) 7 | - [Add a no-verify option to bypass git hooks](#add-a-no-verify-option-to-bypass-git-hooks) 8 | 9 | ## Troubleshooting 10 | 11 | ### Create using an existing branch as the PR branch 12 | 13 | A common point of confusion is to try and use an existing branch containing changes to raise in a PR as the `branch` input. This will not work because the action is primarily designed to be used in workflows where the PR branch does not exist yet. The action creates and manages the PR branch itself. 14 | 15 | If you have an existing branch that you just want to create a PR for, then I recommend using the official [GitHub CLI](https://cli.github.com/manual/gh_pr_create) in a workflow step. 16 | 17 | Alternatively, if you are trying to keep a branch up to date with another branch, then you can follow [this example](https://github.com/peter-evans/create-pull-request/blob/main/docs/examples.md#keep-a-branch-up-to-date-with-another). 18 | 19 | ## Frequently requested features 20 | 21 | ### Disable force updates to existing PR branches 22 | 23 | This behaviour is fundamental to how the action works and is a conscious design decision. The "rule" that I based this design on is that when a workflow executes the action to create or update a PR, the result of those two possible actions should never be different. The easiest way to maintain that consistency is to rebase the PR branch and force push it. 24 | 25 | If you want to avoid this behaviour there are some things that might work depending on your use case: 26 | - Check if the pull request branch exists in a separate step before the action runs and act accordingly. 27 | - Use the [alternative strategy](https://github.com/peter-evans/create-pull-request#alternative-strategy---always-create-a-new-pull-request-branch) of always creating a new PR that won't be updated by the action. 28 | - [Create your own commits](https://github.com/peter-evans/create-pull-request#create-your-own-commits) each time the action is created/updated. 29 | 30 | ### Add a no-verify option to bypass git hooks 31 | 32 | Presently, there is no plan to add this feature to the action. 33 | The reason is that I'm trying very hard to keep the interface for this action to a minimum to prevent it becoming bloated and complicated. 34 | 35 | Git hooks must be installed after a repository is checked out in order for them to work. 36 | So the straightforward solution is to just not install them during the workflow where this action is used. 37 | 38 | - If hooks are automatically enabled by a framework, use an option provided by the framework to disable them. For example, for Husky users, they can be disabled with the `--ignore-scripts` flag, or by setting the `HUSKY` environment variable when the action runs. 39 | ```yml 40 | uses: peter-evans/create-pull-request@v7 41 | env: 42 | HUSKY: '0' 43 | ``` 44 | - If hooks are installed in a script, then add a condition checking if the `CI` environment variable exists. 45 | ```sh 46 | #!/bin/sh 47 | 48 | [ -n "$CI" ] && exit 0 49 | ``` 50 | - If preventing the hooks installing is problematic, just delete them in a workflow step before the action runs. 51 | ```yml 52 | - run: rm .git/hooks -rf 53 | ``` 54 | -------------------------------------------------------------------------------- /docs/concepts-guidelines.md: -------------------------------------------------------------------------------- 1 | # Concepts, guidelines and advanced usage 2 | 3 | This document covers terminology, how the action works, general usage guidelines, and advanced usage. 4 | 5 | - [Terminology](#terminology) 6 | - [Events and checkout](#events-and-checkout) 7 | - [How the action works](#how-the-action-works) 8 | - [Guidelines](#guidelines) 9 | - [Providing a consistent base](#providing-a-consistent-base) 10 | - [Events which checkout a commit](#events-which-checkout-a-commit) 11 | - [Restrictions on repository forks](#restrictions-on-repository-forks) 12 | - [Triggering further workflow runs](#triggering-further-workflow-runs) 13 | - [Security](#security) 14 | - [Advanced usage](#advanced-usage) 15 | - [Creating pull requests in a remote repository](#creating-pull-requests-in-a-remote-repository) 16 | - [Push using SSH (deploy keys)](#push-using-ssh-deploy-keys) 17 | - [Push pull request branches to a fork](#push-pull-request-branches-to-a-fork) 18 | - [Pushing to a fork with fine-grained permissions](#pushing-to-a-fork-with-fine-grained-permissions) 19 | - [Authenticating with GitHub App generated tokens](#authenticating-with-github-app-generated-tokens) 20 | - [Creating pull requests in a remote repository using GitHub App generated tokens](#creating-pull-requests-in-a-remote-repository-using-github-app-generated-tokens) 21 | - [Commit signing](#commit-signing) 22 | - [Commit signature verification for bots](#commit-signature-verification-for-bots) 23 | - [GPG commit signature verification](#gpg-commit-signature-verification) 24 | - [Running in a container or on self-hosted runners](#running-in-a-container-or-on-self-hosted-runners) 25 | 26 | ## Terminology 27 | 28 | [Pull requests](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests#about-pull-requests) are proposed changes to a repository branch that can be reviewed by a repository's collaborators before being accepted or rejected. 29 | 30 | A pull request references two branches: 31 | 32 | - The `base` of a pull request is the branch you intend to change once the proposed changes are merged. 33 | - The `branch` of a pull request represents what you intend the `base` to look like when merged. It is the `base` branch *plus* changes that have been made to it. 34 | 35 | ## Events and checkout 36 | 37 | This action expects repositories to be checked out with the official GitHub Actions [checkout](https://github.com/actions/checkout) action. 38 | For each [event type](https://docs.github.com/en/actions/reference/events-that-trigger-workflows) there is a default `GITHUB_SHA` that will be checked out. 39 | 40 | The default can be overridden by specifying a `ref` on checkout. 41 | 42 | ```yml 43 | - uses: actions/checkout@v4 44 | with: 45 | ref: develop 46 | ``` 47 | 48 | ## How the action works 49 | 50 | Unless the `base` input is supplied, the action expects the target repository to be checked out on the pull request `base`—the branch you intend to modify with the proposed changes. 51 | 52 | Workflow steps: 53 | 54 | 1. Checkout the `base` branch 55 | 2. Make changes 56 | 3. Execute `create-pull-request` action 57 | 58 | The following git diagram shows how the action creates and updates a pull request branch. 59 | 60 | ![Create Pull Request GitGraph](assets/cpr-gitgraph.png) 61 | 62 | ## Guidelines 63 | 64 | ### Providing a consistent base 65 | 66 | For the action to work correctly it should be executed in a workflow that checks out a *consistent* base branch. This will be the base of the pull request unless overridden with the `base` input. 67 | 68 | This means your workflow should be consistently checking out the branch that you intend to modify once the PR is merged. 69 | 70 | In the following example, the [`push`](https://docs.github.com/en/actions/reference/events-that-trigger-workflows#push) and [`create`](https://docs.github.com/en/actions/reference/events-that-trigger-workflows#create) events both trigger the same workflow. This will cause the checkout action to checkout inconsistent branches and commits. Do *not* do this. It will cause multiple pull requests to be created for each additional `base` the action is executed against. 71 | 72 | ```yml 73 | on: 74 | push: 75 | create: 76 | jobs: 77 | example: 78 | runs-on: ubuntu-latest 79 | steps: 80 | - uses: actions/checkout@v4 81 | ``` 82 | 83 | There may be use cases where it makes sense to execute the workflow on a branch that is not the base of the pull request. In these cases, the base branch can be specified with the `base` action input. The action will attempt to rebase changes made during the workflow on to the actual base. 84 | 85 | ### Events which checkout a commit 86 | 87 | The [default checkout](#events-and-checkout) for the majority of events will leave the repository checked out on a branch. 88 | However, some events such as `release` and `pull_request` will leave the repository in a "detached HEAD" state. 89 | This is because they checkout a commit, not a branch. 90 | In these cases, you *must supply* the `base` input so the action can rebase changes made during the workflow for the pull request. 91 | 92 | Workflows triggered by [`pull_request`](https://docs.github.com/en/actions/reference/events-that-trigger-workflows#pull_request) events will by default check out a merge commit. Set the `base` input as follows to base the new pull request on the current pull request's branch. 93 | 94 | ```yml 95 | - uses: peter-evans/create-pull-request@v7 96 | with: 97 | base: ${{ github.head_ref }} 98 | ``` 99 | 100 | Workflows triggered by [`release`](https://docs.github.com/en/actions/reference/events-that-trigger-workflows#release) events will by default check out a tag. For most use cases, you will need to set the `base` input to the branch name of the tagged commit. 101 | 102 | ```yml 103 | - uses: peter-evans/create-pull-request@v7 104 | with: 105 | base: main 106 | ``` 107 | 108 | ### Restrictions on repository forks 109 | 110 | GitHub Actions have imposed restrictions on workflow runs triggered by public repository forks. 111 | Private repositories can be configured to [enable workflows](https://docs.github.com/en/github/administering-a-repository/disabling-or-limiting-github-actions-for-a-repository#enabling-workflows-for-private-repository-forks) from forks to run without restriction. 112 | 113 | The restrictions apply to the `pull_request` event triggered by a fork opening a pull request in the upstream repository. 114 | 115 | - Events from forks cannot access secrets, except for the default `GITHUB_TOKEN`. 116 | > With the exception of GITHUB_TOKEN, secrets are not passed to the runner when a workflow is triggered from a forked repository. 117 | 118 | [GitHub Actions: Using encrypted secrets in a workflow](https://docs.github.com/en/actions/configuring-and-managing-workflows/creating-and-storing-encrypted-secrets#using-encrypted-secrets-in-a-workflow) 119 | 120 | - The `GITHUB_TOKEN` has read-only access when an event is triggered by a forked repository. 121 | 122 | [GitHub Actions: Permissions for the GITHUB_TOKEN](https://docs.github.com/en/actions/configuring-and-managing-workflows/authenticating-with-the-github_token#permissions-for-the-github_token) 123 | 124 | These restrictions mean that during a `pull_request` event triggered by a forked repository, actions have no write access to GitHub resources and will fail on any attempt. 125 | 126 | A job condition can be added to prevent workflows from executing when triggered by a repository fork. 127 | 128 | ```yml 129 | on: pull_request 130 | jobs: 131 | example: 132 | runs-on: ubuntu-latest 133 | # Check if the event is not triggered by a fork 134 | if: github.event.pull_request.head.repo.full_name == github.repository 135 | ``` 136 | 137 | For further reading regarding the security of pull requests, see this GitHub blog post titled [Keeping your GitHub Actions and workflows secure: Preventing pwn requests](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/) 138 | 139 | ### Triggering further workflow runs 140 | 141 | Pull requests created by the action using the default `GITHUB_TOKEN` cannot trigger other workflows. If you have `on: pull_request` or `on: push` workflows acting as checks on pull requests, they will not run. 142 | 143 | > When you use the repository's `GITHUB_TOKEN` to perform tasks, events triggered by the `GITHUB_TOKEN` will not create a new workflow run. This prevents you from accidentally creating recursive workflow runs. For example, if a workflow run pushes code using the repository's `GITHUB_TOKEN`, a new workflow will not run even when the repository contains a workflow configured to run when `push` events occur. 144 | 145 | [GitHub Actions: Triggering a workflow from a workflow](https://docs.github.com/en/actions/using-workflows/triggering-a-workflow#triggering-a-workflow-from-a-workflow) 146 | 147 | #### Workarounds to trigger further workflow runs 148 | 149 | There are a number of workarounds with different pros and cons. 150 | 151 | - Use the default `GITHUB_TOKEN` and allow the action to create pull requests that have no checks enabled. Manually close pull requests and immediately reopen them. This will enable `on: pull_request` workflows to run and be added as checks. To prevent merging of pull requests without checks erroneously, use [branch protection rules](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests). 152 | 153 | - Create draft pull requests by setting the `draft: always-true` input, and configure your workflow to trigger `ready_for_review` in `on: pull_request`. The workflow will run when users manually click the "Ready for review" button on the draft pull requests. If the pull request is updated by the action, the `always-true` mode ensures that the pull request will be converted back to a draft. 154 | 155 | - Use a [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) created on an account that has write access to the repository that pull requests are being created in. This is the standard workaround and [recommended by GitHub](https://docs.github.com/en/actions/using-workflows/triggering-a-workflow#triggering-a-workflow-from-a-workflow). It's advisable to use a dedicated [machine account](https://docs.github.com/en/github/site-policy/github-terms-of-service#3-account-requirements) that has collaborator access to the repository, rather than creating a PAT on a personal user account. Also note that because the account that owns the PAT will be the creator of pull requests, that user account will be unable to perform actions such as request changes or approve the pull request. 156 | 157 | - Use [SSH (deploy keys)](#push-using-ssh-deploy-keys) to push the pull request branch. This is arguably more secure than using a PAT because deploy keys can be set per repository. However, this method will only trigger `on: push` workflows. 158 | 159 | - Use a [machine account that creates pull requests from its own fork](#push-pull-request-branches-to-a-fork). This is the most secure because the PAT created only grants access to the machine account's fork, not the main repository. This method will trigger `on: pull_request` workflows to run. Workflows triggered `on: push` will not run because the push event is in the fork. 160 | 161 | - Use a [GitHub App to generate a token](#authenticating-with-github-app-generated-tokens) that can be used with this action. GitHub App generated tokens are more secure than using a Classic PAT because access permissions can be set with finer granularity and are scoped to only repositories where the App is installed. This method will trigger both `on: push` and `on: pull_request` workflows. 162 | 163 | ### Security 164 | 165 | From a security perspective it's good practice to fork third-party actions, review the code, and use your fork of the action in workflows. 166 | By using third-party actions directly the risk exists that it could be modified to do something malicious, such as capturing secrets. 167 | 168 | Alternatively, use the action directly and reference the commit hash for the version you want to target. 169 | ```yml 170 | - uses: thirdparty/foo-action@172ec762f2ac8e050062398456fccd30444f8f30 171 | ``` 172 | 173 | This action uses [ncc](https://github.com/vercel/ncc) to compile the Node.js code and dependencies into a single JavaScript file under the [dist](https://github.com/peter-evans/create-pull-request/tree/main/dist) directory. 174 | 175 | ## Advanced usage 176 | 177 | ### Creating pull requests in a remote repository 178 | 179 | Checking out a branch from a different repository from where the workflow is executing will make *that repository* the target for the created pull request. In this case, the `GITHUB_TOKEN` will not work and one of the other [token options](../README.md#token) must be used. 180 | 181 | ```yml 182 | - uses: actions/checkout@v4 183 | with: 184 | token: ${{ secrets.PAT }} 185 | repository: owner/repo 186 | 187 | # Make changes to pull request here 188 | 189 | - uses: peter-evans/create-pull-request@v7 190 | with: 191 | token: ${{ secrets.PAT }} 192 | ``` 193 | 194 | ### Push using SSH (deploy keys) 195 | 196 | [Deploy keys](https://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys) can be set per repository and so are arguably more secure than using a Classic [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token). 197 | Allowing the action to push with a configured deploy key will trigger `on: push` workflows. This makes it an alternative to using a PAT to trigger checks for pull requests. 198 | 199 | > [!NOTE] 200 | > - You cannot use deploy keys alone to [create a pull request in a remote repository](#creating-pull-requests-in-a-remote-repository) because then using a PAT would become a requirement. 201 | > This method only makes sense if creating a pull request in the repository where the workflow is running. 202 | > - You cannot use deploy keys with [commit signature verification for bots](#commit-signature-verification-for-bots) (`sign-commits: true`). 203 | 204 | How to use SSH (deploy keys) with create-pull-request action: 205 | 206 | 1. [Create a new SSH key pair](https://docs.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#generating-a-new-ssh-key) for your repository. Do not set a passphrase. 207 | 2. Copy the contents of the public key (.pub file) to a new repository [deploy key](https://developer.github.com/v3/guides/managing-deploy-keys/#deploy-keys) and check the box to "Allow write access." 208 | 3. Add a secret to the repository containing the entire contents of the private key. 209 | 4. As shown in the example below, configure `actions/checkout` to use the deploy key you have created. 210 | 211 | ```yml 212 | steps: 213 | - uses: actions/checkout@v4 214 | with: 215 | ssh-key: ${{ secrets.SSH_PRIVATE_KEY }} 216 | 217 | # Make changes to pull request here 218 | 219 | - name: Create Pull Request 220 | uses: peter-evans/create-pull-request@v7 221 | ``` 222 | 223 | ### Push pull request branches to a fork 224 | 225 | Instead of pushing pull request branches to the repository you want to update, you can push them to a fork of that repository. 226 | This allows you to employ the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege) by using a dedicated user acting as a [machine account](https://docs.github.com/en/github/site-policy/github-terms-of-service#3-account-requirements). 227 | This user only has `read` access to the main repository. 228 | It will use their own fork to push code and create the pull request. 229 | 230 | > [!NOTE] 231 | > If you choose to not give the machine account `write` access to the parent repository, the following inputs cannot be used: `labels`, `assignees`, `reviewers`, `team-reviewers` and `milestone`. 232 | 233 | 1. Create a new GitHub user and login. 234 | 2. Fork the repository that you will be creating pull requests in. 235 | 3. Create a Classic [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) with `repo` and `workflow` scopes. 236 | 4. Logout and log back into your main user account. 237 | 5. Add a secret to your repository containing the above PAT. 238 | 6. As shown in the following example workflow, set the `push-to-fork` input to the full repository name of the fork. 239 | 240 | ```yaml 241 | - uses: actions/checkout@v4 242 | 243 | # Make changes to pull request here 244 | 245 | - uses: peter-evans/create-pull-request@v7 246 | with: 247 | token: ${{ secrets.MACHINE_USER_PAT }} 248 | push-to-fork: machine-user/fork-of-repository 249 | ``` 250 | 251 | > [!TIP] 252 | > You can also combine `push-to-fork` with [creating pull requests in a remote repository](#creating-pull-requests-in-a-remote-repository). 253 | 254 | #### Pushing to a fork with fine-grained permissions 255 | 256 | Using a fine-grained [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) or [GitHub App](#authenticating-with-github-app-generated-tokens) with `push-to-fork` can be achieved, but comes with some caveats. 257 | 258 | When using `push-to-fork`, the action needs permissions for two different repositories. 259 | It needs `contents: write` for the fork to push the branch, and `pull-requests: write` for the parent repository to create the pull request. 260 | 261 | There are two main scenarios: 262 | 1. The parent and fork have different owners. In this case, it's not possible to create a token that is scoped to both repositories so different tokens must be used for each. 263 | 2. The parent and fork both have the same owner (i.e. they exist in the same org). In this case, a single token can be scoped to both repositories, but the permissions granted cannot be different. So it would defeat the purpose of using `push-to-fork`, and you might as well just create the pull request directly on the parent repository. 264 | 265 | For the first scenario, the solution is to scope the token for the fork, and use the `branch-token` input to push the branch. 266 | The `token` input will then default to the repository's `GITHUB_TOKEN`, which will be used to create the pull request. 267 | 268 | > [!NOTE] 269 | > Solution limitations: 270 | > - Since `GITHUB_TOKEN` will be used to create the pull request, the workflow *must* be executing in the parent repository where the pull request should be created. 271 | > - `maintainer-can-modify` *must* be set to `false`, because the `GITHUB_TOKEN` will not have `write` access to the head branch in the fork. 272 | 273 | The following is an example of pushing to a fork using GitHub App tokens. 274 | ```yaml 275 | - uses: actions/create-github-app-token@v1 276 | id: generate-token 277 | with: 278 | app-id: ${{ secrets.APP_ID }} 279 | private-key: ${{ secrets.APP_PRIVATE_KEY }} 280 | owner: owner 281 | repositories: fork-of-repo 282 | 283 | - uses: actions/checkout@v4 284 | 285 | # Make changes to pull request here 286 | 287 | - name: Create Pull Request 288 | uses: peter-evans/create-pull-request@v7 289 | with: 290 | branch-token: ${{ steps.generate-token.outputs.token }} 291 | push-to-fork: owner/fork-of-repo 292 | maintainer-can-modify: false 293 | ``` 294 | 295 | ### Authenticating with GitHub App generated tokens 296 | 297 | A GitHub App can be created for the sole purpose of generating tokens for use with GitHub actions. 298 | GitHub App generated tokens can be configured with fine-grained permissions and are scoped to only repositories where the App is installed. 299 | 300 | 1. Create a minimal [GitHub App](https://docs.github.com/en/developers/apps/creating-a-github-app), setting the following fields: 301 | 302 | - Set `GitHub App name`. 303 | - Set `Homepage URL` to anything you like, such as your GitHub profile page. 304 | - Uncheck `Active` under `Webhook`. You do not need to enter a `Webhook URL`. 305 | - Under `Repository permissions: Contents` select `Access: Read & write`. 306 | - Under `Repository permissions: Pull requests` select `Access: Read & write`. 307 | - Under `Repository permissions: Workflows` select `Access: Read & write`. 308 | - **NOTE**: Only needed if pull requests could contain changes to Actions workflows. 309 | - Under `Organization permissions: Members` select `Access: Read-only`. 310 | - **NOTE**: Only needed if you would like add teams as reviewers to PRs. 311 | 312 | 2. Create a Private key from the App settings page and store it securely. 313 | 314 | 3. Install the App on repositories that the action will require access to in order to create pull requests. 315 | 316 | 4. Set secrets on your repository containing the GitHub App ID, and the private key you created in step 2. e.g. `APP_ID`, `APP_PRIVATE_KEY`. 317 | 318 | 5. The following example workflow shows how to use [actions/create-github-app-token](https://github.com/actions/create-github-app-token) to generate a token for use with this action. 319 | 320 | ```yaml 321 | steps: 322 | - uses: actions/create-github-app-token@v1 323 | id: generate-token 324 | with: 325 | app-id: ${{ secrets.APP_ID }} 326 | private-key: ${{ secrets.APP_PRIVATE_KEY }} 327 | 328 | - uses: actions/checkout@v4 329 | 330 | # Make changes to pull request here 331 | 332 | - name: Create Pull Request 333 | uses: peter-evans/create-pull-request@v7 334 | with: 335 | token: ${{ steps.generate-token.outputs.token }} 336 | ``` 337 | 338 | #### Creating pull requests in a remote repository using GitHub App generated tokens 339 | 340 | For this case a token must be generated from the GitHub App installation of the remote repository. 341 | 342 | In the following example, a pull request is being created in remote repo `owner/repo`. 343 | ```yaml 344 | steps: 345 | - uses: actions/create-github-app-token@v1 346 | id: generate-token 347 | with: 348 | app-id: ${{ secrets.APP_ID }} 349 | private-key: ${{ secrets.APP_PRIVATE_KEY }} 350 | owner: owner 351 | repositories: repo 352 | 353 | - uses: actions/checkout@v4 354 | with: 355 | token: ${{ steps.generate-token.outputs.token }} # necessary if the repo is private 356 | repository: owner/repo 357 | 358 | # Make changes to pull request here 359 | 360 | - name: Create Pull Request 361 | uses: peter-evans/create-pull-request@v7 362 | with: 363 | token: ${{ steps.generate-token.outputs.token }} 364 | ``` 365 | 366 | ### Commit signing 367 | 368 | [Commit signature verification](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification) is a feature where GitHub will mark signed commits as "verified" to give confidence that changes are from a trusted source. 369 | Some organizations require commit signing, and enforce it with branch protection rules. 370 | 371 | The action supports two methods to sign commits, [commit signature verification for bots](#commit-signature-verification-for-bots), and [GPG commit signature verification](#gpg-commit-signature-verification). 372 | 373 | #### Commit signature verification for bots 374 | 375 | The action can sign commits as `github-actions[bot]` when using the repository's default `GITHUB_TOKEN`, or your own bot when using [GitHub App tokens](#authenticating-with-github-app-generated-tokens). 376 | 377 | > [!IMPORTANT] 378 | > - When setting `sign-commits: true` the action will ignore the `committer` and `author` inputs. 379 | > - If you attempt to use a [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) the action will create the pull request, but commits will *not* be signed. Commit signing is only supported with bot generated tokens. 380 | > - The GitHub API has a 40MiB limit when creating git blobs. An error will be raised if there are files in the pull request larger than this. If you hit this limit, use [GPG commit signature verification](#gpg-commit-signature-verification) instead. 381 | 382 | In this example the `token` input is not supplied, so the action will use the repository's default `GITHUB_TOKEN`. This will sign commits as `github-actions[bot]`. 383 | ```yaml 384 | steps: 385 | - uses: actions/checkout@v4 386 | 387 | # Make changes to pull request here 388 | 389 | - name: Create Pull Request 390 | uses: peter-evans/create-pull-request@v7 391 | with: 392 | sign-commits: true 393 | ``` 394 | 395 | In this example, the `token` input is generated using a GitHub App. This will sign commits as `[bot]`. 396 | ```yaml 397 | steps: 398 | - uses: actions/checkout@v4 399 | 400 | - uses: actions/create-github-app-token@v1 401 | id: generate-token 402 | with: 403 | app-id: ${{ secrets.APP_ID }} 404 | private-key: ${{ secrets.APP_PRIVATE_KEY }} 405 | 406 | # Make changes to pull request here 407 | 408 | - name: Create Pull Request 409 | uses: peter-evans/create-pull-request@v7 410 | with: 411 | token: ${{ steps.generate-token.outputs.token }} 412 | sign-commits: true 413 | ``` 414 | 415 | #### GPG commit signature verification 416 | 417 | The action can use GPG to sign commits with a GPG key that you generate yourself. 418 | 419 | 1. Follow GitHub's guide to [generate a new GPG key](https://docs.github.com/en/github/authenticating-to-github/generating-a-new-gpg-key). 420 | 421 | 2. [Add the public key](https://docs.github.com/en/github/authenticating-to-github/adding-a-new-gpg-key-to-your-github-account) to the user account associated with the [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) that you will use with the action. 422 | 423 | 3. Copy the private key to your clipboard, replacing `email@example.com` with the email address of your GPG key. 424 | ``` 425 | # macOS 426 | gpg --armor --export-secret-key email@example.com | pbcopy 427 | ``` 428 | 429 | 4. Paste the private key into a repository secret where the workflow will run. e.g. `GPG_PRIVATE_KEY` 430 | 431 | 5. Create another repository secret for the key's passphrase, if applicable. e.g. `GPG_PASSPHRASE` 432 | 433 | 6. The following example workflow shows how to use [crazy-max/ghaction-import-gpg](https://github.com/crazy-max/ghaction-import-gpg) to import your GPG key and allow the action to sign commits. 434 | 435 | > [!IMPORTANT] 436 | > The `committer` email address *MUST* match the email address used to create your GPG key. 437 | 438 | ```yaml 439 | steps: 440 | - uses: actions/checkout@v4 441 | 442 | - uses: crazy-max/ghaction-import-gpg@v5 443 | with: 444 | gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }} 445 | passphrase: ${{ secrets.GPG_PASSPHRASE }} 446 | git_user_signingkey: true 447 | git_commit_gpgsign: true 448 | 449 | # Make changes to pull request here 450 | 451 | - name: Create Pull Request 452 | uses: peter-evans/create-pull-request@v7 453 | with: 454 | token: ${{ secrets.PAT }} 455 | committer: example 456 | ``` 457 | 458 | ### Running in a container or on self-hosted runners 459 | 460 | This action can be run inside a container, or on [self-hosted runners](https://docs.github.com/en/actions/hosting-your-own-runners), by installing the necessary dependencies. 461 | 462 | This action requires `git` to be installed and on the `PATH`. Note that `actions/checkout` requires Git 2.18 or higher to be installed, otherwise it will just download the source of the repository instead of cloning it. 463 | 464 | The following examples of running in a container show the dependencies being installed during the workflow, but they could also be pre-installed in a custom image. 465 | 466 | **Alpine container example:** 467 | ```yml 468 | jobs: 469 | createPullRequestAlpine: 470 | runs-on: ubuntu-latest 471 | container: 472 | image: alpine 473 | steps: 474 | - name: Install dependencies 475 | run: apk --no-cache add git 476 | 477 | - uses: actions/checkout@v4 478 | 479 | # Make changes to pull request here 480 | 481 | - name: Create Pull Request 482 | uses: peter-evans/create-pull-request@v7 483 | ``` 484 | 485 | **Ubuntu container example:** 486 | ```yml 487 | jobs: 488 | createPullRequestAlpine: 489 | runs-on: ubuntu-latest 490 | container: 491 | image: ubuntu 492 | steps: 493 | - name: Install dependencies 494 | run: | 495 | apt-get update 496 | apt-get install -y software-properties-common 497 | add-apt-repository -y ppa:git-core/ppa 498 | apt-get install -y git 499 | 500 | - uses: actions/checkout@v4 501 | 502 | # Make changes to pull request here 503 | 504 | - name: Create Pull Request 505 | uses: peter-evans/create-pull-request@v7 506 | ``` 507 | -------------------------------------------------------------------------------- /docs/examples.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | - [Use case: Create a pull request to update X on push](#use-case-create-a-pull-request-to-update-x-on-push) 4 | - [Update project authors](#update-project-authors) 5 | - [Keep a branch up-to-date with another](#keep-a-branch-up-to-date-with-another) 6 | - [Use case: Create a pull request to update X on release](#use-case-create-a-pull-request-to-update-x-on-release) 7 | - [Update changelog](#update-changelog) 8 | - [Use case: Create a pull request to update X periodically](#use-case-create-a-pull-request-to-update-x-periodically) 9 | - [Update NPM dependencies](#update-npm-dependencies) 10 | - [Update Gradle dependencies](#update-gradle-dependencies) 11 | - [Update Cargo dependencies](#update-cargo-dependencies) 12 | - [Update SwaggerUI for GitHub Pages](#update-swaggerui-for-github-pages) 13 | - [Keep a fork up-to-date with its upstream](#keep-a-fork-up-to-date-with-its-upstream) 14 | - [Spider and download a website](#spider-and-download-a-website) 15 | - [Use case: Create a pull request to update X by calling the GitHub API](#use-case-create-a-pull-request-to-update-x-by-calling-the-github-api) 16 | - [Call the GitHub API from an external service](#call-the-github-api-from-an-external-service) 17 | - [Call the GitHub API from another GitHub Actions workflow](#call-the-github-api-from-another-github-actions-workflow) 18 | - [Use case: Create a pull request to modify/fix pull requests](#use-case-create-a-pull-request-to-modifyfix-pull-requests) 19 | - [autopep8](#autopep8) 20 | - [Misc workflow tips](#misc-workflow-tips) 21 | - [Filtering push events](#filtering-push-events) 22 | - [Dynamic configuration using variables](#dynamic-configuration-using-variables) 23 | - [Using a markdown template](#using-a-markdown-template) 24 | - [Debugging GitHub Actions](#debugging-github-actions) 25 | - [Show an annotation message for a created pull request](#show-an-annotation-message-for-a-created-pull-request) 26 | 27 | ## Use case: Create a pull request to update X on push 28 | 29 | This pattern will work well for updating any kind of static content based on pushed changes. Care should be taken when using this pattern in repositories with a high frequency of commits. 30 | 31 | ### Update project authors 32 | 33 | Raises a pull request to update a file called `AUTHORS` with the git user names and email addresses of contributors. 34 | 35 | ```yml 36 | name: Update AUTHORS 37 | on: 38 | push: 39 | branches: 40 | - main 41 | jobs: 42 | updateAuthors: 43 | runs-on: ubuntu-latest 44 | steps: 45 | - uses: actions/checkout@v4 46 | with: 47 | fetch-depth: 0 48 | - name: Update AUTHORS 49 | run: | 50 | git log --format='%aN <%aE>%n%cN <%cE>' | sort -u > AUTHORS 51 | - name: Create Pull Request 52 | uses: peter-evans/create-pull-request@v7 53 | with: 54 | commit-message: update authors 55 | title: Update AUTHORS 56 | body: Credit new contributors by updating AUTHORS 57 | branch: update-authors 58 | ``` 59 | 60 | ### Keep a branch up-to-date with another 61 | 62 | This is a use case where a branch should be kept up to date with another by opening a pull request to update it. The pull request should then be updated with new changes until it is merged or closed. 63 | 64 | In this example scenario, a branch called `production` should be updated via pull request to keep it in sync with `main`. Merging the pull request is effectively promoting those changes to production. 65 | 66 | ```yml 67 | name: Create production promotion pull request 68 | on: 69 | push: 70 | branches: 71 | - main 72 | jobs: 73 | productionPromotion: 74 | runs-on: ubuntu-latest 75 | steps: 76 | - uses: actions/checkout@v4 77 | with: 78 | ref: production 79 | - name: Reset promotion branch 80 | run: | 81 | git fetch origin main:main 82 | git reset --hard main 83 | - name: Create Pull Request 84 | uses: peter-evans/create-pull-request@v7 85 | with: 86 | branch: production-promotion 87 | ``` 88 | 89 | ## Use case: Create a pull request to update X on release 90 | 91 | This pattern will work well for updating any kind of static content based on the tagged commit of a release. Note that because `release` is one of the [events which checkout a commit](concepts-guidelines.md#events-which-checkout-a-commit) it is necessary to supply the `base` input to the action. 92 | 93 | ### Update changelog 94 | 95 | Raises a pull request to update the `CHANGELOG.md` file based on the tagged commit of the release. 96 | Note that [git-chglog](https://github.com/git-chglog/git-chglog/) requires some configuration files to exist in the repository before this workflow will work. 97 | 98 | This workflow assumes the tagged release was made on a default branch called `main`. 99 | 100 | ```yml 101 | name: Update Changelog 102 | on: 103 | release: 104 | types: [published] 105 | jobs: 106 | updateChangelog: 107 | runs-on: ubuntu-latest 108 | steps: 109 | - uses: actions/checkout@v4 110 | with: 111 | fetch-depth: 0 112 | - name: Update Changelog 113 | run: | 114 | curl -o git-chglog -L https://github.com/git-chglog/git-chglog/releases/download/0.9.1/git-chglog_linux_amd64 115 | chmod u+x git-chglog 116 | ./git-chglog -o CHANGELOG.md 117 | rm git-chglog 118 | - name: Create Pull Request 119 | uses: peter-evans/create-pull-request@v7 120 | with: 121 | commit-message: update changelog 122 | title: Update Changelog 123 | body: Update changelog to reflect release changes 124 | branch: update-changelog 125 | base: main 126 | ``` 127 | 128 | ## Use case: Create a pull request to update X periodically 129 | 130 | This pattern will work well for updating any kind of static content from an external source. The workflow executes on a schedule and raises a pull request when there are changes. 131 | 132 | ### Update NPM dependencies 133 | 134 | This workflow will create a pull request for npm dependencies. 135 | It works best in combination with a build workflow triggered on `push` and `pull_request`. 136 | A [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) can be used in order for the creation of the pull request to trigger further workflows. See the [documentation here](concepts-guidelines.md#triggering-further-workflow-runs) for further details. 137 | 138 | ```yml 139 | name: Update Dependencies 140 | on: 141 | schedule: 142 | - cron: '0 10 * * 1' 143 | jobs: 144 | update-dep: 145 | runs-on: ubuntu-latest 146 | steps: 147 | - uses: actions/checkout@v4 148 | - uses: actions/setup-node@v3 149 | with: 150 | node-version: '16.x' 151 | - name: Update dependencies 152 | run: | 153 | npx -p npm-check-updates ncu -u 154 | npm install 155 | - name: Create Pull Request 156 | uses: peter-evans/create-pull-request@v7 157 | with: 158 | token: ${{ secrets.PAT }} 159 | commit-message: Update dependencies 160 | title: Update dependencies 161 | body: | 162 | - Dependency updates 163 | 164 | Auto-generated by [create-pull-request][1] 165 | 166 | [1]: https://github.com/peter-evans/create-pull-request 167 | branch: update-dependencies 168 | ``` 169 | 170 | The above workflow works best in combination with a build workflow triggered on `push` and `pull_request`. 171 | 172 | ```yml 173 | name: CI 174 | on: 175 | push: 176 | branches: [main] 177 | pull_request: 178 | branches: [main] 179 | jobs: 180 | build: 181 | runs-on: ubuntu-latest 182 | steps: 183 | - uses: actions/checkout@v4 184 | - uses: actions/setup-node@v3 185 | with: 186 | node-version: 16.x 187 | - run: npm ci 188 | - run: npm run test 189 | - run: npm run build 190 | ``` 191 | 192 | ### Update Gradle dependencies 193 | 194 | The following workflow will create a pull request for Gradle dependencies. 195 | It requires first configuring your project to use Gradle lockfiles. 196 | See [here](https://github.com/peter-evans/gradle-auto-dependency-updates) for how to configure your project and use the following workflow. 197 | 198 | ```yml 199 | name: Update Dependencies 200 | on: 201 | schedule: 202 | - cron: '0 1 * * 1' 203 | jobs: 204 | update-dep: 205 | runs-on: ubuntu-latest 206 | steps: 207 | - uses: actions/checkout@v4 208 | - uses: actions/setup-java@v2 209 | with: 210 | distribution: 'temurin' 211 | java-version: 1.8 212 | - name: Grant execute permission for gradlew 213 | run: chmod +x gradlew 214 | - name: Perform dependency resolution and write new lockfiles 215 | run: ./gradlew dependencies --write-locks 216 | - name: Create Pull Request 217 | uses: peter-evans/create-pull-request@v7 218 | with: 219 | token: ${{ secrets.PAT }} 220 | commit-message: Update dependencies 221 | title: Update dependencies 222 | body: | 223 | - Dependency updates 224 | 225 | Auto-generated by [create-pull-request][1] 226 | 227 | [1]: https://github.com/peter-evans/create-pull-request 228 | branch: update-dependencies 229 | ``` 230 | 231 | ### Update Cargo dependencies 232 | 233 | The following workflow will create a pull request for Cargo dependencies. 234 | It optionally uses [`cargo-edit`](https://github.com/killercup/cargo-edit) to update `Cargo.toml` and keep it in sync with `Cargo.lock`. 235 | 236 | ```yml 237 | name: Update Dependencies 238 | on: 239 | schedule: 240 | - cron: '0 1 * * 1' 241 | jobs: 242 | update-dep: 243 | runs-on: ubuntu-latest 244 | steps: 245 | - uses: actions/checkout@v4 246 | - name: Update dependencies 247 | run: | 248 | cargo install cargo-edit 249 | cargo update 250 | cargo upgrade --to-lockfile 251 | - name: Create Pull Request 252 | uses: peter-evans/create-pull-request@v7 253 | with: 254 | token: ${{ secrets.PAT }} 255 | commit-message: Update dependencies 256 | title: Update dependencies 257 | body: | 258 | - Dependency updates 259 | 260 | Auto-generated by [create-pull-request][1] 261 | 262 | [1]: https://github.com/peter-evans/create-pull-request 263 | branch: update-dependencies 264 | ``` 265 | 266 | ### Update SwaggerUI for GitHub Pages 267 | 268 | When using [GitHub Pages to host Swagger documentation](https://github.com/peter-evans/swagger-github-pages), this workflow updates the repository with the latest distribution of [SwaggerUI](https://github.com/swagger-api/swagger-ui). 269 | 270 | You must create a file called `swagger-ui.version` at the root of your repository before running. 271 | ```yml 272 | name: Update Swagger UI 273 | on: 274 | schedule: 275 | - cron: '0 10 * * *' 276 | jobs: 277 | updateSwagger: 278 | runs-on: ubuntu-latest 279 | steps: 280 | - uses: actions/checkout@v4 281 | - name: Get Latest Swagger UI Release 282 | id: swagger-ui 283 | run: | 284 | release_tag=$(curl -sL https://api.github.com/repos/swagger-api/swagger-ui/releases/latest | jq -r ".tag_name") 285 | echo "release_tag=$release_tag" >> $GITHUB_OUTPUT 286 | current_tag=$(> $GITHUB_OUTPUT 288 | - name: Update Swagger UI 289 | if: steps.swagger-ui.outputs.current_tag != steps.swagger-ui.outputs.release_tag 290 | env: 291 | RELEASE_TAG: ${{ steps.swagger-ui.outputs.release_tag }} 292 | SWAGGER_YAML: "swagger.yaml" 293 | run: | 294 | # Delete the dist directory and index.html 295 | rm -fr dist index.html 296 | # Download the release 297 | curl -sL -o $RELEASE_TAG https://api.github.com/repos/swagger-api/swagger-ui/tarball/$RELEASE_TAG 298 | # Extract the dist directory 299 | tar -xzf $RELEASE_TAG --strip-components=1 $(tar -tzf $RELEASE_TAG | head -1 | cut -f1 -d"/")/dist 300 | rm $RELEASE_TAG 301 | # Move index.html to the root 302 | mv dist/index.html . 303 | # Fix references in index.html 304 | sed -i "s|https://petstore.swagger.io/v2/swagger.json|$SWAGGER_YAML|g" index.html 305 | sed -i "s|href=\"./|href=\"dist/|g" index.html 306 | sed -i "s|src=\"./|src=\"dist/|g" index.html 307 | # Update current release 308 | echo ${{ steps.swagger-ui.outputs.release_tag }} > swagger-ui.version 309 | - name: Create Pull Request 310 | uses: peter-evans/create-pull-request@v7 311 | with: 312 | commit-message: Update swagger-ui to ${{ steps.swagger-ui.outputs.release_tag }} 313 | title: Update SwaggerUI to ${{ steps.swagger-ui.outputs.release_tag }} 314 | body: | 315 | Updates [swagger-ui][1] to ${{ steps.swagger-ui.outputs.release_tag }} 316 | 317 | Auto-generated by [create-pull-request][2] 318 | 319 | [1]: https://github.com/swagger-api/swagger-ui 320 | [2]: https://github.com/peter-evans/create-pull-request 321 | labels: dependencies, automated pr 322 | branch: swagger-ui-updates 323 | ``` 324 | 325 | ### Keep a fork up-to-date with its upstream 326 | 327 | This example is designed to be run in a separate repository from the fork repository itself. 328 | The aim of this is to prevent committing anything to the fork's default branch would cause it to differ from the upstream. 329 | 330 | In the following example workflow, `owner/repo` is the upstream repository and `fork-owner/repo` is the fork. It assumes the default branch of the upstream repository is called `main`. 331 | 332 | The [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) should have `repo` scope. Additionally, if the upstream makes changes to the `.github/workflows` directory, the action will be unable to push the changes to a branch and throw the error "_(refusing to allow a GitHub App to create or update workflow `.github/workflows/xxx.yml` without `workflows` permission)_". To allow these changes to be pushed to the fork, add the `workflow` scope to the PAT. Of course, allowing this comes with the risk that the workflow changes from the upstream could run and do something unexpected. Disabling GitHub Actions in the fork is highly recommended to prevent this. 333 | 334 | When you merge the pull request make sure to choose the [`Rebase and merge`](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-merges#rebase-and-merge-your-pull-request-commits) option. This will make the fork's commits match the commits on the upstream. 335 | 336 | ```yml 337 | name: Update fork 338 | on: 339 | schedule: 340 | - cron: '0 0 * * 0' 341 | jobs: 342 | updateFork: 343 | runs-on: ubuntu-latest 344 | steps: 345 | - uses: actions/checkout@v4 346 | with: 347 | repository: fork-owner/repo 348 | - name: Reset the default branch with upstream changes 349 | run: | 350 | git remote add upstream https://github.com/owner/repo.git 351 | git fetch upstream main:upstream-main 352 | git reset --hard upstream-main 353 | - name: Create Pull Request 354 | uses: peter-evans/create-pull-request@v7 355 | with: 356 | token: ${{ secrets.PAT }} 357 | branch: upstream-changes 358 | ``` 359 | 360 | ### Spider and download a website 361 | 362 | This workflow spiders a website and downloads the content. Any changes to the website will be raised in a pull request. 363 | 364 | ```yml 365 | name: Download Website 366 | on: 367 | schedule: 368 | - cron: '0 10 * * *' 369 | jobs: 370 | format: 371 | runs-on: ubuntu-latest 372 | steps: 373 | - uses: actions/checkout@v4 374 | - name: Download website 375 | run: | 376 | wget \ 377 | --recursive \ 378 | --level=2 \ 379 | --wait=1 \ 380 | --no-clobber \ 381 | --page-requisites \ 382 | --html-extension \ 383 | --convert-links \ 384 | --domains quotes.toscrape.com \ 385 | http://quotes.toscrape.com/ 386 | - name: Create Pull Request 387 | uses: peter-evans/create-pull-request@v7 388 | with: 389 | commit-message: update local website copy 390 | title: Automated Updates to Local Website Copy 391 | body: This is an auto-generated PR with website updates. 392 | branch: website-updates 393 | ``` 394 | 395 | ## Use case: Create a pull request to update X by calling the GitHub API 396 | 397 | You can use the GitHub API to trigger a webhook event called [`repository_dispatch`](https://docs.github.com/en/actions/reference/events-that-trigger-workflows#repository_dispatch) when you want to trigger a workflow for any activity that happens outside of GitHub. 398 | This pattern will work well for updating any kind of static content from an external source. 399 | 400 | You can modify any of the examples in the previous section to work in this fashion. 401 | 402 | Set the workflow to execute `on: repository_dispatch`. 403 | 404 | ```yml 405 | on: 406 | repository_dispatch: 407 | types: [create-pull-request] 408 | ``` 409 | 410 | ### Call the GitHub API from an external service 411 | 412 | An `on: repository_dispatch` workflow can be triggered by a call to the GitHub API as follows. 413 | 414 | - `[username]` is a GitHub username 415 | - `[token]` is a `repo` scoped [Personal Access Token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) 416 | - `[repository]` is the name of the repository the workflow resides in. 417 | 418 | ``` 419 | curl -XPOST -u "[username]:[token]" \ 420 | -H "Accept: application/vnd.github.everest-preview+json" \ 421 | -H "Content-Type: application/json" \ 422 | https://api.github.com/repos/[username]/[repository]/dispatches \ 423 | --data '{"event_type": "create-pull-request"}' 424 | ``` 425 | 426 | ### Call the GitHub API from another GitHub Actions workflow 427 | 428 | An `on: repository_dispatch` workflow can be triggered from another workflow with [repository-dispatch](https://github.com/peter-evans/repository-dispatch) action. 429 | 430 | ```yml 431 | - name: Repository Dispatch 432 | uses: peter-evans/repository-dispatch@v2 433 | with: 434 | token: ${{ secrets.REPO_ACCESS_TOKEN }} 435 | repository: username/my-repo 436 | event-type: create-pull-request 437 | client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}"}' 438 | ``` 439 | 440 | ## Use case: Create a pull request to modify/fix pull requests 441 | 442 | **Note**: While the following approach does work, my strong recommendation would be to use a slash command style "ChatOps" solution for operations on pull requests. See [slash-command-dispatch](https://github.com/peter-evans/slash-command-dispatch) for such a solution. 443 | 444 | This is a pattern that lends itself to automated code linting and fixing. A pull request can be created to fix or modify something during an `on: pull_request` workflow. The pull request containing the fix will be raised with the original pull request as the base. This can be then be merged to update the original pull request and pass any required tests. 445 | 446 | Note that due to [token restrictions on public repository forks](https://docs.github.com/en/actions/configuring-and-managing-workflows/authenticating-with-the-github_token#permissions-for-the-github_token), workflows for this use case do not work for pull requests raised from forks. 447 | Private repositories can be configured to [enable workflows](https://docs.github.com/en/github/administering-a-repository/disabling-or-limiting-github-actions-for-a-repository#enabling-workflows-for-private-repository-forks) from forks to run without restriction. 448 | 449 | ### autopep8 450 | 451 | The following is an example workflow for a use case where [autopep8 action](https://github.com/peter-evans/autopep8) runs as both a check on pull requests and raises a further pull request to apply code fixes. 452 | 453 | How it works: 454 | 455 | 1. When a pull request is raised the workflow executes as a check 456 | 2. If autopep8 makes any fixes a pull request will be raised for those fixes to be merged into the current pull request branch. The workflow then deliberately causes the check to fail. 457 | 3. When the pull request containing the fixes is merged the workflow runs again. This time autopep8 makes no changes and the check passes. 458 | 4. The original pull request can now be merged. 459 | 460 | ```yml 461 | name: autopep8 462 | on: pull_request 463 | jobs: 464 | autopep8: 465 | # Check if the PR is not raised by this workflow and is not from a fork 466 | if: startsWith(github.head_ref, 'autopep8-patches') == false && github.event.pull_request.head.repo.full_name == github.repository 467 | runs-on: ubuntu-latest 468 | steps: 469 | - uses: actions/checkout@v4 470 | with: 471 | ref: ${{ github.head_ref }} 472 | - name: autopep8 473 | id: autopep8 474 | uses: peter-evans/autopep8@v1 475 | with: 476 | args: --exit-code --recursive --in-place --aggressive --aggressive . 477 | - name: Set autopep8 branch name 478 | id: vars 479 | run: | 480 | branch-name="autopep8-patches/${{ github.head_ref }}" 481 | echo "branch-name=$branch-name" >> $GITHUB_OUTPUT 482 | - name: Create Pull Request 483 | if: steps.autopep8.outputs.exit-code == 2 484 | uses: peter-evans/create-pull-request@v7 485 | with: 486 | commit-message: autopep8 action fixes 487 | title: Fixes by autopep8 action 488 | body: This is an auto-generated PR with fixes by autopep8. 489 | labels: autopep8, automated pr 490 | branch: ${{ steps.vars.outputs.branch-name }} 491 | - name: Fail if autopep8 made changes 492 | if: steps.autopep8.outputs.exit-code == 2 493 | run: exit 1 494 | ``` 495 | 496 | ## Misc workflow tips 497 | 498 | ### Filtering push events 499 | 500 | For workflows using `on: push` you may want to ignore push events for tags and only execute for branches. Specifying `branches` causes only events on branches to trigger the workflow. The `'**'` wildcard will match any branch name. 501 | 502 | ```yml 503 | on: 504 | push: 505 | branches: 506 | - '**' 507 | ``` 508 | 509 | If you have a workflow that contains jobs to handle push events on branches as well as tags, you can make sure that the job where you use `create-pull-request` action only executes when `github.ref` is a branch by using an `if` condition as follows. 510 | 511 | ```yml 512 | on: push 513 | jobs: 514 | createPullRequest: 515 | if: startsWith(github.ref, 'refs/heads/') 516 | runs-on: ubuntu-latest 517 | steps: 518 | - uses: actions/checkout@v4 519 | ... 520 | 521 | someOtherJob: 522 | runs-on: ubuntu-latest 523 | steps: 524 | - uses: actions/checkout@v4 525 | ... 526 | ``` 527 | 528 | ### Dynamic configuration using variables 529 | 530 | The following examples show how configuration for the action can be dynamically defined in a previous workflow step. 531 | Note that the step where output variables are defined must have an id. 532 | 533 | ```yml 534 | - name: Set output variables 535 | id: vars 536 | run: | 537 | pr_title="[Test] Add report file $(date +%d-%m-%Y)" 538 | pr_body="This PR was auto-generated on $(date +%d-%m-%Y) \ 539 | by [create-pull-request](https://github.com/peter-evans/create-pull-request)." 540 | echo "pr_title=$pr_title" >> $GITHUB_OUTPUT 541 | echo "pr_body=$pr_body" >> $GITHUB_OUTPUT 542 | - name: Create Pull Request 543 | uses: peter-evans/create-pull-request@v7 544 | with: 545 | title: ${{ steps.vars.outputs.pr_title }} 546 | body: ${{ steps.vars.outputs.pr_body }} 547 | ``` 548 | 549 | ### Using a markdown template 550 | 551 | In this example, a markdown template file is added to the repository at `.github/pull-request-template.md` with the following content. 552 | ``` 553 | This is a test pull request template 554 | Render template variables such as {{ .foo }} and {{ .bar }}. 555 | ``` 556 | 557 | The template is rendered using the [render-template](https://github.com/chuhlomin/render-template) action and the result is used to create the pull request. 558 | ```yml 559 | - name: Render template 560 | id: template 561 | uses: chuhlomin/render-template@v1.4 562 | with: 563 | template: .github/pull-request-template.md 564 | vars: | 565 | foo: this 566 | bar: that 567 | 568 | - name: Create Pull Request 569 | uses: peter-evans/create-pull-request@v7 570 | with: 571 | body: ${{ steps.template.outputs.result }} 572 | ``` 573 | 574 | ### Debugging GitHub Actions 575 | 576 | #### Runner Diagnostic Logging 577 | 578 | [Runner diagnostic logging](https://docs.github.com/en/actions/configuring-and-managing-workflows/managing-a-workflow-run#enabling-runner-diagnostic-logging) provides additional log files that contain information about how a runner is executing an action. 579 | To enable runner diagnostic logging, set the secret `ACTIONS_RUNNER_DEBUG` to `true` in the repository that contains the workflow. 580 | 581 | #### Step Debug Logging 582 | 583 | [Step debug logging](https://docs.github.com/en/actions/configuring-and-managing-workflows/managing-a-workflow-run#enabling-step-debug-logging) increases the verbosity of a job's logs during and after a job's execution. 584 | To enable step debug logging set the secret `ACTIONS_STEP_DEBUG` to `true` in the repository that contains the workflow. 585 | 586 | #### Output Various Contexts 587 | 588 | ```yml 589 | steps: 590 | - name: Dump GitHub context 591 | env: 592 | GITHUB_CONTEXT: ${{ toJson(github) }} 593 | run: echo "$GITHUB_CONTEXT" 594 | - name: Dump job context 595 | env: 596 | JOB_CONTEXT: ${{ toJson(job) }} 597 | run: echo "$JOB_CONTEXT" 598 | - name: Dump steps context 599 | env: 600 | STEPS_CONTEXT: ${{ toJson(steps) }} 601 | run: echo "$STEPS_CONTEXT" 602 | - name: Dump runner context 603 | env: 604 | RUNNER_CONTEXT: ${{ toJson(runner) }} 605 | run: echo "$RUNNER_CONTEXT" 606 | - name: Dump strategy context 607 | env: 608 | STRATEGY_CONTEXT: ${{ toJson(strategy) }} 609 | run: echo "$STRATEGY_CONTEXT" 610 | - name: Dump matrix context 611 | env: 612 | MATRIX_CONTEXT: ${{ toJson(matrix) }} 613 | run: echo "$MATRIX_CONTEXT" 614 | ``` 615 | 616 | ### Show an annotation message for a created pull request 617 | 618 | Showing an annotation message for a created or updated pull request allows you to confirm the pull request easily, such as by visiting the link. This can be achieved by adding a step that uses the [`notice` workflow command](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions?tool=bash#setting-a-notice-message). 619 | 620 | For example: 621 | 622 | ```yml 623 | - name: Create Pull Request 624 | id: cpr 625 | uses: peter-evans/create-pull-request@v7 626 | 627 | - name: Show message for created Pull Request 628 | if: ${{ steps.cpr.outputs.pull-request-url && steps.cpr.outputs.pull-request-operation != 'none' }} 629 | shell: bash 630 | env: 631 | PR_URL: ${{ steps.cpr.outputs.pull-request-url }} 632 | PR_OPERATION: ${{ steps.cpr.outputs.pull-request-operation }} 633 | run: | 634 | echo "::notice::${PR_URL} was ${PR_OPERATION}." 635 | ``` 636 | 637 | In this example, when a pull request is created, you will be able to see the following message on an action run page (e.g., `/actions/runs/12812393039`): 638 | 639 | ``` 640 | https://github.com/peter-evans/create-pull-request/pull/1 was created. 641 | ``` 642 | -------------------------------------------------------------------------------- /docs/updating.md: -------------------------------------------------------------------------------- 1 | ## Updating from `v6` to `v7` 2 | 3 | ### Behaviour changes 4 | 5 | - Action input `git-token` has been renamed `branch-token`, to be more clear about its purpose. The `branch-token` is the token that the action will use to create and update the branch. 6 | - The action now handles requests that have been rate-limited by GitHub. Requests hitting a primary rate limit will retry twice, for a total of three attempts. Requests hitting a secondary rate limit will not be retried. 7 | - The `pull-request-operation` output now returns `none` when no operation was executed. 8 | - Removed deprecated output environment variable `PULL_REQUEST_NUMBER`. Please use the `pull-request-number` action output instead. 9 | 10 | ### What's new 11 | 12 | - The action can now sign commits as `github-actions[bot]` when using `GITHUB_TOKEN`, or your own bot when using [GitHub App tokens](concepts-guidelines.md#authenticating-with-github-app-generated-tokens). See [commit signing](concepts-guidelines.md#commit-signature-verification-for-bots) for details. 13 | - Action input `draft` now accepts a new value `always-true`. This will set the pull request to draft status when the pull request is updated, as well as on creation. 14 | - A new action input `maintainer-can-modify` indicates whether [maintainers can modify](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) the pull request. The default is `true`, which retains the existing behaviour of the action. 15 | - A new output `pull-request-commits-verified` returns `true` or `false`, indicating whether GitHub considers the signature of the branch's commits to be verified. 16 | 17 | ## Updating from `v5` to `v6` 18 | 19 | ### Behaviour changes 20 | 21 | - The default values for `author` and `committer` have changed. See "What's new" below for details. If you are overriding the default values you will not be affected by this change. 22 | - On completion, the action now removes the temporary git remote configuration it adds when using `push-to-fork`. This should not affect you unless you were using the temporary configuration for some other purpose after the action completes. 23 | 24 | ### What's new 25 | 26 | - Updated runtime to Node.js 20 27 | - The action now requires a minimum version of [v2.308.0](https://github.com/actions/runner/releases/tag/v2.308.0) for the Actions runner. Update self-hosted runners to v2.308.0 or later to ensure compatibility. 28 | - The default value for `author` has been changed to `${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com>`. The change adds the `${{ github.actor_id }}+` prefix to the email address to align with GitHub's standard format for the author email address. 29 | - The default value for `committer` has been changed to `github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>`. This is to align with the default GitHub Actions bot user account. 30 | - Adds input `git-token`, the [Personal Access Token (PAT)](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) that the action will use for git operations. This input defaults to the value of `token`. Use this input if you would like the action to use a different token for git operations than the one used for the GitHub API. 31 | - `push-to-fork` now supports pushing to sibling repositories in the same network. 32 | - Previously, when using `push-to-fork`, the action did not remove temporary git remote configuration it adds during execution. This has been fixed and the configuration is now removed when the action completes. 33 | - If the pull request body is truncated due to exceeding the maximum length, the action will now suffix the body with the message "...*[Pull request body truncated]*" to indicate that the body has been truncated. 34 | - The action now uses `--unshallow` only when necessary, rather than as a default argument of `git fetch`. This should improve performance, particularly for large git repositories with extensive commit history. 35 | - The action can now be executed on one GitHub server and create pull requests on a *different* GitHub server. Server products include GitHub hosted (github.com), GitHub Enterprise Server (GHES), and GitHub Enterprise Cloud (GHEC). For example, the action can be executed on GitHub hosted and create pull requests on a GHES or GHEC instance. 36 | 37 | ## Updating from `v4` to `v5` 38 | 39 | ### Behaviour changes 40 | 41 | - The action will no longer leave the local repository checked out on the pull request `branch`. Instead, it will leave the repository checked out on the branch or commit that it was when the action started. 42 | - When using `add-paths`, uncommitted changes will no longer be destroyed. They will be stashed and restored at the end of the action run. 43 | 44 | ### What's new 45 | 46 | - Adds input `body-path`, the path to a file containing the pull request body. 47 | - At the end of the action run the local repository is now checked out on the branch or commit that it was when the action started. 48 | - Any uncommitted tracked or untracked changes are now stashed and restored at the end of the action run. Currently, this can only occur when using the `add-paths` input, which allows for changes to not be committed. Previously, any uncommitted changes would be destroyed. 49 | - The proxy implementation has been revised but is not expected to have any change in behaviour. It continues to support the standard environment variables `http_proxy`, `https_proxy` and `no_proxy`. 50 | - Now sets the git `safe.directory` configuration for the local repository path. The configuration is removed when the action completes. Fixes issue https://github.com/peter-evans/create-pull-request/issues/1170. 51 | - Now determines the git directory path using the `git rev-parse --git-dir` command. This allows users with custom repository configurations to use the action. 52 | - Improved handling of the `team-reviewers` input and associated errors. 53 | 54 | ## Updating from `v3` to `v4` 55 | 56 | ### Behaviour changes 57 | 58 | - The `add-paths` input no longer accepts `-A` as a valid value. When committing all new and modified files the `add-paths` input should be omitted. 59 | 60 | - If using self-hosted runners or GitHub Enterprise Server, there are minimum requirements for `v4` to run. See "What's new" below for details. 61 | 62 | ### What's new 63 | 64 | - Updated runtime to Node.js 16 65 | - The action now requires a minimum version of v2.285.0 for the [Actions Runner](https://github.com/actions/runner/releases/tag/v2.285.0). 66 | - If using GitHub Enterprise Server, the action requires [GHES 3.4](https://docs.github.com/en/enterprise-server@3.4/admin/release-notes) or later. 67 | 68 | ## Updating from `v2` to `v3` 69 | 70 | ### Behaviour changes 71 | 72 | - The `author` input now defaults to the user who triggered the workflow run. This default is set via [action.yml](../action.yml) as `${{ github.actor }} <${{ github.actor }}@users.noreply.github.com>`, where `github.actor` is the GitHub user account associated with the run. For example, `peter-evans `. 73 | 74 | To continue to use the `v2` default, set the `author` input as follows. 75 | ```yaml 76 | - uses: peter-evans/create-pull-request@v3 77 | with: 78 | author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 79 | ``` 80 | 81 | - The `author` and `committer` inputs are no longer cross-used if only one is supplied. Additionally, when neither input is set, the `author` and `committer` are no longer determined from an existing identity set in git config. In both cases, the inputs will fall back to their default set in [action.yml](../action.yml). 82 | 83 | - Deprecated inputs `project` and `project-column` have been removed in favour of an additional action step. See [Create a project card](https://github.com/peter-evans/create-pull-request#create-a-project-card) for details. 84 | 85 | - Deprecated output `pr_number` has been removed in favour of `pull-request-number`. 86 | 87 | - Input `request-to-parent` has been removed in favour of `push-to-fork`. This greatly simplifies pushing the pull request branch to a fork of the parent repository. See [Push pull request branches to a fork](concepts-guidelines.md#push-pull-request-branches-to-a-fork) for details. 88 | 89 | e.g. 90 | ```yaml 91 | - uses: actions/checkout@v2 92 | 93 | # Make changes to pull request here 94 | 95 | - uses: peter-evans/create-pull-request@v3 96 | with: 97 | token: ${{ secrets.MACHINE_USER_PAT }} 98 | push-to-fork: machine-user/fork-of-repository 99 | ``` 100 | 101 | ### What's new 102 | 103 | - The action has been converted to Typescript giving it a significant performance improvement. 104 | 105 | - If you run this action in a container, or on [self-hosted runners](https://docs.github.com/en/actions/hosting-your-own-runners), `python` and `pip` are no longer required dependencies. See [Running in a container or on self-hosted runners](concepts-guidelines.md#running-in-a-container-or-on-self-hosted-runners) for details. 106 | 107 | - Inputs `labels`, `assignees`, `reviewers` and `team-reviewers` can now be newline separated, or comma separated. 108 | e.g. 109 | ```yml 110 | labels: | 111 | chore 112 | dependencies 113 | automated 114 | ``` 115 | 116 | ## Updating from `v1` to `v2` 117 | 118 | ### Behaviour changes 119 | 120 | - `v2` now expects repositories to be checked out with `actions/checkout@v2` 121 | 122 | To use `actions/checkout@v1` the following step to checkout the branch is necessary. 123 | ```yml 124 | - uses: actions/checkout@v1 125 | - name: Checkout branch 126 | run: git checkout "${GITHUB_REF:11}" 127 | ``` 128 | 129 | - The two branch naming strategies have been swapped. Fixed-branch naming strategy is now the default. i.e. `branch-suffix: none` is now the default and should be removed from configuration if set. 130 | 131 | - `author-name`, `author-email`, `committer-name`, `committer-email` have been removed in favour of `author` and `committer`. 132 | They can both be set in the format `Display Name ` 133 | 134 | If neither `author` or `committer` are set the action will default to making commits as the GitHub Actions bot user. 135 | 136 | ### What's new 137 | 138 | - Unpushed commits made during the workflow before the action runs will now be considered as changes to be raised in the pull request. See [Create your own commits](https://github.com/peter-evans/create-pull-request#create-your-own-commits) for details. 139 | - New commits made to the pull request base will now be taken into account when pull requests are updated. 140 | - If an updated pull request no longer differs from its base it will automatically be closed and the pull request branch deleted. 141 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | clearMocks: true, 3 | moduleFileExtensions: ['js', 'ts'], 4 | testEnvironment: 'node', 5 | testMatch: ['**/*.test.ts'], 6 | testRunner: 'jest-circus/runner', 7 | transform: { 8 | '^.+\\.ts$': 'ts-jest' 9 | }, 10 | verbose: true 11 | } 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "create-pull-request", 3 | "version": "7.0.0", 4 | "private": true, 5 | "description": "Creates a pull request for changes to your repository in the actions workspace", 6 | "main": "lib/main.js", 7 | "scripts": { 8 | "build": "tsc && ncc build", 9 | "format": "prettier --write '**/*.ts'", 10 | "format-check": "prettier --check '**/*.ts'", 11 | "lint": "eslint src/**/*.ts", 12 | "test:unit": "jest unit", 13 | "test:int": "__test__/integration-tests.sh", 14 | "test": "npm run test:unit && npm run test:int" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/peter-evans/create-pull-request.git" 19 | }, 20 | "keywords": [ 21 | "actions", 22 | "pull", 23 | "request" 24 | ], 25 | "author": "Peter Evans", 26 | "license": "MIT", 27 | "bugs": { 28 | "url": "https://github.com/peter-evans/create-pull-request/issues" 29 | }, 30 | "homepage": "https://github.com/peter-evans/create-pull-request", 31 | "dependencies": { 32 | "@actions/core": "^1.11.1", 33 | "@actions/exec": "^1.1.1", 34 | "@octokit/core": "^6.1.5", 35 | "@octokit/plugin-paginate-rest": "^11.6.0", 36 | "@octokit/plugin-rest-endpoint-methods": "^13.5.0", 37 | "@octokit/plugin-throttling": "^9.6.1", 38 | "node-fetch-native": "^1.6.6", 39 | "p-limit": "^6.2.0", 40 | "uuid": "^9.0.1" 41 | }, 42 | "devDependencies": { 43 | "@types/jest": "^29.5.14", 44 | "@types/node": "^18.19.103", 45 | "@typescript-eslint/eslint-plugin": "^7.18.0", 46 | "@typescript-eslint/parser": "^7.18.0", 47 | "@vercel/ncc": "^0.38.3", 48 | "eslint": "^8.57.1", 49 | "eslint-import-resolver-typescript": "^3.10.1", 50 | "eslint-plugin-github": "^4.10.2", 51 | "eslint-plugin-import": "^2.31.0", 52 | "eslint-plugin-jest": "^27.9.0", 53 | "eslint-plugin-prettier": "^5.4.0", 54 | "jest": "^29.7.0", 55 | "jest-circus": "^29.7.0", 56 | "jest-environment-jsdom": "^29.7.0", 57 | "js-yaml": "^4.1.0", 58 | "prettier": "^3.5.3", 59 | "ts-jest": "^29.3.4", 60 | "typescript": "^5.8.3", 61 | "undici": "^6.21.3" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/create-or-update-branch.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import {GitCommandManager, Commit} from './git-command-manager' 3 | import {v4 as uuidv4} from 'uuid' 4 | import * as utils from './utils' 5 | 6 | const CHERRYPICK_EMPTY = 7 | 'The previous cherry-pick is now empty, possibly due to conflict resolution.' 8 | const NOTHING_TO_COMMIT = 'nothing to commit, working tree clean' 9 | 10 | const FETCH_DEPTH_MARGIN = 10 11 | 12 | export enum WorkingBaseType { 13 | Branch = 'branch', 14 | Commit = 'commit' 15 | } 16 | 17 | export async function getWorkingBaseAndType( 18 | git: GitCommandManager 19 | ): Promise<[string, WorkingBaseType]> { 20 | const symbolicRefResult = await git.exec( 21 | ['symbolic-ref', 'HEAD', '--short'], 22 | {allowAllExitCodes: true} 23 | ) 24 | if (symbolicRefResult.exitCode == 0) { 25 | // A ref is checked out 26 | return [symbolicRefResult.stdout.trim(), WorkingBaseType.Branch] 27 | } else { 28 | // A commit is checked out (detached HEAD) 29 | const headSha = await git.revParse('HEAD') 30 | return [headSha, WorkingBaseType.Commit] 31 | } 32 | } 33 | 34 | export async function tryFetch( 35 | git: GitCommandManager, 36 | remote: string, 37 | branch: string, 38 | depth: number 39 | ): Promise { 40 | try { 41 | await git.fetch([`${branch}:refs/remotes/${remote}/${branch}`], remote, [ 42 | '--force', 43 | `--depth=${depth}` 44 | ]) 45 | return true 46 | } catch { 47 | return false 48 | } 49 | } 50 | 51 | export async function buildBranchCommits( 52 | git: GitCommandManager, 53 | base: string, 54 | branch: string 55 | ): Promise { 56 | const output = await git.exec(['log', '--format=%H', `${base}..${branch}`]) 57 | const shas = output.stdout 58 | .split('\n') 59 | .filter(x => x !== '') 60 | .reverse() 61 | const commits: Commit[] = [] 62 | for (const sha of shas) { 63 | const commit = await git.getCommit(sha) 64 | commits.push(commit) 65 | for (const unparsedChange of commit.unparsedChanges) { 66 | core.warning(`Skipping unexpected diff entry: ${unparsedChange}`) 67 | } 68 | } 69 | return commits 70 | } 71 | 72 | // Return the number of commits that branch2 is ahead of branch1 73 | async function commitsAhead( 74 | git: GitCommandManager, 75 | branch1: string, 76 | branch2: string 77 | ): Promise { 78 | const result = await git.revList( 79 | [`${branch1}...${branch2}`], 80 | ['--right-only', '--count'] 81 | ) 82 | return Number(result) 83 | } 84 | 85 | // Return true if branch2 is ahead of branch1 86 | async function isAhead( 87 | git: GitCommandManager, 88 | branch1: string, 89 | branch2: string 90 | ): Promise { 91 | return (await commitsAhead(git, branch1, branch2)) > 0 92 | } 93 | 94 | // Return the number of commits that branch2 is behind branch1 95 | async function commitsBehind( 96 | git: GitCommandManager, 97 | branch1: string, 98 | branch2: string 99 | ): Promise { 100 | const result = await git.revList( 101 | [`${branch1}...${branch2}`], 102 | ['--left-only', '--count'] 103 | ) 104 | return Number(result) 105 | } 106 | 107 | // Return true if branch2 is behind branch1 108 | async function isBehind( 109 | git: GitCommandManager, 110 | branch1: string, 111 | branch2: string 112 | ): Promise { 113 | return (await commitsBehind(git, branch1, branch2)) > 0 114 | } 115 | 116 | // Return true if branch2 is even with branch1 117 | async function isEven( 118 | git: GitCommandManager, 119 | branch1: string, 120 | branch2: string 121 | ): Promise { 122 | return ( 123 | !(await isAhead(git, branch1, branch2)) && 124 | !(await isBehind(git, branch1, branch2)) 125 | ) 126 | } 127 | 128 | // Return true if the specified number of commits on branch1 and branch2 have a diff 129 | async function commitsHaveDiff( 130 | git: GitCommandManager, 131 | branch1: string, 132 | branch2: string, 133 | depth: number 134 | ): Promise { 135 | // Some action use cases lead to the depth being a very large number and the diff fails. 136 | // I've made this check optional for now because it was a fix for an edge case that is 137 | // very rare, anyway. 138 | try { 139 | const diff1 = ( 140 | await git.exec(['diff', '--stat', `${branch1}..${branch1}~${depth}`]) 141 | ).stdout.trim() 142 | const diff2 = ( 143 | await git.exec(['diff', '--stat', `${branch2}..${branch2}~${depth}`]) 144 | ).stdout.trim() 145 | return diff1 !== diff2 146 | } catch (error) { 147 | core.info('Failed optional check of commits diff; Skipping.') 148 | core.debug(utils.getErrorMessage(error)) 149 | return false 150 | } 151 | } 152 | 153 | function splitLines(multilineString: string): string[] { 154 | return multilineString 155 | .split('\n') 156 | .map(s => s.trim()) 157 | .filter(x => x !== '') 158 | } 159 | 160 | interface CreateOrUpdateBranchResult { 161 | action: string 162 | base: string 163 | hasDiffWithBase: boolean 164 | baseCommit: Commit 165 | headSha: string 166 | branchCommits: Commit[] 167 | } 168 | 169 | export async function createOrUpdateBranch( 170 | git: GitCommandManager, 171 | commitMessage: string, 172 | base: string, 173 | branch: string, 174 | branchRemoteName: string, 175 | signoff: boolean, 176 | addPaths: string[] 177 | ): Promise { 178 | // Get the working base. 179 | // When a ref, it may or may not be the actual base. 180 | // When a commit, we must rebase onto the actual base. 181 | const [workingBase, workingBaseType] = await getWorkingBaseAndType(git) 182 | core.info(`Working base is ${workingBaseType} '${workingBase}'`) 183 | if (workingBaseType == WorkingBaseType.Commit && !base) { 184 | throw new Error(`When in 'detached HEAD' state, 'base' must be supplied.`) 185 | } 186 | 187 | // If the base is not specified it is assumed to be the working base. 188 | base = base ? base : workingBase 189 | const baseRemote = 'origin' 190 | 191 | // Save the working base changes to a temporary branch 192 | const tempBranch = uuidv4() 193 | await git.checkout(tempBranch, 'HEAD') 194 | // Commit any uncommitted changes 195 | if (await git.isDirty(true, addPaths)) { 196 | core.info('Uncommitted changes found. Adding a commit.') 197 | const aopts = ['add'] 198 | if (addPaths.length > 0) { 199 | aopts.push(...['--', ...addPaths]) 200 | } else { 201 | aopts.push('-A') 202 | } 203 | await git.exec(aopts, {allowAllExitCodes: true}) 204 | const popts = ['-m', commitMessage] 205 | if (signoff) { 206 | popts.push('--signoff') 207 | } 208 | const commitResult = await git.commit(popts, true) 209 | // 'nothing to commit' can occur when core.autocrlf is set to true 210 | if ( 211 | commitResult.exitCode != 0 && 212 | !commitResult.stdout.includes(NOTHING_TO_COMMIT) 213 | ) { 214 | throw new Error(`Unexpected error: ${commitResult.stderr}`) 215 | } 216 | } 217 | 218 | // Stash any uncommitted tracked and untracked changes 219 | const stashed = await git.stashPush(['--include-untracked']) 220 | 221 | // Reset the working base 222 | // Commits made during the workflow will be removed 223 | if (workingBaseType == WorkingBaseType.Branch) { 224 | core.info(`Resetting working base branch '${workingBase}'`) 225 | await git.checkout(workingBase) 226 | await git.exec(['reset', '--hard', `${baseRemote}/${workingBase}`]) 227 | } 228 | 229 | // If the working base is not the base, rebase the temp branch commits 230 | // This will also be true if the working base type is a commit 231 | if (workingBase != base) { 232 | core.info( 233 | `Rebasing commits made to ${workingBaseType} '${workingBase}' on to base branch '${base}'` 234 | ) 235 | const fetchArgs = ['--force'] 236 | if (branchRemoteName != 'fork') { 237 | // If pushing to a fork we cannot shallow fetch otherwise the 'shallow update not allowed' error occurs 238 | fetchArgs.push('--depth=1') 239 | } 240 | // Checkout the actual base 241 | await git.fetch([`${base}:${base}`], baseRemote, fetchArgs) 242 | await git.checkout(base) 243 | // Cherrypick commits from the temporary branch starting from the working base 244 | const commits = await git.revList( 245 | [`${workingBase}..${tempBranch}`, '.'], 246 | ['--reverse'] 247 | ) 248 | for (const commit of splitLines(commits)) { 249 | const result = await git.cherryPick( 250 | ['--strategy=recursive', '--strategy-option=theirs', commit], 251 | true 252 | ) 253 | if (result.exitCode != 0 && !result.stderr.includes(CHERRYPICK_EMPTY)) { 254 | throw new Error(`Unexpected error: ${result.stderr}`) 255 | } 256 | } 257 | // Reset the temp branch to the working index 258 | await git.checkout(tempBranch, 'HEAD') 259 | // Reset the base 260 | await git.fetch([`${base}:${base}`], baseRemote, fetchArgs) 261 | } 262 | 263 | // Determine the fetch depth for the pull request branch (best effort) 264 | const tempBranchCommitsAhead = await commitsAhead(git, base, tempBranch) 265 | const fetchDepth = 266 | tempBranchCommitsAhead > 0 267 | ? tempBranchCommitsAhead + FETCH_DEPTH_MARGIN 268 | : FETCH_DEPTH_MARGIN 269 | 270 | let action = 'none' 271 | let hasDiffWithBase = false 272 | 273 | // Try to fetch the pull request branch 274 | if (!(await tryFetch(git, branchRemoteName, branch, fetchDepth))) { 275 | // The pull request branch does not exist 276 | core.info(`Pull request branch '${branch}' does not exist yet.`) 277 | // Create the pull request branch 278 | await git.checkout(branch, tempBranch) 279 | // Check if the pull request branch is ahead of the base 280 | hasDiffWithBase = await isAhead(git, base, branch) 281 | if (hasDiffWithBase) { 282 | action = 'created' 283 | core.info(`Created branch '${branch}'`) 284 | } else { 285 | core.info( 286 | `Branch '${branch}' is not ahead of base '${base}' and will not be created` 287 | ) 288 | } 289 | } else { 290 | // The pull request branch exists 291 | core.info( 292 | `Pull request branch '${branch}' already exists as remote branch '${branchRemoteName}/${branch}'` 293 | ) 294 | // Checkout the pull request branch 295 | await git.checkout(branch) 296 | 297 | // Reset the branch if one of the following conditions is true. 298 | // - If the branch differs from the recreated temp branch. 299 | // - If the number of commits ahead of the base branch differs between the branch and 300 | // temp branch. This catches a case where the base branch has been force pushed to 301 | // a new commit. 302 | // - If the recreated temp branch is not ahead of the base. This means there will be 303 | // no pull request diff after the branch is reset. This will reset any undeleted 304 | // branches after merging. In particular, it catches a case where the branch was 305 | // squash merged but not deleted. We need to reset to make sure it doesn't appear 306 | // to have a diff with the base due to different commits for the same changes. 307 | // - If the diff of the commits ahead of the base branch differs between the branch and 308 | // temp branch. This catches a case where changes have been partially merged to the 309 | // base. The overall diff is the same, but the branch needs to be rebased to show 310 | // the correct diff. 311 | // 312 | // For changes on base this reset is equivalent to a rebase of the pull request branch. 313 | const branchCommitsAhead = await commitsAhead(git, base, branch) 314 | if ( 315 | (await git.hasDiff([`${branch}..${tempBranch}`])) || 316 | branchCommitsAhead != tempBranchCommitsAhead || 317 | !(tempBranchCommitsAhead > 0) || // !isAhead 318 | (await commitsHaveDiff(git, branch, tempBranch, tempBranchCommitsAhead)) 319 | ) { 320 | core.info(`Resetting '${branch}'`) 321 | // Alternatively, git switch -C branch tempBranch 322 | await git.checkout(branch, tempBranch) 323 | } 324 | 325 | // Check if the pull request branch has been updated 326 | // If the branch was reset or updated it will be ahead 327 | // It may be behind if a reset now results in no diff with the base 328 | if (!(await isEven(git, `${branchRemoteName}/${branch}`, branch))) { 329 | action = 'updated' 330 | core.info(`Updated branch '${branch}'`) 331 | } else { 332 | action = 'not-updated' 333 | core.info( 334 | `Branch '${branch}' is even with its remote and will not be updated` 335 | ) 336 | } 337 | 338 | // Check if the pull request branch is ahead of the base 339 | hasDiffWithBase = await isAhead(git, base, branch) 340 | } 341 | 342 | // Get the base and head SHAs 343 | const baseSha = await git.revParse(base) 344 | const baseCommit = await git.getCommit(baseSha) 345 | const headSha = await git.revParse(branch) 346 | 347 | let branchCommits: Commit[] = [] 348 | if (hasDiffWithBase) { 349 | // Build the branch commits 350 | branchCommits = await buildBranchCommits(git, base, branch) 351 | } 352 | 353 | // Delete the temporary branch 354 | await git.exec(['branch', '--delete', '--force', tempBranch]) 355 | 356 | // Checkout the working base to leave the local repository as it was found 357 | await git.checkout(workingBase) 358 | 359 | // Restore any stashed changes 360 | if (stashed) { 361 | await git.stashPop() 362 | } 363 | 364 | return { 365 | action: action, 366 | base: base, 367 | hasDiffWithBase: hasDiffWithBase, 368 | baseCommit: baseCommit, 369 | headSha: headSha, 370 | branchCommits: branchCommits 371 | } 372 | } 373 | -------------------------------------------------------------------------------- /src/create-pull-request.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import { 3 | createOrUpdateBranch, 4 | getWorkingBaseAndType, 5 | WorkingBaseType 6 | } from './create-or-update-branch' 7 | import {GitHubHelper} from './github-helper' 8 | import {GitCommandManager} from './git-command-manager' 9 | import {GitConfigHelper} from './git-config-helper' 10 | import * as utils from './utils' 11 | 12 | export interface Inputs { 13 | token: string 14 | branchToken: string 15 | path: string 16 | addPaths: string[] 17 | commitMessage: string 18 | committer: string 19 | author: string 20 | signoff: boolean 21 | branch: string 22 | deleteBranch: boolean 23 | branchSuffix: string 24 | base: string 25 | pushToFork: string 26 | signCommits: boolean 27 | title: string 28 | body: string 29 | bodyPath: string 30 | labels: string[] 31 | assignees: string[] 32 | reviewers: string[] 33 | teamReviewers: string[] 34 | milestone: number 35 | draft: { 36 | value: boolean 37 | always: boolean 38 | } 39 | maintainerCanModify: boolean 40 | } 41 | 42 | export async function createPullRequest(inputs: Inputs): Promise { 43 | let gitConfigHelper, git 44 | try { 45 | core.startGroup('Prepare git configuration') 46 | const repoPath = utils.getRepoPath(inputs.path) 47 | git = await GitCommandManager.create(repoPath) 48 | gitConfigHelper = await GitConfigHelper.create(git) 49 | core.endGroup() 50 | 51 | core.startGroup('Determining the base and head repositories') 52 | const baseRemote = gitConfigHelper.getGitRemote() 53 | // Init the GitHub clients 54 | const ghBranch = new GitHubHelper(baseRemote.hostname, inputs.branchToken) 55 | const ghPull = new GitHubHelper(baseRemote.hostname, inputs.token) 56 | // Determine the head repository; the target for the pull request branch 57 | const branchRemoteName = inputs.pushToFork ? 'fork' : 'origin' 58 | const branchRepository = inputs.pushToFork 59 | ? inputs.pushToFork 60 | : baseRemote.repository 61 | if (inputs.pushToFork) { 62 | // Check if the supplied fork is really a fork of the base 63 | core.info( 64 | `Checking if '${branchRepository}' is a fork of '${baseRemote.repository}'` 65 | ) 66 | const baseParentRepository = await ghBranch.getRepositoryParent( 67 | baseRemote.repository 68 | ) 69 | const branchParentRepository = 70 | await ghBranch.getRepositoryParent(branchRepository) 71 | if (branchParentRepository == null) { 72 | throw new Error( 73 | `Repository '${branchRepository}' is not a fork. Unable to continue.` 74 | ) 75 | } 76 | if ( 77 | branchParentRepository != baseRemote.repository && 78 | baseParentRepository != branchParentRepository 79 | ) { 80 | throw new Error( 81 | `Repository '${branchRepository}' is not a fork of '${baseRemote.repository}', nor are they siblings. Unable to continue.` 82 | ) 83 | } 84 | // Add a remote for the fork 85 | const remoteUrl = utils.getRemoteUrl( 86 | baseRemote.protocol, 87 | baseRemote.hostname, 88 | branchRepository 89 | ) 90 | await git.exec(['remote', 'add', 'fork', remoteUrl]) 91 | } 92 | core.endGroup() 93 | core.info( 94 | `Pull request branch target repository set to ${branchRepository}` 95 | ) 96 | 97 | // Configure auth 98 | if (baseRemote.protocol == 'HTTPS') { 99 | core.startGroup('Configuring credential for HTTPS authentication') 100 | await gitConfigHelper.configureToken(inputs.branchToken) 101 | core.endGroup() 102 | } 103 | 104 | core.startGroup('Checking the base repository state') 105 | const [workingBase, workingBaseType] = await getWorkingBaseAndType(git) 106 | core.info(`Working base is ${workingBaseType} '${workingBase}'`) 107 | // When in detached HEAD state (checked out on a commit), we need to 108 | // know the 'base' branch in order to rebase changes. 109 | if (workingBaseType == WorkingBaseType.Commit && !inputs.base) { 110 | throw new Error( 111 | `When the repository is checked out on a commit instead of a branch, the 'base' input must be supplied.` 112 | ) 113 | } 114 | // If the base is not specified it is assumed to be the working base. 115 | const base = inputs.base ? inputs.base : workingBase 116 | // Throw an error if the base and branch are not different branches 117 | // of the 'origin' remote. An identically named branch in the `fork` 118 | // remote is perfectly fine. 119 | if (branchRemoteName == 'origin' && base == inputs.branch) { 120 | throw new Error( 121 | `The 'base' and 'branch' for a pull request must be different branches. Unable to continue.` 122 | ) 123 | } 124 | // For self-hosted runners the repository state persists between runs. 125 | // This command prunes the stale remote ref when the pull request branch was 126 | // deleted after being merged or closed. Without this the push using 127 | // '--force-with-lease' fails due to "stale info." 128 | // https://github.com/peter-evans/create-pull-request/issues/633 129 | await git.exec(['remote', 'prune', branchRemoteName]) 130 | core.endGroup() 131 | 132 | // Apply the branch suffix if set 133 | if (inputs.branchSuffix) { 134 | switch (inputs.branchSuffix) { 135 | case 'short-commit-hash': 136 | // Suffix with the short SHA1 hash 137 | inputs.branch = `${inputs.branch}-${await git.revParse('HEAD', [ 138 | '--short' 139 | ])}` 140 | break 141 | case 'timestamp': 142 | // Suffix with the current timestamp 143 | inputs.branch = `${inputs.branch}-${utils.secondsSinceEpoch()}` 144 | break 145 | case 'random': 146 | // Suffix with a 7 character random string 147 | inputs.branch = `${inputs.branch}-${utils.randomString()}` 148 | break 149 | default: 150 | throw new Error( 151 | `Branch suffix '${inputs.branchSuffix}' is not a valid value. Unable to continue.` 152 | ) 153 | } 154 | } 155 | 156 | // Output head branch 157 | core.info( 158 | `Pull request branch to create or update set to '${inputs.branch}'` 159 | ) 160 | 161 | // Configure the committer and author 162 | core.startGroup('Configuring the committer and author') 163 | const parsedAuthor = utils.parseDisplayNameEmail(inputs.author) 164 | const parsedCommitter = utils.parseDisplayNameEmail(inputs.committer) 165 | git.setIdentityGitOptions([ 166 | '-c', 167 | `author.name=${parsedAuthor.name}`, 168 | '-c', 169 | `author.email=${parsedAuthor.email}`, 170 | '-c', 171 | `committer.name=${parsedCommitter.name}`, 172 | '-c', 173 | `committer.email=${parsedCommitter.email}` 174 | ]) 175 | core.info( 176 | `Configured git committer as '${parsedCommitter.name} <${parsedCommitter.email}>'` 177 | ) 178 | core.info( 179 | `Configured git author as '${parsedAuthor.name} <${parsedAuthor.email}>'` 180 | ) 181 | core.endGroup() 182 | 183 | // Action outputs 184 | const outputs = new Map() 185 | outputs.set('pull-request-branch', inputs.branch) 186 | outputs.set('pull-request-operation', 'none') 187 | 188 | // Create or update the pull request branch 189 | core.startGroup('Create or update the pull request branch') 190 | const result = await createOrUpdateBranch( 191 | git, 192 | inputs.commitMessage, 193 | inputs.base, 194 | inputs.branch, 195 | branchRemoteName, 196 | inputs.signoff, 197 | inputs.addPaths 198 | ) 199 | outputs.set('pull-request-head-sha', result.headSha) 200 | // Set the base. It would have been '' if not specified as an input 201 | inputs.base = result.base 202 | core.endGroup() 203 | 204 | if (['created', 'updated'].includes(result.action)) { 205 | // The branch was created or updated 206 | core.startGroup( 207 | `Pushing pull request branch to '${branchRemoteName}/${inputs.branch}'` 208 | ) 209 | if (inputs.signCommits) { 210 | // Create signed commits via the GitHub API 211 | const stashed = await git.stashPush(['--include-untracked']) 212 | await git.checkout(inputs.branch) 213 | const pushSignedCommitsResult = await ghBranch.pushSignedCommits( 214 | git, 215 | result.branchCommits, 216 | result.baseCommit, 217 | repoPath, 218 | branchRepository, 219 | inputs.branch 220 | ) 221 | outputs.set('pull-request-head-sha', pushSignedCommitsResult.sha) 222 | outputs.set( 223 | 'pull-request-commits-verified', 224 | pushSignedCommitsResult.verified.toString() 225 | ) 226 | await git.checkout('-') 227 | if (stashed) { 228 | await git.stashPop() 229 | } 230 | } else { 231 | await git.push([ 232 | '--force-with-lease', 233 | branchRemoteName, 234 | `${inputs.branch}:refs/heads/${inputs.branch}` 235 | ]) 236 | } 237 | core.endGroup() 238 | } 239 | 240 | if (result.hasDiffWithBase) { 241 | core.startGroup('Create or update the pull request') 242 | const pull = await ghPull.createOrUpdatePullRequest( 243 | inputs, 244 | baseRemote.repository, 245 | branchRepository 246 | ) 247 | outputs.set('pull-request-number', pull.number.toString()) 248 | outputs.set('pull-request-url', pull.html_url) 249 | if (pull.created) { 250 | outputs.set('pull-request-operation', 'created') 251 | } else if (result.action == 'updated') { 252 | outputs.set('pull-request-operation', 'updated') 253 | // The pull request was updated AND the branch was updated. 254 | // Convert back to draft if 'draft: always-true' is set. 255 | if (inputs.draft.always && pull.draft !== undefined && !pull.draft) { 256 | await ghPull.convertToDraft(pull.node_id) 257 | } 258 | } 259 | core.endGroup() 260 | } else { 261 | // There is no longer a diff with the base 262 | // Check we are in a state where a branch exists 263 | if (['updated', 'not-updated'].includes(result.action)) { 264 | core.info( 265 | `Branch '${inputs.branch}' no longer differs from base branch '${inputs.base}'` 266 | ) 267 | if (inputs.deleteBranch) { 268 | core.info(`Deleting branch '${inputs.branch}'`) 269 | await git.push([ 270 | '--delete', 271 | '--force', 272 | branchRemoteName, 273 | `refs/heads/${inputs.branch}` 274 | ]) 275 | outputs.set('pull-request-operation', 'closed') 276 | } 277 | } 278 | } 279 | 280 | core.startGroup('Setting outputs') 281 | // If the head commit is signed, get its verification status if we don't already know it. 282 | // This can happen if the branch wasn't updated (action = 'not-updated'), or GPG commit signing is in use. 283 | if ( 284 | !outputs.has('pull-request-commits-verified') && 285 | result.branchCommits.length > 0 && 286 | result.branchCommits[result.branchCommits.length - 1].signed 287 | ) { 288 | // Using the local head commit SHA because in this case commits have not been pushed via the API. 289 | core.info(`Checking verification status of head commit ${result.headSha}`) 290 | try { 291 | const headCommit = await ghBranch.getCommit( 292 | result.headSha, 293 | branchRepository 294 | ) 295 | outputs.set( 296 | 'pull-request-commits-verified', 297 | headCommit.verified.toString() 298 | ) 299 | } catch (error) { 300 | core.warning('Failed to check verification status of head commit.') 301 | core.debug(utils.getErrorMessage(error)) 302 | } 303 | } 304 | if (!outputs.has('pull-request-commits-verified')) { 305 | outputs.set('pull-request-commits-verified', 'false') 306 | } 307 | 308 | // Set outputs 309 | for (const [key, value] of outputs) { 310 | core.info(`${key} = ${value}`) 311 | core.setOutput(key, value) 312 | } 313 | core.endGroup() 314 | } catch (error) { 315 | core.setFailed(utils.getErrorMessage(error)) 316 | } finally { 317 | core.startGroup('Restore git configuration') 318 | if (inputs.pushToFork) { 319 | await git.exec(['remote', 'rm', 'fork']) 320 | } 321 | await gitConfigHelper.close() 322 | core.endGroup() 323 | } 324 | } 325 | -------------------------------------------------------------------------------- /src/git-command-manager.ts: -------------------------------------------------------------------------------- 1 | import * as exec from '@actions/exec' 2 | import * as io from '@actions/io' 3 | import * as utils from './utils' 4 | import * as path from 'path' 5 | import stream, {Writable} from 'stream' 6 | 7 | const tagsRefSpec = '+refs/tags/*:refs/tags/*' 8 | 9 | export type Commit = { 10 | sha: string 11 | tree: string 12 | parents: string[] 13 | signed: boolean 14 | subject: string 15 | body: string 16 | changes: { 17 | mode: string 18 | dstSha: string 19 | status: 'A' | 'M' | 'D' 20 | path: string 21 | }[] 22 | unparsedChanges: string[] 23 | } 24 | 25 | export type ExecOpts = { 26 | allowAllExitCodes?: boolean 27 | encoding?: 'utf8' | 'base64' 28 | suppressGitCmdOutput?: boolean 29 | } 30 | 31 | export class GitCommandManager { 32 | private gitPath: string 33 | private workingDirectory: string 34 | // Git options used when commands require an identity 35 | private identityGitOptions?: string[] 36 | 37 | private constructor(workingDirectory: string, gitPath: string) { 38 | this.workingDirectory = workingDirectory 39 | this.gitPath = gitPath 40 | } 41 | 42 | static async create(workingDirectory: string): Promise { 43 | const gitPath = await io.which('git', true) 44 | return new GitCommandManager(workingDirectory, gitPath) 45 | } 46 | 47 | setIdentityGitOptions(identityGitOptions: string[]): void { 48 | this.identityGitOptions = identityGitOptions 49 | } 50 | 51 | async checkout(ref: string, startPoint?: string): Promise { 52 | const args = ['checkout', '--progress'] 53 | if (startPoint) { 54 | args.push('-B', ref, startPoint) 55 | } else { 56 | args.push(ref) 57 | } 58 | // https://github.com/git/git/commit/a047fafc7866cc4087201e284dc1f53e8f9a32d5 59 | args.push('--') 60 | await this.exec(args) 61 | } 62 | 63 | async cherryPick( 64 | options?: string[], 65 | allowAllExitCodes = false 66 | ): Promise { 67 | const args = ['cherry-pick'] 68 | if (this.identityGitOptions) { 69 | args.unshift(...this.identityGitOptions) 70 | } 71 | 72 | if (options) { 73 | args.push(...options) 74 | } 75 | 76 | return await this.exec(args, {allowAllExitCodes: allowAllExitCodes}) 77 | } 78 | 79 | async commit( 80 | options?: string[], 81 | allowAllExitCodes = false 82 | ): Promise { 83 | const args = ['commit'] 84 | if (this.identityGitOptions) { 85 | args.unshift(...this.identityGitOptions) 86 | } 87 | 88 | if (options) { 89 | args.push(...options) 90 | } 91 | 92 | return await this.exec(args, {allowAllExitCodes: allowAllExitCodes}) 93 | } 94 | 95 | async config( 96 | configKey: string, 97 | configValue: string, 98 | globalConfig?: boolean, 99 | add?: boolean 100 | ): Promise { 101 | const args: string[] = ['config', globalConfig ? '--global' : '--local'] 102 | if (add) { 103 | args.push('--add') 104 | } 105 | args.push(...[configKey, configValue]) 106 | await this.exec(args) 107 | } 108 | 109 | async configExists( 110 | configKey: string, 111 | configValue = '.', 112 | globalConfig?: boolean 113 | ): Promise { 114 | const output = await this.exec( 115 | [ 116 | 'config', 117 | globalConfig ? '--global' : '--local', 118 | '--name-only', 119 | '--get-regexp', 120 | configKey, 121 | configValue 122 | ], 123 | {allowAllExitCodes: true} 124 | ) 125 | return output.exitCode === 0 126 | } 127 | 128 | async fetch( 129 | refSpec: string[], 130 | remoteName?: string, 131 | options?: string[], 132 | unshallow = false 133 | ): Promise { 134 | const args = ['-c', 'protocol.version=2', 'fetch'] 135 | if (!refSpec.some(x => x === tagsRefSpec)) { 136 | args.push('--no-tags') 137 | } 138 | 139 | args.push('--progress', '--no-recurse-submodules') 140 | 141 | if ( 142 | unshallow && 143 | utils.fileExistsSync(path.join(this.workingDirectory, '.git', 'shallow')) 144 | ) { 145 | args.push('--unshallow') 146 | } 147 | 148 | if (options) { 149 | args.push(...options) 150 | } 151 | 152 | if (remoteName) { 153 | args.push(remoteName) 154 | } else { 155 | args.push('origin') 156 | } 157 | for (const arg of refSpec) { 158 | args.push(arg) 159 | } 160 | 161 | await this.exec(args) 162 | } 163 | 164 | async getCommit(ref: string): Promise { 165 | const endOfBody = '###EOB###' 166 | const output = await this.exec( 167 | [ 168 | '-c', 169 | 'core.quotePath=false', 170 | 'show', 171 | '--raw', 172 | '--cc', 173 | '--no-renames', 174 | '--no-abbrev', 175 | `--format=%H%n%T%n%P%n%G?%n%s%n%b%n${endOfBody}`, 176 | ref 177 | ], 178 | {suppressGitCmdOutput: true} 179 | ) 180 | const lines = output.stdout.split('\n') 181 | const endOfBodyIndex = lines.lastIndexOf(endOfBody) 182 | const detailLines = lines.slice(0, endOfBodyIndex) 183 | 184 | const unparsedChanges: string[] = [] 185 | return { 186 | sha: detailLines[0], 187 | tree: detailLines[1], 188 | parents: detailLines[2].split(' '), 189 | signed: detailLines[3] !== 'N', 190 | subject: detailLines[4], 191 | body: detailLines.slice(5, endOfBodyIndex).join('\n'), 192 | changes: lines.slice(endOfBodyIndex + 2, -1).map(line => { 193 | const change = line.match( 194 | /^:(\d{6}) (\d{6}) \w{40} (\w{40}) ([AMD])\s+(.*)$/ 195 | ) 196 | if (change) { 197 | return { 198 | mode: change[4] === 'D' ? change[1] : change[2], 199 | dstSha: change[3], 200 | status: change[4], 201 | path: change[5] 202 | } 203 | } else { 204 | unparsedChanges.push(line) 205 | } 206 | }), 207 | unparsedChanges: unparsedChanges 208 | } 209 | } 210 | 211 | async getConfigValue(configKey: string, configValue = '.'): Promise { 212 | const output = await this.exec([ 213 | 'config', 214 | '--local', 215 | '--get-regexp', 216 | configKey, 217 | configValue 218 | ]) 219 | return output.stdout.trim().split(`${configKey} `)[1] 220 | } 221 | 222 | getGitDirectory(): Promise { 223 | return this.revParse('--git-dir') 224 | } 225 | 226 | getWorkingDirectory(): string { 227 | return this.workingDirectory 228 | } 229 | 230 | async hasDiff(options?: string[]): Promise { 231 | const args = ['diff', '--quiet'] 232 | if (options) { 233 | args.push(...options) 234 | } 235 | const output = await this.exec(args, {allowAllExitCodes: true}) 236 | return output.exitCode === 1 237 | } 238 | 239 | async isDirty(untracked: boolean, pathspec?: string[]): Promise { 240 | const pathspecArgs = pathspec ? ['--', ...pathspec] : [] 241 | // Check untracked changes 242 | const sargs = ['--porcelain', '-unormal'] 243 | sargs.push(...pathspecArgs) 244 | if (untracked && (await this.status(sargs))) { 245 | return true 246 | } 247 | // Check working index changes 248 | if (await this.hasDiff(pathspecArgs)) { 249 | return true 250 | } 251 | // Check staged changes 252 | const dargs = ['--staged'] 253 | dargs.push(...pathspecArgs) 254 | if (await this.hasDiff(dargs)) { 255 | return true 256 | } 257 | return false 258 | } 259 | 260 | async push(options?: string[]): Promise { 261 | const args = ['push'] 262 | if (options) { 263 | args.push(...options) 264 | } 265 | await this.exec(args) 266 | } 267 | 268 | async revList( 269 | commitExpression: string[], 270 | options?: string[] 271 | ): Promise { 272 | const args = ['rev-list'] 273 | if (options) { 274 | args.push(...options) 275 | } 276 | args.push(...commitExpression) 277 | const output = await this.exec(args) 278 | return output.stdout.trim() 279 | } 280 | 281 | async revParse(ref: string, options?: string[]): Promise { 282 | const args = ['rev-parse'] 283 | if (options) { 284 | args.push(...options) 285 | } 286 | args.push(ref) 287 | const output = await this.exec(args) 288 | return output.stdout.trim() 289 | } 290 | 291 | async showFileAtRefBase64(ref: string, path: string): Promise { 292 | const args = ['show', `${ref}:${path}`] 293 | const output = await this.exec(args, { 294 | encoding: 'base64', 295 | suppressGitCmdOutput: true 296 | }) 297 | return output.stdout.trim() 298 | } 299 | 300 | async stashPush(options?: string[]): Promise { 301 | const args = ['stash', 'push'] 302 | if (options) { 303 | args.push(...options) 304 | } 305 | const output = await this.exec(args) 306 | return output.stdout.trim() !== 'No local changes to save' 307 | } 308 | 309 | async stashPop(options?: string[]): Promise { 310 | const args = ['stash', 'pop'] 311 | if (options) { 312 | args.push(...options) 313 | } 314 | await this.exec(args) 315 | } 316 | 317 | async status(options?: string[]): Promise { 318 | const args = ['status'] 319 | if (options) { 320 | args.push(...options) 321 | } 322 | const output = await this.exec(args) 323 | return output.stdout.trim() 324 | } 325 | 326 | async symbolicRef(ref: string, options?: string[]): Promise { 327 | const args = ['symbolic-ref', ref] 328 | if (options) { 329 | args.push(...options) 330 | } 331 | const output = await this.exec(args) 332 | return output.stdout.trim() 333 | } 334 | 335 | async tryConfigUnset( 336 | configKey: string, 337 | configValue = '.', 338 | globalConfig?: boolean 339 | ): Promise { 340 | const output = await this.exec( 341 | [ 342 | 'config', 343 | globalConfig ? '--global' : '--local', 344 | '--unset', 345 | configKey, 346 | configValue 347 | ], 348 | {allowAllExitCodes: true} 349 | ) 350 | return output.exitCode === 0 351 | } 352 | 353 | async tryGetRemoteUrl(): Promise { 354 | const output = await this.exec( 355 | ['config', '--local', '--get', 'remote.origin.url'], 356 | {allowAllExitCodes: true} 357 | ) 358 | 359 | if (output.exitCode !== 0) { 360 | return '' 361 | } 362 | 363 | const stdout = output.stdout.trim() 364 | if (stdout.includes('\n')) { 365 | return '' 366 | } 367 | 368 | return stdout 369 | } 370 | 371 | async exec( 372 | args: string[], 373 | { 374 | encoding = 'utf8', 375 | allowAllExitCodes = false, 376 | suppressGitCmdOutput = false 377 | }: ExecOpts = {} 378 | ): Promise { 379 | const result = new GitOutput() 380 | 381 | if (process.env['CPR_SHOW_GIT_CMD_OUTPUT']) { 382 | // debug mode overrides the suppressGitCmdOutput option 383 | suppressGitCmdOutput = false 384 | } 385 | 386 | const env = {} 387 | for (const key of Object.keys(process.env)) { 388 | env[key] = process.env[key] 389 | } 390 | 391 | const stdout: Buffer[] = [] 392 | let stdoutLength = 0 393 | const stderr: Buffer[] = [] 394 | let stderrLength = 0 395 | 396 | const options = { 397 | cwd: this.workingDirectory, 398 | env, 399 | ignoreReturnCode: allowAllExitCodes, 400 | listeners: { 401 | stdout: (data: Buffer) => { 402 | stdout.push(data) 403 | stdoutLength += data.length 404 | }, 405 | stderr: (data: Buffer) => { 406 | stderr.push(data) 407 | stderrLength += data.length 408 | } 409 | }, 410 | outStream: outStreamHandler(process.stdout, suppressGitCmdOutput), 411 | errStream: outStreamHandler(process.stderr, suppressGitCmdOutput) 412 | } 413 | 414 | result.exitCode = await exec.exec(`"${this.gitPath}"`, args, options) 415 | result.stdout = Buffer.concat(stdout, stdoutLength).toString(encoding) 416 | result.stderr = Buffer.concat(stderr, stderrLength).toString(encoding) 417 | return result 418 | } 419 | } 420 | 421 | class GitOutput { 422 | stdout = '' 423 | stderr = '' 424 | exitCode = 0 425 | } 426 | 427 | const outStreamHandler = ( 428 | outStream: Writable, 429 | suppressGitCmdOutput: boolean 430 | ): Writable => { 431 | return new stream.Writable({ 432 | write(chunk, _, next) { 433 | if (suppressGitCmdOutput) { 434 | const lines = chunk.toString().trimEnd().split('\n') 435 | for (const line of lines) { 436 | if (line.startsWith('[command]')) { 437 | outStream.write(`${line}\n`) 438 | } 439 | } 440 | } else { 441 | outStream.write(chunk) 442 | } 443 | next() 444 | } 445 | }) 446 | } 447 | -------------------------------------------------------------------------------- /src/git-config-helper.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import * as fs from 'fs' 3 | import {GitCommandManager} from './git-command-manager' 4 | import * as path from 'path' 5 | import {URL} from 'url' 6 | import * as utils from './utils' 7 | 8 | interface GitRemote { 9 | hostname: string 10 | protocol: string 11 | repository: string 12 | } 13 | 14 | export class GitConfigHelper { 15 | private git: GitCommandManager 16 | private gitConfigPath = '' 17 | private workingDirectory: string 18 | private safeDirectoryConfigKey = 'safe.directory' 19 | private safeDirectoryAdded = false 20 | private remoteUrl = '' 21 | private extraheaderConfigKey = '' 22 | private extraheaderConfigPlaceholderValue = 'AUTHORIZATION: basic ***' 23 | private extraheaderConfigValueRegex = '^AUTHORIZATION:' 24 | private persistedExtraheaderConfigValue = '' 25 | 26 | private constructor(git: GitCommandManager) { 27 | this.git = git 28 | this.workingDirectory = this.git.getWorkingDirectory() 29 | } 30 | 31 | static async create(git: GitCommandManager): Promise { 32 | const gitConfigHelper = new GitConfigHelper(git) 33 | await gitConfigHelper.addSafeDirectory() 34 | await gitConfigHelper.fetchRemoteDetail() 35 | await gitConfigHelper.savePersistedAuth() 36 | return gitConfigHelper 37 | } 38 | 39 | async close(): Promise { 40 | // Remove auth and restore persisted auth config if it existed 41 | await this.removeAuth() 42 | await this.restorePersistedAuth() 43 | await this.removeSafeDirectory() 44 | } 45 | 46 | async addSafeDirectory(): Promise { 47 | const exists = await this.git.configExists( 48 | this.safeDirectoryConfigKey, 49 | this.workingDirectory, 50 | true 51 | ) 52 | if (!exists) { 53 | await this.git.config( 54 | this.safeDirectoryConfigKey, 55 | this.workingDirectory, 56 | true, 57 | true 58 | ) 59 | this.safeDirectoryAdded = true 60 | } 61 | } 62 | 63 | async removeSafeDirectory(): Promise { 64 | if (this.safeDirectoryAdded) { 65 | await this.git.tryConfigUnset( 66 | this.safeDirectoryConfigKey, 67 | this.workingDirectory, 68 | true 69 | ) 70 | } 71 | } 72 | 73 | async fetchRemoteDetail(): Promise { 74 | this.remoteUrl = await this.git.tryGetRemoteUrl() 75 | } 76 | 77 | getGitRemote(): GitRemote { 78 | return GitConfigHelper.parseGitRemote(this.remoteUrl) 79 | } 80 | 81 | static parseGitRemote(remoteUrl: string): GitRemote { 82 | const httpsUrlPattern = new RegExp( 83 | '^(https?)://(?:.+@)?(.+?)/(.+/.+?)(\\.git)?$', 84 | 'i' 85 | ) 86 | const httpsMatch = remoteUrl.match(httpsUrlPattern) 87 | if (httpsMatch) { 88 | return { 89 | hostname: httpsMatch[2], 90 | protocol: 'HTTPS', 91 | repository: httpsMatch[3] 92 | } 93 | } 94 | 95 | const sshUrlPattern = new RegExp('^git@(.+?):(.+/.+)\\.git$', 'i') 96 | const sshMatch = remoteUrl.match(sshUrlPattern) 97 | if (sshMatch) { 98 | return { 99 | hostname: sshMatch[1], 100 | protocol: 'SSH', 101 | repository: sshMatch[2] 102 | } 103 | } 104 | 105 | // Unauthenticated git protocol for integration tests only 106 | const gitUrlPattern = new RegExp('^git://(.+?)/(.+/.+)\\.git$', 'i') 107 | const gitMatch = remoteUrl.match(gitUrlPattern) 108 | if (gitMatch) { 109 | return { 110 | hostname: gitMatch[1], 111 | protocol: 'GIT', 112 | repository: gitMatch[2] 113 | } 114 | } 115 | 116 | throw new Error( 117 | `The format of '${remoteUrl}' is not a valid GitHub repository URL` 118 | ) 119 | } 120 | 121 | async savePersistedAuth(): Promise { 122 | const serverUrl = new URL(`https://${this.getGitRemote().hostname}`) 123 | this.extraheaderConfigKey = `http.${serverUrl.origin}/.extraheader` 124 | // Save and unset persisted extraheader credential in git config if it exists 125 | this.persistedExtraheaderConfigValue = await this.getAndUnset() 126 | } 127 | 128 | async restorePersistedAuth(): Promise { 129 | if (this.persistedExtraheaderConfigValue) { 130 | try { 131 | await this.setExtraheaderConfig(this.persistedExtraheaderConfigValue) 132 | core.info('Persisted git credentials restored') 133 | } catch (e) { 134 | core.warning(utils.getErrorMessage(e)) 135 | } 136 | } 137 | } 138 | 139 | async configureToken(token: string): Promise { 140 | // Encode and configure the basic credential for HTTPS access 141 | const basicCredential = Buffer.from( 142 | `x-access-token:${token}`, 143 | 'utf8' 144 | ).toString('base64') 145 | core.setSecret(basicCredential) 146 | const extraheaderConfigValue = `AUTHORIZATION: basic ${basicCredential}` 147 | await this.setExtraheaderConfig(extraheaderConfigValue) 148 | } 149 | 150 | async removeAuth(): Promise { 151 | await this.getAndUnset() 152 | } 153 | 154 | private async setExtraheaderConfig( 155 | extraheaderConfigValue: string 156 | ): Promise { 157 | // Configure a placeholder value. This approach avoids the credential being captured 158 | // by process creation audit events, which are commonly logged. For more information, 159 | // refer to https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing 160 | // See https://github.com/actions/checkout/blob/main/src/git-auth-helper.ts#L267-L274 161 | await this.git.config( 162 | this.extraheaderConfigKey, 163 | this.extraheaderConfigPlaceholderValue 164 | ) 165 | // Replace the placeholder 166 | await this.gitConfigStringReplace( 167 | this.extraheaderConfigPlaceholderValue, 168 | extraheaderConfigValue 169 | ) 170 | } 171 | 172 | private async getAndUnset(): Promise { 173 | let configValue = '' 174 | // Save and unset persisted extraheader credential in git config if it exists 175 | if ( 176 | await this.git.configExists( 177 | this.extraheaderConfigKey, 178 | this.extraheaderConfigValueRegex 179 | ) 180 | ) { 181 | configValue = await this.git.getConfigValue( 182 | this.extraheaderConfigKey, 183 | this.extraheaderConfigValueRegex 184 | ) 185 | if ( 186 | await this.git.tryConfigUnset( 187 | this.extraheaderConfigKey, 188 | this.extraheaderConfigValueRegex 189 | ) 190 | ) { 191 | core.info(`Unset config key '${this.extraheaderConfigKey}'`) 192 | } else { 193 | core.warning( 194 | `Failed to unset config key '${this.extraheaderConfigKey}'` 195 | ) 196 | } 197 | } 198 | return configValue 199 | } 200 | 201 | private async gitConfigStringReplace( 202 | find: string, 203 | replace: string 204 | ): Promise { 205 | if (this.gitConfigPath.length === 0) { 206 | const gitDir = await this.git.getGitDirectory() 207 | this.gitConfigPath = path.join(this.workingDirectory, gitDir, 'config') 208 | } 209 | let content = (await fs.promises.readFile(this.gitConfigPath)).toString() 210 | const index = content.indexOf(find) 211 | if (index < 0 || index != content.lastIndexOf(find)) { 212 | throw new Error(`Unable to replace '${find}' in ${this.gitConfigPath}`) 213 | } 214 | content = content.replace(find, replace) 215 | await fs.promises.writeFile(this.gitConfigPath, content) 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /src/github-helper.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import {Inputs} from './create-pull-request' 3 | import {Commit, GitCommandManager} from './git-command-manager' 4 | import {Octokit, OctokitOptions, throttleOptions} from './octokit-client' 5 | import pLimit from 'p-limit' 6 | import * as utils from './utils' 7 | 8 | const ERROR_PR_ALREADY_EXISTS = 'A pull request already exists for' 9 | const ERROR_PR_REVIEW_TOKEN_SCOPE = 10 | 'Validation Failed: "Could not resolve to a node with the global id of' 11 | const ERROR_PR_FORK_COLLAB = `Fork collab can't be granted by someone without permission` 12 | 13 | const blobCreationLimit = pLimit(8) 14 | 15 | interface Repository { 16 | owner: string 17 | repo: string 18 | } 19 | 20 | interface Pull { 21 | number: number 22 | html_url: string 23 | node_id: string 24 | draft?: boolean 25 | created: boolean 26 | } 27 | 28 | interface CommitResponse { 29 | sha: string 30 | tree: string 31 | verified: boolean 32 | } 33 | 34 | type TreeObject = { 35 | path: string 36 | mode: '100644' | '100755' | '040000' | '160000' | '120000' 37 | sha: string | null 38 | type: 'blob' | 'commit' 39 | } 40 | 41 | export class GitHubHelper { 42 | private octokit: InstanceType 43 | 44 | constructor(githubServerHostname: string, token: string) { 45 | const options: OctokitOptions = {} 46 | if (token) { 47 | options.auth = `${token}` 48 | } 49 | if (githubServerHostname !== 'github.com') { 50 | options.baseUrl = `https://${githubServerHostname}/api/v3` 51 | } else { 52 | options.baseUrl = 'https://api.github.com' 53 | } 54 | options.throttle = throttleOptions 55 | this.octokit = new Octokit(options) 56 | } 57 | 58 | private parseRepository(repository: string): Repository { 59 | const [owner, repo] = repository.split('/') 60 | return { 61 | owner: owner, 62 | repo: repo 63 | } 64 | } 65 | 66 | private async createOrUpdate( 67 | inputs: Inputs, 68 | baseRepository: string, 69 | headRepository: string 70 | ): Promise { 71 | const [headOwner] = headRepository.split('/') 72 | const headBranch = `${headOwner}:${inputs.branch}` 73 | 74 | // Try to create the pull request 75 | try { 76 | core.info(`Attempting creation of pull request`) 77 | const {data: pull} = await this.octokit.rest.pulls.create({ 78 | ...this.parseRepository(baseRepository), 79 | title: inputs.title, 80 | head: headBranch, 81 | head_repo: headRepository, 82 | base: inputs.base, 83 | body: inputs.body, 84 | draft: inputs.draft.value, 85 | maintainer_can_modify: inputs.maintainerCanModify 86 | }) 87 | core.info( 88 | `Created pull request #${pull.number} (${headBranch} => ${inputs.base})` 89 | ) 90 | return { 91 | number: pull.number, 92 | html_url: pull.html_url, 93 | node_id: pull.node_id, 94 | draft: pull.draft, 95 | created: true 96 | } 97 | } catch (e) { 98 | const errorMessage = utils.getErrorMessage(e) 99 | if (errorMessage.includes(ERROR_PR_ALREADY_EXISTS)) { 100 | core.info(`A pull request already exists for ${headBranch}`) 101 | } else if (errorMessage.includes(ERROR_PR_FORK_COLLAB)) { 102 | core.warning( 103 | 'An attempt was made to create a pull request using a token that does not have write access to the head branch.' 104 | ) 105 | core.warning( 106 | `For this case, set input 'maintainer-can-modify' to 'false' to allow pull request creation.` 107 | ) 108 | throw e 109 | } else { 110 | throw e 111 | } 112 | } 113 | 114 | // Update the pull request that exists for this branch and base 115 | core.info(`Fetching existing pull request`) 116 | const {data: pulls} = await this.octokit.rest.pulls.list({ 117 | ...this.parseRepository(baseRepository), 118 | state: 'open', 119 | head: headBranch, 120 | base: inputs.base 121 | }) 122 | core.info(`Attempting update of pull request`) 123 | const {data: pull} = await this.octokit.rest.pulls.update({ 124 | ...this.parseRepository(baseRepository), 125 | pull_number: pulls[0].number, 126 | title: inputs.title, 127 | body: inputs.body 128 | }) 129 | core.info( 130 | `Updated pull request #${pull.number} (${headBranch} => ${inputs.base})` 131 | ) 132 | return { 133 | number: pull.number, 134 | html_url: pull.html_url, 135 | node_id: pull.node_id, 136 | draft: pull.draft, 137 | created: false 138 | } 139 | } 140 | 141 | async getRepositoryParent(headRepository: string): Promise { 142 | const {data: headRepo} = await this.octokit.rest.repos.get({ 143 | ...this.parseRepository(headRepository) 144 | }) 145 | if (!headRepo.parent) { 146 | return null 147 | } 148 | return headRepo.parent.full_name 149 | } 150 | 151 | async createOrUpdatePullRequest( 152 | inputs: Inputs, 153 | baseRepository: string, 154 | headRepository: string 155 | ): Promise { 156 | // Create or update the pull request 157 | const pull = await this.createOrUpdate( 158 | inputs, 159 | baseRepository, 160 | headRepository 161 | ) 162 | 163 | // Apply milestone 164 | if (inputs.milestone) { 165 | core.info(`Applying milestone '${inputs.milestone}'`) 166 | await this.octokit.rest.issues.update({ 167 | ...this.parseRepository(baseRepository), 168 | issue_number: pull.number, 169 | milestone: inputs.milestone 170 | }) 171 | } 172 | // Apply labels 173 | if (inputs.labels.length > 0) { 174 | core.info(`Applying labels '${inputs.labels}'`) 175 | await this.octokit.rest.issues.addLabels({ 176 | ...this.parseRepository(baseRepository), 177 | issue_number: pull.number, 178 | labels: inputs.labels 179 | }) 180 | } 181 | // Apply assignees 182 | if (inputs.assignees.length > 0) { 183 | core.info(`Applying assignees '${inputs.assignees}'`) 184 | await this.octokit.rest.issues.addAssignees({ 185 | ...this.parseRepository(baseRepository), 186 | issue_number: pull.number, 187 | assignees: inputs.assignees 188 | }) 189 | } 190 | 191 | // Request reviewers and team reviewers 192 | const requestReviewersParams = {} 193 | if (inputs.reviewers.length > 0) { 194 | requestReviewersParams['reviewers'] = inputs.reviewers 195 | core.info(`Requesting reviewers '${inputs.reviewers}'`) 196 | } 197 | if (inputs.teamReviewers.length > 0) { 198 | const teams = utils.stripOrgPrefixFromTeams(inputs.teamReviewers) 199 | requestReviewersParams['team_reviewers'] = teams 200 | core.info(`Requesting team reviewers '${teams}'`) 201 | } 202 | if (Object.keys(requestReviewersParams).length > 0) { 203 | try { 204 | await this.octokit.rest.pulls.requestReviewers({ 205 | ...this.parseRepository(baseRepository), 206 | pull_number: pull.number, 207 | ...requestReviewersParams 208 | }) 209 | } catch (e) { 210 | if (utils.getErrorMessage(e).includes(ERROR_PR_REVIEW_TOKEN_SCOPE)) { 211 | core.error( 212 | `Unable to request reviewers. If requesting team reviewers a 'repo' scoped PAT is required.` 213 | ) 214 | } 215 | throw e 216 | } 217 | } 218 | 219 | return pull 220 | } 221 | 222 | async pushSignedCommits( 223 | git: GitCommandManager, 224 | branchCommits: Commit[], 225 | baseCommit: Commit, 226 | repoPath: string, 227 | branchRepository: string, 228 | branch: string 229 | ): Promise { 230 | let headCommit: CommitResponse = { 231 | sha: baseCommit.sha, 232 | tree: baseCommit.tree, 233 | verified: false 234 | } 235 | for (const commit of branchCommits) { 236 | headCommit = await this.createCommit( 237 | git, 238 | commit, 239 | headCommit, 240 | repoPath, 241 | branchRepository 242 | ) 243 | } 244 | await this.createOrUpdateRef(branchRepository, branch, headCommit.sha) 245 | return headCommit 246 | } 247 | 248 | private async createCommit( 249 | git: GitCommandManager, 250 | commit: Commit, 251 | parentCommit: CommitResponse, 252 | repoPath: string, 253 | branchRepository: string 254 | ): Promise { 255 | const repository = this.parseRepository(branchRepository) 256 | // In the case of an empty commit, the tree references the parent's tree 257 | let treeSha = parentCommit.tree 258 | if (commit.changes.length > 0) { 259 | core.info(`Creating tree objects for local commit ${commit.sha}`) 260 | const treeObjects = await Promise.all( 261 | commit.changes.map(async ({path, mode, status, dstSha}) => { 262 | if (mode === '160000') { 263 | // submodule 264 | core.info(`Creating tree object for submodule commit at '${path}'`) 265 | return { 266 | path, 267 | mode, 268 | sha: dstSha, 269 | type: 'commit' 270 | } 271 | } else { 272 | let sha: string | null = null 273 | if (status === 'A' || status === 'M') { 274 | try { 275 | const {data: blob} = await blobCreationLimit(async () => 276 | this.octokit.rest.git.createBlob({ 277 | ...repository, 278 | content: await git.showFileAtRefBase64(commit.sha, path), 279 | encoding: 'base64' 280 | }) 281 | ) 282 | sha = blob.sha 283 | } catch (error) { 284 | core.error( 285 | `Error creating blob for file '${path}': ${utils.getErrorMessage(error)}` 286 | ) 287 | throw error 288 | } 289 | } 290 | core.info( 291 | `Creating tree object for blob at '${path}' with status '${status}'` 292 | ) 293 | return { 294 | path, 295 | mode, 296 | sha, 297 | type: 'blob' 298 | } 299 | } 300 | }) 301 | ) 302 | 303 | const chunkSize = 100 304 | const chunkedTreeObjects: TreeObject[][] = Array.from( 305 | {length: Math.ceil(treeObjects.length / chunkSize)}, 306 | (_, i) => treeObjects.slice(i * chunkSize, i * chunkSize + chunkSize) 307 | ) 308 | 309 | core.info(`Creating tree for local commit ${commit.sha}`) 310 | for (let i = 0; i < chunkedTreeObjects.length; i++) { 311 | const {data: tree} = await this.octokit.rest.git.createTree({ 312 | ...repository, 313 | base_tree: treeSha, 314 | tree: chunkedTreeObjects[i] 315 | }) 316 | treeSha = tree.sha 317 | if (chunkedTreeObjects.length > 1) { 318 | core.info( 319 | `Created tree ${treeSha} of multipart tree (${i + 1} of ${chunkedTreeObjects.length})` 320 | ) 321 | } 322 | } 323 | core.info(`Created tree ${treeSha} for local commit ${commit.sha}`) 324 | } 325 | 326 | const {data: remoteCommit} = await this.octokit.rest.git.createCommit({ 327 | ...repository, 328 | parents: [parentCommit.sha], 329 | tree: treeSha, 330 | message: `${commit.subject}\n\n${commit.body}` 331 | }) 332 | core.info( 333 | `Created commit ${remoteCommit.sha} for local commit ${commit.sha}` 334 | ) 335 | core.info( 336 | `Commit verified: ${remoteCommit.verification.verified}; reason: ${remoteCommit.verification.reason}` 337 | ) 338 | return { 339 | sha: remoteCommit.sha, 340 | tree: remoteCommit.tree.sha, 341 | verified: remoteCommit.verification.verified 342 | } 343 | } 344 | 345 | async getCommit( 346 | sha: string, 347 | branchRepository: string 348 | ): Promise { 349 | const repository = this.parseRepository(branchRepository) 350 | const {data: remoteCommit} = await this.octokit.rest.git.getCommit({ 351 | ...repository, 352 | commit_sha: sha 353 | }) 354 | return { 355 | sha: remoteCommit.sha, 356 | tree: remoteCommit.tree.sha, 357 | verified: remoteCommit.verification.verified 358 | } 359 | } 360 | 361 | private async createOrUpdateRef( 362 | branchRepository: string, 363 | branch: string, 364 | newHead: string 365 | ) { 366 | const repository = this.parseRepository(branchRepository) 367 | const branchExists = await this.octokit.rest.repos 368 | .getBranch({ 369 | ...repository, 370 | branch: branch 371 | }) 372 | .then( 373 | () => true, 374 | () => false 375 | ) 376 | 377 | if (branchExists) { 378 | core.info(`Branch ${branch} exists; Updating ref`) 379 | await this.octokit.rest.git.updateRef({ 380 | ...repository, 381 | sha: newHead, 382 | ref: `heads/${branch}`, 383 | force: true 384 | }) 385 | } else { 386 | core.info(`Branch ${branch} does not exist; Creating ref`) 387 | await this.octokit.rest.git.createRef({ 388 | ...repository, 389 | sha: newHead, 390 | ref: `refs/heads/${branch}` 391 | }) 392 | } 393 | } 394 | 395 | async convertToDraft(id: string): Promise { 396 | core.info(`Converting pull request to draft`) 397 | await this.octokit.graphql({ 398 | query: `mutation($pullRequestId: ID!) { 399 | convertPullRequestToDraft(input: {pullRequestId: $pullRequestId}) { 400 | pullRequest { 401 | isDraft 402 | } 403 | } 404 | }`, 405 | pullRequestId: id 406 | }) 407 | } 408 | } 409 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import {Inputs, createPullRequest} from './create-pull-request' 3 | import {inspect} from 'util' 4 | import * as utils from './utils' 5 | 6 | function getDraftInput(): {value: boolean; always: boolean} { 7 | if (core.getInput('draft') === 'always-true') { 8 | return {value: true, always: true} 9 | } else { 10 | return {value: core.getBooleanInput('draft'), always: false} 11 | } 12 | } 13 | 14 | async function run(): Promise { 15 | try { 16 | const inputs: Inputs = { 17 | token: core.getInput('token'), 18 | branchToken: core.getInput('branch-token'), 19 | path: core.getInput('path'), 20 | addPaths: utils.getInputAsArray('add-paths'), 21 | commitMessage: core.getInput('commit-message'), 22 | committer: core.getInput('committer'), 23 | author: core.getInput('author'), 24 | signoff: core.getBooleanInput('signoff'), 25 | branch: core.getInput('branch'), 26 | deleteBranch: core.getBooleanInput('delete-branch'), 27 | branchSuffix: core.getInput('branch-suffix'), 28 | base: core.getInput('base'), 29 | pushToFork: core.getInput('push-to-fork'), 30 | signCommits: core.getBooleanInput('sign-commits'), 31 | title: core.getInput('title'), 32 | body: core.getInput('body'), 33 | bodyPath: core.getInput('body-path'), 34 | labels: utils.getInputAsArray('labels'), 35 | assignees: utils.getInputAsArray('assignees'), 36 | reviewers: utils.getInputAsArray('reviewers'), 37 | teamReviewers: utils.getInputAsArray('team-reviewers'), 38 | milestone: Number(core.getInput('milestone')), 39 | draft: getDraftInput(), 40 | maintainerCanModify: core.getBooleanInput('maintainer-can-modify') 41 | } 42 | core.debug(`Inputs: ${inspect(inputs)}`) 43 | 44 | if (!inputs.token) { 45 | throw new Error(`Input 'token' not supplied. Unable to continue.`) 46 | } 47 | if (!inputs.branchToken) { 48 | inputs.branchToken = inputs.token 49 | } 50 | if (inputs.bodyPath) { 51 | if (!utils.fileExistsSync(inputs.bodyPath)) { 52 | throw new Error(`File '${inputs.bodyPath}' does not exist.`) 53 | } 54 | // Update the body input with the contents of the file 55 | inputs.body = utils.readFile(inputs.bodyPath) 56 | } 57 | // 65536 characters is the maximum allowed for the pull request body. 58 | if (inputs.body.length > 65536) { 59 | core.warning( 60 | `Pull request body is too long. Truncating to 65536 characters.` 61 | ) 62 | inputs.body = inputs.body.substring(0, 65536) 63 | } 64 | 65 | await createPullRequest(inputs) 66 | } catch (error) { 67 | core.setFailed(utils.getErrorMessage(error)) 68 | } 69 | } 70 | 71 | run() 72 | -------------------------------------------------------------------------------- /src/octokit-client.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import {Octokit as OctokitCore} from '@octokit/core' 3 | import {paginateRest} from '@octokit/plugin-paginate-rest' 4 | import {restEndpointMethods} from '@octokit/plugin-rest-endpoint-methods' 5 | import {throttling} from '@octokit/plugin-throttling' 6 | import {fetch} from 'node-fetch-native/proxy' 7 | export {RestEndpointMethodTypes} from '@octokit/plugin-rest-endpoint-methods' 8 | // eslint-disable-next-line import/no-unresolved 9 | export {OctokitOptions} from '@octokit/core/dist-types/types' 10 | 11 | export const Octokit = OctokitCore.plugin( 12 | paginateRest, 13 | restEndpointMethods, 14 | throttling, 15 | autoProxyAgent 16 | ) 17 | 18 | export const throttleOptions = { 19 | onRateLimit: (retryAfter, options, _, retryCount) => { 20 | core.debug(`Hit rate limit for request ${options.method} ${options.url}`) 21 | // Retries twice for a total of three attempts 22 | if (retryCount < 2) { 23 | core.debug(`Retrying after ${retryAfter} seconds!`) 24 | return true 25 | } 26 | }, 27 | onSecondaryRateLimit: (retryAfter, options) => { 28 | core.warning( 29 | `Hit secondary rate limit for request ${options.method} ${options.url}` 30 | ) 31 | core.warning(`Requests may be retried after ${retryAfter} seconds.`) 32 | } 33 | } 34 | 35 | // Octokit plugin to support the standard environment variables http_proxy, https_proxy and no_proxy 36 | function autoProxyAgent(octokit: OctokitCore) { 37 | octokit.hook.before('request', options => { 38 | options.request.fetch = fetch 39 | }) 40 | } 41 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import * as fs from 'fs' 3 | import * as path from 'path' 4 | 5 | export function getInputAsArray( 6 | name: string, 7 | options?: core.InputOptions 8 | ): string[] { 9 | return getStringAsArray(core.getInput(name, options)) 10 | } 11 | 12 | export function getStringAsArray(str: string): string[] { 13 | return str 14 | .split(/[\n,]+/) 15 | .map(s => s.trim()) 16 | .filter(x => x !== '') 17 | } 18 | 19 | export function stripOrgPrefixFromTeams(teams: string[]): string[] { 20 | return teams.map(team => { 21 | const slashIndex = team.lastIndexOf('/') 22 | if (slashIndex > 0) { 23 | return team.substring(slashIndex + 1) 24 | } 25 | return team 26 | }) 27 | } 28 | 29 | export function getRepoPath(relativePath?: string): string { 30 | let githubWorkspacePath = process.env['GITHUB_WORKSPACE'] 31 | if (!githubWorkspacePath) { 32 | throw new Error('GITHUB_WORKSPACE not defined') 33 | } 34 | githubWorkspacePath = path.resolve(githubWorkspacePath) 35 | core.debug(`githubWorkspacePath: ${githubWorkspacePath}`) 36 | 37 | let repoPath = githubWorkspacePath 38 | if (relativePath) repoPath = path.resolve(repoPath, relativePath) 39 | 40 | core.debug(`repoPath: ${repoPath}`) 41 | return repoPath 42 | } 43 | 44 | export function getRemoteUrl( 45 | protocol: string, 46 | hostname: string, 47 | repository: string 48 | ): string { 49 | return protocol == 'HTTPS' 50 | ? `https://${hostname}/${repository}` 51 | : `git@${hostname}:${repository}.git` 52 | } 53 | 54 | export function secondsSinceEpoch(): number { 55 | const now = new Date() 56 | return Math.round(now.getTime() / 1000) 57 | } 58 | 59 | export function randomString(): string { 60 | return Math.random().toString(36).substr(2, 7) 61 | } 62 | 63 | interface DisplayNameEmail { 64 | name: string 65 | email: string 66 | } 67 | 68 | export function parseDisplayNameEmail( 69 | displayNameEmail: string 70 | ): DisplayNameEmail { 71 | // Parse the name and email address from a string in the following format 72 | // Display Name 73 | const pattern = /^([^<]+)\s*<([^>]+)>$/i 74 | 75 | // Check we have a match 76 | const match = displayNameEmail.match(pattern) 77 | if (!match) { 78 | throw new Error( 79 | `The format of '${displayNameEmail}' is not a valid email address with display name` 80 | ) 81 | } 82 | 83 | // Check that name and email are not just whitespace 84 | const name = match[1].trim() 85 | const email = match[2].trim() 86 | if (!name || !email) { 87 | throw new Error( 88 | `The format of '${displayNameEmail}' is not a valid email address with display name` 89 | ) 90 | } 91 | 92 | return { 93 | name: name, 94 | email: email 95 | } 96 | } 97 | 98 | export function fileExistsSync(path: string): boolean { 99 | if (!path) { 100 | throw new Error("Arg 'path' must not be empty") 101 | } 102 | 103 | let stats: fs.Stats 104 | try { 105 | stats = fs.statSync(path) 106 | } catch (error) { 107 | if (hasErrorCode(error) && error.code === 'ENOENT') { 108 | return false 109 | } 110 | 111 | throw new Error( 112 | `Encountered an error when checking whether path '${path}' exists: ${getErrorMessage( 113 | error 114 | )}` 115 | ) 116 | } 117 | 118 | if (!stats.isDirectory()) { 119 | return true 120 | } 121 | 122 | return false 123 | } 124 | 125 | export function readFile(path: string): string { 126 | return fs.readFileSync(path, 'utf-8') 127 | } 128 | 129 | /* eslint-disable @typescript-eslint/no-explicit-any */ 130 | function hasErrorCode(error: any): error is {code: string} { 131 | return typeof (error && error.code) === 'string' 132 | } 133 | 134 | export function getErrorMessage(error: unknown) { 135 | if (error instanceof Error) return error.message 136 | return String(error) 137 | } 138 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "lib": [ 6 | "es6" 7 | ], 8 | "outDir": "./lib", 9 | "rootDir": "./src", 10 | "declaration": true, 11 | "strict": true, 12 | "noImplicitAny": false, 13 | "esModuleInterop": true 14 | }, 15 | "exclude": ["__test__", "lib", "node_modules"] 16 | } 17 | --------------------------------------------------------------------------------