11
22import contextlib
3+ import logging
34import time
45
56from pre_commit .prefixed_command_runner import CalledProcessError
67
78
9+ logger = logging .getLogger ('pre_commit' )
10+
11+
812@contextlib .contextmanager
913def staged_files_only (cmd_runner ):
1014 """Clear any unstaged changes from the git working directory inside this
@@ -19,10 +23,12 @@ def staged_files_only(cmd_runner):
1923 retcode = None ,
2024 )
2125 if retcode :
22- # TODO: print a warning message that unstaged things are being stashed
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+ )
2331 # Save the current unstaged changes as a patch
24- # TODO: use a more unique patch filename
25- patch_filename = cmd_runner .path ('patch{0}' .format (time .time ()))
2632 with open (patch_filename , 'w' ) as patch_file :
2733 cmd_runner .run (['git' , 'diff' , '--binary' ], stdout = patch_file )
2834
@@ -35,12 +41,17 @@ def staged_files_only(cmd_runner):
3541 try :
3642 cmd_runner .run (['git' , 'apply' , patch_filename ])
3743 except CalledProcessError :
44+ logger .warning (
45+ 'Stashed changes conflicted with hook auto-fixes... '
46+ 'Rolling back fixes...'
47+ )
3848 # TOOD: print a warning about rolling back changes made by hooks
3949 # We failed to apply the patch, presumably due to fixes made
4050 # by hooks.
4151 # Roll back the changes made by hooks.
4252 cmd_runner .run (['git' , 'checkout' , '--' , '.' ])
4353 cmd_runner .run (['git' , 'apply' , patch_filename ])
54+ logger .info ('Restored changes from {0}.' .format (patch_filename ))
4455 else :
4556 # There weren't any staged files so we don't need to do anything
4657 # special
0 commit comments