Anee
Anee

Reputation: 483

Pre-commit hook in IntelliJ IDEA

I wanted to create a pre-commit hook in IntelliJ IDEA(Community Edition) to be used to create a list of all the files selected for the commit and dump it into an xml file. I am using a Team services VCS Git repository.

I have installed the Pre-Commit plugin as well. I am not sure what code goes into the "pre-commit-hook.sh" file to be able to achieve this. Can someone help me with this?

Upvotes: 3

Views: 8374

Answers (2)

jake77
jake77

Reputation: 2034

As the description of the plugin is not very helpful, there is my solution for Windows to run all tests before commiting:

  • create a file called pre-commit-hook.bat in the project root folder
  • create a .py file, e.g. prehook_runner.py that hold the python code you want to exectute before commit. In my case this was a call to the test runner: PATH_TO_ENV\python.exe PATH_TO_FILE/prehook_runner.py. This will be called by the bat file so make sure this runs in the Command Prompt.
  • put the code yopu want to run pre-commit in prehook_runner.py. My code (origin):

    import sys
    import unittest
    
    test_suite = unittest.defaultTestLoader.discover('.\\Test', 'test*.py')
    test_runner = unittest.TextTestRunner(resultclass=unittest.TextTestResult)
    result = test_runner.run(test_suite)
    if not result.wasSuccessful():
        print('')
        print('')
        print('SOME TESTS FAILED. You can still commit, but be aware.')
        print('')
        print('')
        print('')
    sys.exit(not result.wasSuccessful())
    

This would generate a popup if the tests fail.

Upvotes: 1

Marina Liu
Marina Liu

Reputation: 38126

To change the being committed file(s) extension to xml in pre-commit hook, you can use the below shell script:

#!/bin/sh

# find the staged files
for Sfile in $(git diff --name-only --cached)
do
{
  mv "$Sfile" "${Sfile%.*}.xml"
  git add ${Sfile%.*}.xml
}
done
# find the unstaged files
for USfile in $(git diff --name-only)
do
{
  mv "$USfile" "${USfile%.*}.xml"
  git add ${USfile%.*}.xml
}
done

Upvotes: 1

Related Questions