|
| 1 | +from __future__ import print_function |
| 2 | +from __future__ import unicode_literals |
| 3 | + |
| 4 | +import io |
| 5 | +import os |
| 6 | +import os.path |
| 7 | +import pkg_resources |
| 8 | +import stat |
| 9 | + |
| 10 | + |
| 11 | +# This is used to identify the hook file we install |
| 12 | +IDENTIFYING_HASH = 'd8ee923c46731b42cd95cc869add4062' |
| 13 | + |
| 14 | + |
| 15 | +def is_our_pre_commit(filename): |
| 16 | + return IDENTIFYING_HASH in io.open(filename).read() |
| 17 | + |
| 18 | + |
| 19 | +def make_executable(filename): |
| 20 | + original_mode = os.stat(filename).st_mode |
| 21 | + os.chmod( |
| 22 | + filename, |
| 23 | + original_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH, |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +def install(runner, overwrite=False): |
| 28 | + """Install the pre-commit hooks.""" |
| 29 | + pre_commit_file = pkg_resources.resource_filename( |
| 30 | + 'pre_commit', 'resources/pre-commit-hook', |
| 31 | + ) |
| 32 | + |
| 33 | + # If we have an existing hook, move it to pre-commit.legacy |
| 34 | + if ( |
| 35 | + os.path.exists(runner.pre_commit_path) and |
| 36 | + not is_our_pre_commit(runner.pre_commit_path) |
| 37 | + ): |
| 38 | + os.rename(runner.pre_commit_path, runner.pre_commit_legacy_path) |
| 39 | + |
| 40 | + # If we specify overwrite, we simply delete the legacy file |
| 41 | + if overwrite and os.path.exists(runner.pre_commit_legacy_path): |
| 42 | + os.remove(runner.pre_commit_legacy_path) |
| 43 | + elif os.path.exists(runner.pre_commit_legacy_path): |
| 44 | + print( |
| 45 | + 'Running in migration mode with existing hooks at {0}\n' |
| 46 | + 'Use -f to use only pre-commit.'.format( |
| 47 | + runner.pre_commit_legacy_path, |
| 48 | + ) |
| 49 | + ) |
| 50 | + |
| 51 | + with open(runner.pre_commit_path, 'w') as pre_commit_file_obj: |
| 52 | + pre_commit_file_obj.write(open(pre_commit_file).read()) |
| 53 | + make_executable(runner.pre_commit_path) |
| 54 | + |
| 55 | + print('pre-commit installed at {0}'.format(runner.pre_commit_path)) |
| 56 | + return 0 |
| 57 | + |
| 58 | + |
| 59 | +def uninstall(runner): |
| 60 | + """Uninstall the pre-commit hooks.""" |
| 61 | + if os.path.exists(runner.pre_commit_path): |
| 62 | + os.remove(runner.pre_commit_path) |
| 63 | + print('pre-commit uninstalled') |
| 64 | + |
| 65 | + if os.path.exists(runner.pre_commit_legacy_path): |
| 66 | + os.rename(runner.pre_commit_legacy_path, runner.pre_commit_path) |
| 67 | + print('Restored previous hooks to {0}'.format(runner.pre_commit_path)) |
| 68 | + |
| 69 | + return 0 |
0 commit comments