name: clang-format

on: [push, pull_request]

jobs:
  check:
    runs-on: ubuntu-20.04
    env:
      CLANG_VERSION: 10
    steps:
    - uses: actions/checkout@v4
    - name: Install clang-format
      run: |
        codename=$( lsb_release --codename --short )
        sudo tee /etc/apt/sources.list.d/llvm.list >/dev/null <<EOF
        deb http://apt.llvm.org/${codename}/ llvm-toolchain-${codename}-${CLANG_VERSION} main
        deb-src http://apt.llvm.org/${codename}/ llvm-toolchain-${codename}-${CLANG_VERSION} main
        EOF
        wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add
        sudo apt-get update
        sudo apt-get install clang-format-${CLANG_VERSION}
    - name: Format src/ripple
      run: find src/ripple -type f \( -name '*.cpp' -o -name '*.h' -o -name '*.ipp' \) -print0 | xargs -0 clang-format-${CLANG_VERSION} -i
    - name: Format src/test
      run: find src/test -type f \( -name '*.cpp' -o -name '*.h' -o -name '*.ipp' \) -print0 | xargs -0 clang-format-${CLANG_VERSION} -i
    - name: Check for differences
      id: assert
      run: |
        set -o pipefail
        git diff --exit-code | tee "clang-format.patch"
    - name: Upload patch
      if: failure() && steps.assert.outcome == 'failure'
      uses: actions/upload-artifact@v3
      continue-on-error: true
      with:
        name: clang-format.patch
        if-no-files-found: ignore
        path: clang-format.patch
    - name: What happened?
      if: failure() && steps.assert.outcome == 'failure'
      env:
        PREAMBLE: |
          If you are reading this, you are looking at a failed Github Actions
          job.  That means you pushed one or more files that did not conform
          to the formatting specified in .clang-format. That may be because
          you neglected to run 'git clang-format' or 'clang-format' before
          committing, or that your version of clang-format has an
          incompatibility with the one on this
          machine, which is:
        SUGGESTION: |

          To fix it, you can do one of two things:
          1. Download and apply the patch generated as an artifact of this
             job to your repo, commit, and push.
          2. Run 'git-clang-format --extensions c,cpp,h,cxx,ipp develop'
             in your repo, commit, and push.
      run: |
        echo "${PREAMBLE}"
        clang-format-${CLANG_VERSION} --version
        echo "${SUGGESTION}"
        exit 1
