|
| 1 | + |
| 2 | +import contextlib |
| 3 | +import logging |
| 4 | +import time |
| 5 | + |
| 6 | +from pre_commit.prefixed_command_runner import CalledProcessError |
| 7 | + |
| 8 | + |
| 9 | +logger = logging.getLogger('pre_commit') |
| 10 | + |
| 11 | + |
| 12 | +@contextlib.contextmanager |
| 13 | +def staged_files_only(cmd_runner): |
| 14 | + """Clear any unstaged changes from the git working directory inside this |
| 15 | + context. |
| 16 | +
|
| 17 | + Args: |
| 18 | + cmd_runner - PrefixedCommandRunner |
| 19 | + """ |
| 20 | + # Determine if there are unstaged files |
| 21 | + retcode, _, _ = cmd_runner.run( |
| 22 | + ['git', 'diff-files', '--quiet'], |
| 23 | + retcode=None, |
| 24 | + ) |
| 25 | + if retcode: |
| 26 | + patch_filename = cmd_runner.path('patch{0}'.format(int(time.time()))) |
| 27 | + logger.warning('Unstaged files detected.') |
| 28 | + logger.info( |
| 29 | + 'Stashing unstaged files to {0}.'.format(patch_filename), |
| 30 | + ) |
| 31 | + # Save the current unstaged changes as a patch |
| 32 | + with open(patch_filename, 'w') as patch_file: |
| 33 | + cmd_runner.run(['git', 'diff', '--binary'], stdout=patch_file) |
| 34 | + |
| 35 | + # Clear the working directory of unstaged changes |
| 36 | + cmd_runner.run(['git', 'checkout', '--', '.']) |
| 37 | + try: |
| 38 | + yield |
| 39 | + finally: |
| 40 | + # Try to apply the patch we saved |
| 41 | + try: |
| 42 | + cmd_runner.run(['git', 'apply', patch_filename]) |
| 43 | + except CalledProcessError: |
| 44 | + logger.warning( |
| 45 | + 'Stashed changes conflicted with hook auto-fixes... ' |
| 46 | + 'Rolling back fixes...' |
| 47 | + ) |
| 48 | + # We failed to apply the patch, presumably due to fixes made |
| 49 | + # by hooks. |
| 50 | + # Roll back the changes made by hooks. |
| 51 | + cmd_runner.run(['git', 'checkout', '--', '.']) |
| 52 | + cmd_runner.run(['git', 'apply', patch_filename]) |
| 53 | + logger.info('Restored changes from {0}.'.format(patch_filename)) |
| 54 | + else: |
| 55 | + # There weren't any staged files so we don't need to do anything |
| 56 | + # special |
| 57 | + yield |
0 commit comments