diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py index 6a72149e..59901388 100644 --- a/pre_commit/commands/run.py +++ b/pre_commit/commands/run.py @@ -129,7 +129,7 @@ def _run_single_hook(classifier, hook, args, skips, cols, use_color): diff_after = cmd_output_b('git', 'diff', '--no-ext-diff', retcode=None) file_modifications = diff_before != diff_after - modified_ok = args.modified_files_ok + modified_ok = args.modified_files_ok or args.add_modified # If the hook makes changes, fail the commit if not modified_ok and file_modifications: @@ -169,6 +169,10 @@ def _run_single_hook(classifier, hook, args, skips, cols, use_color): output.write_line(out.strip(), logfile_name=hook.log_file) output.write_line() + if file_modifications and modified_ok: + output.write_line('Adding modified files to index\n') + git.add_all() + return retcode diff --git a/pre_commit/git.py b/pre_commit/git.py index 3ee9ca3a..37e45e38 100644 --- a/pre_commit/git.py +++ b/pre_commit/git.py @@ -192,3 +192,8 @@ def check_for_cygwin_mismatch(): exe_type[is_cygwin_python], exe_type[is_cygwin_git], ), ) + + +def add_all(repo='.'): + cmd = ('git', 'add', '.') + cmd_output(*cmd, cwd=repo) diff --git a/pre_commit/main.py b/pre_commit/main.py index ade17a51..e3242492 100644 --- a/pre_commit/main.py +++ b/pre_commit/main.py @@ -108,6 +108,15 @@ def _add_run_options(parser): 'Equivalent to setting the environment variable ' 'PRE_COMMIT_MODIFIED_FILES_OK=true.', ) + parser.add_argument( + '--add-modified', action='store_true', + default='PRE_COMMIT_ADD_MODIFIED_FILES' in os.environ, + help='Any file modifications made by hooks will be automatically ' + 'added to the index unless any hook fails. When set, file ' + "modification by hooks won't be equated with failure (same as if " + '--modified-files-ok is set). Equivalent to setting the ' + 'environment variable PRE_COMMIT_ADD_MODIFIED_FILES=true.', + ) mutex_group = parser.add_mutually_exclusive_group(required=False) mutex_group.add_argument( '--all-files', '-a', action='store_true', default=False, diff --git a/testing/util.py b/testing/util.py index fa706b2f..6a6ba54b 100644 --- a/testing/util.py +++ b/testing/util.py @@ -108,6 +108,7 @@ def run_opts( show_diff_on_failure=False, commit_msg_filename='', modified_files_ok=False, + add_modified=False, ): # These are mutually exclusive assert not (all_files and files) @@ -123,6 +124,7 @@ def run_opts( show_diff_on_failure=show_diff_on_failure, commit_msg_filename=commit_msg_filename, modified_files_ok=modified_files_ok, + add_modified=add_modified, )