在 GitHub 操作中评论拉取请求

jjm*_*elo 8 github github-api

我正在尝试从 GitHub 操作的拉取请求中插入常规评论。我似乎无法正确理解。Octokit 是底层库,允许您为PR创建reviewComments,但那些指的是提交,这不是我想要的,我想要一个简单的评论。我想我可以只使用octokit.issues.createComment. 但是,这似乎不起作用。这是代码

import * as core from '@actions/core';
const {GitHub, context} = require('@actions/github')
const parse = require('parse-diff')

async function run() {
    try {
        // get information on everything
        const token = core.getInput('github-token', {required: true})
        const github = new GitHub(token, {} )
        console.log( context )
        const PR_number = context.payload.pull_request.number

        // Check if the body contains required string
        const bodyContains = core.getInput('bodyContains')

        if ( context.payload.pull_request.body.indexOf( bodyContains) < 0  ) {
            core.setFailed("The body of the PR does not contain " + bodyContains);
            console.log( "Actor " + context.actor + " pr number " PR_number)
            const result = await github.issues.createComment({
                owner: context.actor,
                repo: context.payload.repository.full_name,
                issue_number: PR_number,
                body: "We need to have the word " + bodyContains + " in the body of the pull request"
            });
            console.log(result)
       } // more irrelevant stuff below
}}
Run Code Online (Sandbox Code Playgroud)

这似乎只是返回“未找到”。我似乎无法确定这是类型问题还是其他问题。理论上,owner、repo、issue number 和 body 应该是正确的,并且打印正确。任何帮助将不胜感激。这可能是 GitHub API 领域中一个更普遍的问题,GitHub 操作只是上下文,所以我可能错了。

Kev*_*cke 17

2020 年的方法是使用官方Github 脚本操作。不要混淆,GitHub API 的问题和 PR 是相同的。

on:
  # Trigger the workflow on push or pull request
  pull_request:
    branches:
      - master
      - develop

jobs:
  comment:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/github-script@v3
        with:
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            github.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: ' Thanks for reporting!'
            })
Run Code Online (Sandbox Code Playgroud)

见:https : //github.com/actions/github-script#comment-on-an-issue

  • @SevastyanSavanyuk OP 的措辞可能不那么固执己见,但一旦你进入 GH 生态系统,我认为想要减少对它的依赖是没有必要的。在行动方面做了很多工作,在我看来这是最好的方法 (8认同)
  • 这不应该由“pull_request_target”而不是“pull_request”触发吗?在“pull_request”触发的运行中,“GITHUB_TOKEN”没有对存储库的写访问权限,并导致错误“资源无法通过集成访问”。 (4认同)
  • 我不喜欢这种 2020 年的做法。使用“curl”接触真实的 API 端点应该是实现这一点的方法。否则,所有 github actions 的东西作为脚本是没有用的,因为它使用另一个“脚本”,从而模糊了意图并危及自身。结果,让你变得愚蠢,因为你不知道(或者更确切地说,无法控制)发生了什么。 (3认同)
  • 至于“不要混淆,GitHub API 的问题和 PR 是相同的。”,请查看 https://github.com/actions/toolkit/blob/main/packages/github/src/context.ts#L55 -L62 (2认同)
  • @wjkw1:这似乎是带有连字符的“pull-requests:write”,而不是下划线? (2认同)

slo*_*low 14

我最初尝试使用Respost,但它不允许设置原始body字符串。

所以这里有一种方法可以使用curl.

在一个.github/workflows/whatever.yml

name: Some workflow

on:
  issue_comment:
    types: [created]

jobs:
  comment:
    runs-on: ubuntu-latest

    steps:
      - name: Add comment to PR
        if: contains(github.event.comment.body, 'special string')
        env:
          URL: ${{ github.event.issue.comments_url }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          curl \
            -X POST \
            $URL \
            -H "Content-Type: application/json" \
            -H "Authorization: token $GITHUB_TOKEN" \
            --data '{ "body": "blah blah" }'
Run Code Online (Sandbox Code Playgroud)

  • 对于事件 `pull_request` 我必须使用 `${{ github.event.pull_request.comments_url }}` 作为 URL (13认同)

Dav*_*ner 8

其他答案没有提到的是从触发事件的分叉运行的 GitHub 操作的安全限制pull_request。这些操作中的GITHUB_TOKEN没有对存储库的写入权限,因此无法创建评论。请参阅GITHUB_TOKEN 的权限

workflow_run 事件的 GitHub 文档提供了一个很好的示例,说明如何解决此问题。基本思想是让事件触发的工作流程使用actions/upload-artifactpull_request上传评论中所需的任何信息作为构建工件。然后,由事件触发的单独工作流程使用actions/download-artifact下载信息。workflow_run

注意:出于安全考虑,由于 触发的工作流workflow_run具有写入权限,因此必须先将其提交到默认分支才能使用。(另请记住,构建工件可能包含来自恶意拉取请求的恶意数据)。

以下是链接文档中的示例工作流程的副本(以防链接中断或文档发生更改):

name: Upload data

on:
  pull_request:

jobs:
  upload:
    runs-on: ubuntu-latest

    steps:        
      - name: Save PR number
        env:
          PR_NUMBER: ${{ github.event.number }}
        run: |
          mkdir -p ./pr
          echo $PR_NUMBER > ./pr/pr_number
      - uses: actions/upload-artifact@v3
        with:
          name: pr_number
          path: pr/
Run Code Online (Sandbox Code Playgroud)
name: Use the data

on:
  workflow_run:
    workflows: [Upload data]
    types:
      - completed

jobs:
  download:
    runs-on: ubuntu-latest
    steps:
      - name: 'Download artifact'
        uses: actions/github-script@v5
        with:
          script: |
            let allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({
               owner: context.repo.owner,
               repo: context.repo.repo,
               run_id: context.payload.workflow_run.id,
            });
            let matchArtifact = allArtifacts.data.artifacts.filter((artifact) => {
              return artifact.name == "pr_number"
            })[0];
            let download = await github.rest.actions.downloadArtifact({
               owner: context.repo.owner,
               repo: context.repo.repo,
               artifact_id: matchArtifact.id,
               archive_format: 'zip',
            });
            let fs = require('fs');
            fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/pr_number.zip`, Buffer.from(download.data));

      - name: 'Unzip artifact'
        run: unzip pr_number.zip

      - name: 'Comment on PR'
        uses: actions/github-script@v5
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            let fs = require('fs');
            let issue_number = Number(fs.readFileSync('./pr_number'));
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: issue_number,
              body: 'Thank you for the PR!'
            });
Run Code Online (Sandbox Code Playgroud)


小智 7

您还可以使用@actions/github允许您使用octokit 客户端来简化操作:

const core = require('@actions/core');
const github = require('@actions/github');

async function run() {
  try {
    const message = core.getInput('message');
    const github_token = core.getInput('GITHUB_TOKEN');

    const context = github.context;
    if (context.payload.pull_request == null) {
        core.setFailed('No pull request found.');
        return;
    }
    const pull_request_number = context.payload.pull_request.number;

    const octokit = new github.GitHub(github_token);
    const new_comment = octokit.issues.createComment({
        ...context.repo,
        issue_number: pull_request_number,
        body: message
      });

  } catch (error) {
    core.setFailed(error.message);
  }
}

run();
Run Code Online (Sandbox Code Playgroud)

取自这个repo