Search code examples
javagithookcheckstyle

add checkstyle as pre-commit git hook


I am trying to add this: https://gist.github.com/davetron5000/37350 checkstyle code format check as pre-commit git hook.

I followed the instructions below but it doesn't work.

Steps I've tried:

  1. Checkstyle's jar file somewhere
  2. Checkstyle XML check file somewhere
  3. To configure git:
    • git config --add checkstyle.jar <location of jar>
    • git config --add checkstyle.checkfile <location of checkfile>
    • git config --add java.command <path to java executable> [optional, defaults to assuming it's in your path]
  4. Put this in your .git/hooks directory as pre-commit

Maybe it doesn't work because I dont understand what git config --add java.command <path to java executable> means. But it says it's optional If that's not the problem maybe I need to make the script-file an executable somehow?

ps: OS is Windows


Solution

  • Okay seems as i found a solution finally. I added some comments to the instructions how i made it work.

     1. checkstyle's jar file somewhere
     2. a checkstyle XML check file somewhere
     3. To configure git:
       * git config --add checkstyle.jar <location of jar>
       * git config --add checkstyle.checkfile <location of checkfile>
       * git config --add java.command <path to java executale> [optional
        defaults to assuming it's in your path]
    

    I checked my config (can be found in the .git directory of your git reposirtory) and it looked like this:

     ...    
     [checkstyle]   
     checkfile = C:\\Users\\schuster\\Desktop\\checkstyle
     jar = C:\\Users\\schuster\\Desktop\\checkstyle    
      ...   
    

    So since im Working on Windows i changed it to:

    ...
    [checkstyle]
        checkfile = C:/Users/schuster/Desktop/checkstyle/google_checks.xml
        jar = C:/Users/schuster/Desktop/checkstyle/checkstyle.jar
    ...
    

    .

     4. Put this in your .git/hooks directory as pre-commit
    

    'This' is the file i linked when i stated my problem. So this file needs to be in the /hooks directory. But it has to be renamed as one of the existing samples which are already in there. Since my hook is a pre-commit hook i took the "pre-commit" filename. Next this file has to become an executable. To do that type in chmod +x pre-commit in the /hooks directory of your git repository. If you work with Windows do that using the Git Bash.

    EDIT :

    In case someone want to use this script and is wondering why it doesnt abort even if checks fail - here is how to fix it. in line 58
    if (&run_and_log_system ($command))
    has to be chanted to
    if (!&run_and_log_system ($command))