gitgithub-actionspre-commitpre-commit.com

GitHub Actions PreCommit FatalError: git failed


I have a task to move CI/CD from Gitlab to GitHub Actions and there is one last obstacle I encounter.
PreCommit library is not working. Everything worked fine in gitlab and that is why I have no idea what could I change

My Code

name: CI Workflow

on:
  push:
    branches:
      - main

jobs:
  pre-commit-test:
    runs-on: ubuntu-latest
    container:
      image: python:3.11
    
    steps:
    - name: Checkout repository
      uses: actions/checkout@v2

    - name: Print current directory
      run: pwd

    - name: Set up Python 3.11
      uses: actions/setup-python@v2
      with:
        python-version: 3.11
          
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt

    - name: Check Git version
      run: git --version
      
    - name: Initialize Git
      run: git init  # Optional step if needed

    - name: Cache pre-commit hooks
      uses: actions/cache@v2
      with:
        path: ~/.cache/pre-commit
        key: ${{ runner.os }}-precommit-${{ hashFiles('.pre-commit-config.yaml') }}

    - name: Install pre-commit
      run: pip install pre-commit

    - name: Run pre-commit with debug
      run: pre-commit run --all-files

Error

Run pre-commit run --all-files
  pre-commit run --all-files
  shell: sh -e {0}
  env:
    pythonLocation: /__t/Python/3.11.9/x64
    LD_LIBRARY_PATH: /__t/Python/3.11.9/x64/lib
An error has occurred: FatalError: git failed. Is it installed, and are you in a Git repository directory?
Check the log at /github/home/.cache/pre-commit/pre-commit.log

Solution

  • Running inside a container is causing an issue. Container runs as root and all file system is owned by root. As a result git is unable to operate. Removing container works for me with this workflow:

    name: pre-commit
    
    on:
      workflow_dispatch:
    
    jobs:
      pre-commit-test:
        runs-on: ubuntu-latest
    
        steps:
          - name: Checkout repository
            uses: actions/checkout@v2
    
          - name: Set up Python 3.11
            uses: actions/setup-python@v2
            with:
              python-version: 3.11
    
          - name: Install dependencies
            run: python -m pip install --upgrade pip
    
          - name: Cache pre-commit hooks
            uses: actions/cache@v2
            with:
              path: ~/.cache/pre-commit
              key: ${{ runner.os }}-precommit-${{ hashFiles('.pre-commit-config.yaml') }}
    
          - name: Install pre-commit
            run: python -m pip install pre-commit
    
          - name: Run pre-commit with debug
            run: pre-commit run --all-files
    

    and this .pre-commit-config.yaml:

    repos:
    -   repo: https://github.com/pre-commit/pre-commit-hooks
        rev: v1.2.3
        hooks:
        -   id: trailing-whitespace