Pre-commit hook in IntelliJ IDEA

Viewed 7168

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?

2 Answers

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.

Related