Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Any way to checkout PR from issue_comment event? #331

Open
aaronsteers opened this issue Aug 16, 2020 · 26 comments · May be fixed by #1248
Open

Any way to checkout PR from issue_comment event? #331

aaronsteers opened this issue Aug 16, 2020 · 26 comments · May be fixed by #1248

Comments

@aaronsteers
Copy link

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
Copy link
Author

aaronsteers commented Aug 16, 2020

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 "my.email@sample.com"
          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?

@NutanNiraula
Copy link

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 }}

@Simran-B
Copy link

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

@zyv
Copy link

zyv commented Jun 18, 2021

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 }}

@aaronsteers
Copy link
Author

aaronsteers commented Jun 18, 2021

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. 🙌

@rongquantoh-intel
Copy link

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

@mareksuscak
Copy link

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 }}

@tomdottom
Copy link

tomdottom commented Oct 7, 2021

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 }}

@zyv
Copy link

zyv commented Oct 8, 2021

@tomdottom this information is not available in issue_comment event.

@tomdottom
Copy link

@tomdottom this information is not available in issue_comment event.

@zyv thanks for pointing this out

@suonto
Copy link

suonto commented Nov 5, 2021

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 🙂

fidencio added a commit to fidencio/kata-containers that referenced this issue Jan 17, 2022
The action used for testing kata-deploy is entirely based on the action
used to build the kata-deploy tarball, but while the latter is able to
use the correct branch, the former always uses `main`.

This happens as the `issue_comment`, from GitHub actions, passed the
"default branch" as the GITHUB_REF.

As we're not the first ones to face such a issue, I've decided to take
one of the approaches suggested at one of the checkout's issues,
actions/checkout#331, and take advantage of a
new action provided by the community, which will get the PR where the
comment was made, give us that ref, and that then can be used with the
checkout action, resulting on what we originally wanted.

Fixes: kata-containers#3443

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
fidencio added a commit to fidencio/kata-containers that referenced this issue Jan 17, 2022
The action used for testing kata-deploy is entirely based on the action
used to build the kata-deploy tarball, but while the latter is able to
use the correct branch, the former always uses `main`.

This happens as the `issue_comment`, from GitHub actions, passed the
"default branch" as the GITHUB_REF.

As we're not the first ones to face such a issue, I've decided to take
one of the approaches suggested at one of the checkout's issues,
actions/checkout#331, and take advantage of a
new action provided by the community, which will get the PR where the
comment was made, give us that ref, and that then can be used with the
checkout action, resulting on what we originally wanted.

Fixes: kata-containers#3443

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
fidencio added a commit to fidencio/kata-containers that referenced this issue Jan 17, 2022
The action used for testing kata-deploy is entirely based on the action
used to build the kata-deploy tarball, but while the latter is able to
use the correct branch, the former always uses `main`.

This happens as the `issue_comment`, from GitHub actions, passed the
"default branch" as the GITHUB_REF.

As we're not the first ones to face such a issue, I've decided to take
one of the approaches suggested at one of the checkout's issues,
actions/checkout#331, and take advantage of a
new action provided by the community, which will get the PR where the
comment was made, give us that ref, and that then can be used with the
checkout action, resulting on what we originally wanted.

Fixes: kata-containers#3443

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
snir911 pushed a commit to snir911/kata-containers that referenced this issue Jan 31, 2022
The action used for testing kata-deploy is entirely based on the action
used to build the kata-deploy tarball, but while the latter is able to
use the correct branch, the former always uses `main`.

This happens as the `issue_comment`, from GitHub actions, passed the
"default branch" as the GITHUB_REF.

As we're not the first ones to face such a issue, I've decided to take
one of the approaches suggested at one of the checkout's issues,
actions/checkout#331, and take advantage of a
new action provided by the community, which will get the PR where the
comment was made, give us that ref, and that then can be used with the
checkout action, resulting on what we originally wanted.

Fixes: kata-containers#3443

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
@jacobrask
Copy link

jacobrask commented Feb 10, 2022

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 }}

@AllanOricil
Copy link

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

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

What else did you do?

@NickCrews
Copy link

@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 }}

@ADTC
Copy link

ADTC commented Mar 26, 2023

@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

@Zhiyuan-Amos
Copy link

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.

@ADTC
Copy link

ADTC commented May 30, 2023

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

weiji14 added a commit to weiji14/conda-lock-refresh-demo that referenced this issue Aug 24, 2023
weiji14 added a commit to weiji14/conda-lock-refresh-demo that referenced this issue Aug 24, 2023
Patch at 1631a18 doesn't actually work. Need to checkout the Pull Request branch instead of the HEAD ref. Fixes error like `fatal: You are not currently on a branch. To push the history leading to the current (detached HEAD)
state now, use ...`. Xref actions/checkout#331 (comment)
python3kgae added a commit to python3kgae/apply_diff that referenced this issue Nov 6, 2023
@dcantu96
Copy link

dcantu96 commented Nov 22, 2023

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

@hakuno
Copy link

hakuno commented Feb 28, 2024

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) || '' }}

tnyo43 added a commit to tnyo43/recommend-mobpro-action that referenced this issue Mar 2, 2024
tnyo43 added a commit to tnyo43/recommend-mobpro-action that referenced this issue Mar 2, 2024
tnyo43 added a commit to tnyo43/recommend-mobpro-action that referenced this issue Mar 2, 2024
* set `Checkout Pull Request step`

ref: actions/checkout#331 (comment)

* fix condition

* fix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.