从一个bash脚本中获取GitHub拉取请求中所有新创建/编辑的文件的列表。

huangapple go评论55阅读模式
英文:

get a list of all newly created/edited files in a github pull request from a bash script

问题

for filepath in $(git diff-tree --no-commit-id --name-only -r HEAD^ HEAD | grep '\.json$'); do
  # do something with the filepaths
done
英文:

I have a github actions set up to run on the creation/synchronization of pull requests. I want to be able to get a list of all the JSON filepaths that were either created, or edited in the pull request, and do something with this list of filepaths.

Github Workflow

name: PR
on:
  pull_request

jobs:
  run-script:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      - name: run the script
        run:./.github/scripts/script.sh
        shell: bash

script.sh

for filepath in $(...); do # get the list of filepaths that were created or edited in the PR
  # do something with the filepaths
done

My attempt

for file in $(git diff-tree --no-commit-id --name-only -r HEAD~1 HEAD | grep '\.json$'); do
done

but this gave me an error

fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

答案1

得分: 1

获取脚本的方法是,你可以这样获取json文件的差异:

mergeBranch='main' # 如果PR合并到不同的分支,请更改
oldCommit=$(git log $mergeBranch | head -n 1 | awk -F ' ' '{print $2}')
latestCommit=$(git log | head -n 1 | awk -F ' ' '{print $2}')
git diff --merge-base $oldCommit $latestCommit -- '*.json'

此外,这不是必须的,只是一个建议,可以编辑更少的文件。你可以将脚本的内容放在GitHub操作步骤内部,如下所示:
  • name: Check Diff
    run: |
    # 下面是脚本内容
英文:

For the script, you can get the diff of json files like so:

mergeBranch='main' # Change if PR merges into a different branch
oldCommit=$(git log $mergeBranch | head -n 1 | awk -F ' ' '{print $2}')
latestCommit=$(git log | head -n 1 | awk -F ' ' '{print $2}')
git diff --merge-base $oldCommit $latestCommit -- '*.json'

Also, this is not a requirement, but a suggestion to edit less files. You can have the contents of the script inside of the GitHub Action step itself as so:

  - name: Check Diff
        run: |
           # Script Contents Below

huangapple
  • 本文由 发表于 2023年3月31日 02:31:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定