Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Github action check if a file already exists

I have the following git action which allows me to download an image.

I have to make sure if the file already exists to skip the "Commit file" and the "Push changes"

How can I check if the file already exists if it already exists nothing is done.

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 }}
like image 429
Paul Avatar asked Sep 13 '25 05:09

Paul


1 Answers

You can use Github Actions built-in hashFiles function for this. From the docs:

Returns a single hash for the set of files that matches the path pattern. You can provide a single path pattern or multiple path patterns separated by commas. (...) If the path pattern does not match any files, this returns an empty string.

See docs for details: docs.github.com

So you can do like this:

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

This won't work for checking directories though, as hashFiles will return empty string for empty directories.

Credits for the solution goes to Peter Bengtsson's blog: peterbe.com/plog

like image 139
spinpwr Avatar answered Sep 14 '25 19:09

spinpwr