Github 操作检查文件是否已存在

Pau*_*aul 12 yaml action file github github-actions

我有以下 git 操作,它允许我下载图像。

我必须确保文件是否已存在才能跳过“提交文件”和“推送更改”

如何检查文件是否已经存在,如果它已经存在则不执行任何操作。

on: 
  workflow_dispatch:
  
name: Scrape File
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        name: Check out current commit
     
      - name: Url
        run: |
         URL=$(node ./action.js)
         echo $URL
         echo "URL=$URL" >> $GITHUB_ENV
      
      - uses: suisei-cn/actions-download-file@v1
        id: downloadfile
        name: Download the file
        with:
          url: ${{ env.URL }}
          target: assets/
      - run: ls -l 'assets/'
          
      - name: Commit files
        run: |
         git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
         git config --local user.name "github-actions[bot]"
         git add .
         git commit -m "Add changes" -a
         
      - name: Push changes
        uses: ad-m/github-push-action@master
        with:
         github_token: ${{ secrets.GITHUB_TOKEN }}
         branch: ${{ github.ref }}
Run Code Online (Sandbox Code Playgroud)

Grz*_*ski 11

这里有几个选项 - 你可以直接使用 bash 并执行如下操作:

if test -f "$FILE"; then
    #file exists
fi
Run Code Online (Sandbox Code Playgroud)

或使用现有操作之一,如下所示:

- name: Check file existence
  id: check_files
  uses: andstor/file-existence-action@v1
  with:
    files: "assets/${{ env.URL }}"

- name: File exists
  if: steps.check_files.outputs.files_exists == 'true'
  run: echo "It exists !"
Run Code Online (Sandbox Code Playgroud)


小智 9

您可以使用 Github Actions 内置hashFiles功能来实现此目的。来自文档:

返回与路径模式匹配的文件集的单个哈希值。您可以提供单个路径模式或多个以逗号分隔的路径模式。(...) 如果路径模式与任何文件都不匹配,则返回空字符串。

有关详细信息,请参阅文档:docs.github.com

所以你可以这样做:

  - name: Commit files
    if: ${{ hashFiles('assets/') != '' }}
    run: |
     git config ...
Run Code Online (Sandbox Code Playgroud)

但这不适用于检查目录,因为hashFiles空目录将返回空字符串。

该解决方案归功于 Peter Bengtsson 的博客:peterbe.com/plog