checkout icon indicating copy to clipboard operation
checkout copied to clipboard

Any way to checkout PR from `issue_comment` event?

Open aaronsteers opened this issue 5 years ago • 30 comments

The example in the docs here assumes a pull request event, but it does not work when operating on Pull Request comments, since those come through the issue_comment event.

I've spent several hours on this now and I don't see any way to checkout the branch associated with the issue_event.

Complications:

  • The event is the comment and it links to an issue, which only indirectly seems to have data on the pull request url.
  • Checking out the associate sha doesn't give push ability, since the branch name itself is not discoverable (at least not as well as I can tell).
  • Since issue_comment events have to be triggered by the workflow file on the default branch, it seems that is always the branch name provided. I haven't yet found any way to get the actual PR branch, although it seems this should be a straightforward and frequent use case for operating on PR comments.

aaronsteers avatar Aug 16 '20 00:08 aaronsteers

The only solution I found was to first use the checkout event and then separately use hub CLI, which is apparently installed by default and which can run hub pr checkout ${pr_num} in order to checkout whatever branch is associated with the PR (after parsing the PR num from the URL).

name: Slash Command CI

on: issue_comment

jobs:
  check_comments:
    runs-on: ubuntu-latest
    name: Check comments for /format
    steps:
      - name: Clone git repo
        uses: actions/checkout@v2
      - name: Checkout Pull Request
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          PR_URL="${{ github.event.issue.pull_request.url }}"
          PR_NUM=${PR_URL##*/}
          echo "Checking out from PR #$PR_NUM based on URL: $PR_URL"
          hub pr checkout $PR_NUM
      - name: Configure Git Agent
        run: |
          git config --global user.email "[email protected]"
          git config --global user.name "Me, Not Really (CI bot)"
      - uses: hashicorp/setup-terraform@v1
        with:
          terraform_version: 0.13.0
      - run: terraform fmt -recursive
      - run: git commit -a -m "GitOps Bot (Autoformat)"
      - run: git push

Is there a better way?

aaronsteers avatar Aug 16 '20 01:08 aaronsteers

I faced the same problem with one more restriction that github account was not owned by us, I don't know the context that other users will face but in my case I can just send in the branch name through the comment. so, here is what I did:

Basically pull out branch name from comment where branch name is enclosed in [], i.e [branch_name] then extract out the name to pass it to the checkout action. I would love to find better way than this but for now it works ok.

steps:
    - name: Get Branch name
      id: branchName
      run: |
        echo ::set-output name=branch::$(echo $PR_COMMENT | cut -d "[" -f2 | cut -d "]" -f1)
      env:
        PR_COMMENT: ${{ github.event.comment.body }}
    - name: Checkout code
      uses: actions/checkout@v2
      with: 
        ref: ${{ steps.branchName.outputs.branch }}

NutanNiraula avatar Oct 08 '20 05:10 NutanNiraula

As the required information isn't present in the event payload, you could use the GitHub API to fetch it. The github-script action allows you to write actions in your workflow file, which is pretty convenient:

name: Checkout PR on comment

on:
  issue_comment:
    # triggers on created, edited and deleted by default, you may wanna restrict it, e.g.:
    #types: [created]
jobs:
  pr-commented:
    name: PR commented
    if: github.event.issue.pull_request
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v3
        id: get-pr
        with:
          script: |
            const request = {
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number
            }
            core.info(`Getting PR #${request.pull_number} from ${request.owner}/${request.repo}`)
            try {
              const result = await github.pulls.get(request)
              return result.data
            } catch (err) {
              core.setFailed(`Request failed with error ${err}`)
            }
      - uses: actions/checkout@v2
        with:
          repository: ${{ fromJSON(steps.get-pr.outputs.result).head.repo.full_name }}
          ref: ${{ fromJSON(steps.get-pr.outputs.result).head.sha }} # or .head.ref for branch name

Simran-B avatar Oct 12 '20 12:10 Simran-B

The only solution I found was to first use the checkout event and then separately use hub CLI, which is apparently installed by default and which can run hub pr checkout ${pr_num} in order to checkout whatever branch is associated with the PR (after parsing the PR num from the URL).

Is there a better way?

@aaronsteers do you even need to parse it? I though the following should do:

hub pr checkout ${{ github.event.issue.number }}

zyv avatar Jun 18 '21 15:06 zyv

The only solution I found was to first use the checkout event and then separately use hub CLI, which is apparently installed by default and which can run hub pr checkout ${pr_num} in order to checkout whatever branch is associated with the PR (after parsing the PR num from the URL).

Is there a better way?

@aaronsteers do you even need to parse it? I though the following should do:

hub pr checkout ${{ github.event.issue.number }}

@zyv , yes, I think it would! The 10-months-ago-me perhaps didn't know or realize yet that a PR is an issue and the issue number is therefore the same as the PR number. 🙌

aaronsteers avatar Jun 18 '21 19:06 aaronsteers

Can we add PR information like target branch or source branch in issue_comment webhook payload? These should be very commonly used.

rongquantoh-intel avatar Aug 12 '21 08:08 rongquantoh-intel

The only solution I found was to first use the checkout event and then separately use hub CLI, which is apparently installed by default and which can run hub pr checkout ${pr_num} in order to checkout whatever branch is associated with the PR (after parsing the PR num from the URL). Is there a better way?

@aaronsteers do you even need to parse it? I though the following should do:

hub pr checkout ${{ github.event.issue.number }}

This has worked for us!

deploy:
  runs-on: ubuntu-latest
  steps:
    # Checkout source code
    - name: Checkout
      uses: actions/checkout@v2
    - name: Checkout Pull Request
      run: hub pr checkout ${{ github.event.issue.number }}
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

mareksuscak avatar Sep 22 '21 23:09 mareksuscak

Edit: The below information is not correct as pointed out by @zyv below

- uses: actions/checkout@v2
  with:
    ref: ${{ github.event.pull_request.head.sha }}
  • https://frontside.com/blog/2020-05-26-github-actions-pull_request/

tomdottom avatar Oct 07 '21 19:10 tomdottom

@tomdottom this information is not available in issue_comment event.

zyv avatar Oct 08 '21 07:10 zyv

@tomdottom this information is not available in issue_comment event.

@zyv thanks for pointing this out

tomdottom avatar Oct 12 '21 13:10 tomdottom

I just created a tiny js action that will output base_ref and head_ref: https://github.com/eficode/resolve-pr-refs

It's really simple to use:

- name: resolve pr refs
  id: refs
  uses: eficode/resolve-pr-refs@main
  with:
    token: ${{ secrets.GITHUB_TOKEN }}

In the following steps you can reference ${{ steps.refs.outputs.head_ref }} and ${{ steps.refs.outputs.base_ref }}

I hope you like it 🙂

suonto avatar Nov 05 '21 13:11 suonto

In case anyone else comes looking, you can use the gh cli to only get the branch name if you still want to use the actions/checkout action

    steps:
      - id: 'get-branch'
        run: echo ::set-output name=branch::$(gh pr view $PR_NO --repo $REPO --json headRefName --jq '.headRefName')
        env:
          REPO: ${{ github.repository }}
          PR_NO: ${{ github.event.issue.number }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Checkout
        uses: actions/checkout@v2
        with:
          ref: ${{ steps.get-branch.outputs.branch }}

jacobrask avatar Feb 10 '22 21:02 jacobrask

@jacobrask I tried your solution and I received the following output:

GraphQL: Resource not accessible by integration (repository.pullRequest)

What else did you do?

AllanOricil avatar Apr 19 '22 16:04 AllanOricil

@mareksuscak's method worked great for my on: issue_comment triggered workflow. Pretty sure you can't get much shorter or faster than this!

deploy:
  runs-on: ubuntu-latest
  steps:
    # need this first step to init the git repo
    - name: Checkout
      uses: actions/checkout@v2
    - name: Checkout Pull Request
      run: hub pr checkout ${{ github.event.issue.number }}
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

NickCrews avatar May 07 '22 02:05 NickCrews

Github Action Workflow: Screenshot 2022-05-19 at 23 10 11

Github Action Result: Screenshot 2022-05-19 at 23 04 01 (1)

Having an issue connecting a Github Action workflow triggered on issue_comment always triggering CircleCI from the branch master.

I would ideally like to be able to type /test on any PR to trigger a test job on CircleCI to run all of our E2E tests for that particular branch.

I have tried multiple solutions above and all work great for checking out the branch and it correcting the ref but somewhere along the line CircleCI is still picking this up as being triggered from the branch master.

Could anyone shed some light on this and some possible solutions?

joshS28 avatar May 19 '22 22:05 joshS28

@joshS28 you have 2 options:

Option 1, use an action to resolve refs: Please find an example here: https://github.com/eficode/resolve-pr-refs#example-usecase

Option 2, use script-action like @Simran-B suggested here: https://github.com/actions/checkout/issues/331#issuecomment-707103442

The option 1 is like a packaged version of option 2. They both work.

suonto avatar May 20 '22 07:05 suonto

@joshS28 I have to apologise for my previous comment. It was useless and I wasn't paying attention to your actual issue. The actual issue is that even though you're resolving branches, you're not passing them to the trigger action as parameters. It's determining the refs automatically and facing this same issue no doubt.

Furthermore I saw your comment in https://github.com/CircleCI-Public/trigger-circleci-pipeline-action/pull/11 and can see that you've found the best possible place to ask this question.

Hope it gets resolved there.

suonto avatar May 23 '22 09:05 suonto

This helped me https://github.com/marketplace/actions/pull-request-comment-branch

leiarenee avatar Sep 10 '22 11:09 leiarenee

I want to thank all of you for the previous contributions, but I'm trying to re-run the main workflow (which is a reusable workflow) from a callee workflow like so:

name: Re-Run Tests on PR Comment Workflow
on:
  issue_comment:
    types: [created]
  
jobs:
  rerun-tests-job:
    if: github.event.issue.pull_request && contains(github.event.comment.body, 'run tests')
    uses: ./.github/workflows/main.yml

Unfortunately, I don't think I can easily or gracefully change the action/checkout -> ref: of the previous workflow that I am re-using.

This seems like such a common use-case though, I'm surprised it isn't supported.

I can solve this by ditching the "reusable workflow" and copy/pasting the reusable workflow into the new workflow, but I don't want to have to maintain both pipelines -- I would much rather reuse the first and call it from the second.

mrk-han avatar Oct 26 '22 03:10 mrk-han

hi @mrk-han you could give it a try this to achieve what you are looking for.

name: Re-Run Tests on PR Comment Workflow
on:
  issue_comment:
    types: [created]
  
jobs:
  rerun-tests-job:
  if: github.event_name == 'pull_request' || github.event.issue.pull_request && contains(github.event.comment.body, 'run tests')
    uses: ./.github/workflows/main.yml

In main workflow step

you could add example:

      - uses: actions/github-script@v6
        if: github.event_name == 'pull_request' || github.event.issue.pull_request

jtoscript avatar Feb 06 '23 17:02 jtoscript

Hey everybody, I noticed that GitHub creates refs for pull request commits: https://www.jvt.me/posts/2019/01/19/git-ref-github-pull-requests/ This allows to checkout the branch of the pull request directly in the actions/checkout@v3 action:

      - name: Checkout pull request 🏁
        uses: actions/checkout@v3
        with:
          ref: refs/pull/${{ github.event.issue.number }}/head

niklasnatter avatar Feb 21 '23 10:02 niklasnatter

@niklasnatter you have THE PERFECT SOLUTION! Thank you.

      - name: Checkout pull request 🏁
        uses: actions/checkout@v3
        with:
          ref: refs/pull/${{ github.event.issue.number }}/head

ADTC avatar Mar 26 '23 17:03 ADTC

Did some testing and realised there's some slight differences between some of the answers above. This answer actually checks out the PR branch

steps:
  - id: 'get-branch'
    run: echo ::set-output name=branch::$(gh pr view $PR_NO --repo $REPO --json headRefName --jq '.headRefName')
    env:
      REPO: ${{ github.repository }}
      PR_NO: ${{ github.event.issue.number }}
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  - name: Checkout
    uses: actions/checkout@v2
    with:
      ref: ${{ steps.get-branch.outputs.branch }}

While this answer checks out the latest commit of the PR branch

  - name: Checkout pull request 🏁
    uses: actions/checkout@v3
    with:
      ref: refs/pull/${{ github.event.issue.number }}/head

My use case involves linting code (triggered by slash command /lint) and committing the changes. The 2nd answer doesn't work for me as the git push command errors out with fatal: You are not currently on a branch.

Zhiyuan-Amos avatar May 30 '23 02:05 Zhiyuan-Amos

Great discovery @Zhiyuan-Amos I will add your comment in my PR if that's okay with you.

ADTC avatar May 30 '23 02:05 ADTC

has anyone found a way to find the ref of the pr with this issue_comment trigger event ?

as far as I know github.event.issue.pull_request.ref doesnt work :/ i'd like a solution that avoids using octokit

dcantu96 avatar Nov 22 '23 15:11 dcantu96

Hey everybody, I noticed that GitHub creates refs for pull request commits: https://www.jvt.me/posts/2019/01/19/git-ref-github-pull-requests/ This allows to checkout the branch of the pull request directly in the actions/checkout@v3 action:

      - name: Checkout pull request 🏁
        uses: actions/checkout@v3
        with:
          ref: refs/pull/${{ github.event.issue.number }}/head

I changed that for me to support both triggers (issue_comment or any other like workflow_dispatch):

- uses: actions/checkout@v4
  with:
    ref: ${{ github.event_name == 'issue_comment' && format('refs/pull/{0}/head', github.event.issue.number) || '' }}

hakuno avatar Feb 28 '24 19:02 hakuno