gitpre-commit-hookpre-commit.comgoogle-java-format

How to exclude a directory from google-java-format via Git pre-commit hook?


.pre-commit-hooks.yaml is like below:

-   id: google-style-java
    name: Google Java Code Style for Java
    description: Formats code in Google's Java codestyle.
    entry: ./format-code.sh
    language: script
    files: \.java$ 

What is the correct way to configure the exclude setting in my .pre-commit-hooks.yaml for the google-style-java hook to prevent it from processing any .java files located within a directory named generated, or any subdirectory under generated directory?

I tried adding exclude like below:

-   id: google-style-java
    name: Google Java Code Style for Java
    description: Formats code in Google's Java codestyle.
    entry: ./format-code.sh
    language: script
    files: \.java$
    exclude: ^generated/

But still it is formatting all files under generated or sub-folder under it.

format-code.sh looks like below:

#!/usr/bin/env sh

VERSION="1.24.0"

mkdir -p .cache
cd .cache
if [ ! -f google-java-format-${VERSION}-all-deps.jar ]
then
    curl -LJO "https://github.com/google/google-java-format/releases/download/v${VERSION}/google-java-format-${VERSION}-all-deps.jar"
    chmod 755 google-java-format-${VERSION}-all-deps.jar
fi
cd ..

java \
--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \
--add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED \
--add-exports jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED \
--add-exports jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED \
--add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED \
--add-exports jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED \
--add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED \
--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED \
--add-opens jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED \
--add-opens jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED \
-jar .cache/google-java-format-${VERSION}-all-deps.jar --replace $@

Solution

  • I had to update the exclude like below to handle directory structure com/nex/schema/monitoring/generated/DefaultSchema.java

    exclude: (^|/)generated/
    

    It can be added in either .pre-commit-config.yaml like below

    repos:
      - repo: https://github.com/maltzj/google-style-precommit-hook
        rev: b7e9e7fcba4a5aea463e72fe9964c14877bd8130
        hooks:
          - id: google-style-java
            files: \.java$
            exclude: (^|/)generated/
    

    or in pre-commit-hooks.yaml like below

    -   id: google-style-java
        name: Google Java Code Style for Java
        description: Formats code in Google's Java codestyle.
        entry: ./format-code.sh
        language: script
        files: \.java$ 
        exclude: (^|/)generated/