diff --git a/infra/specs/PRESUBMIT.py b/infra/specs/PRESUBMIT.py index f064cacaf8..0886ee6682 100644 --- a/infra/specs/PRESUBMIT.py +++ b/infra/specs/PRESUBMIT.py @@ -8,6 +8,7 @@ # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. +import difflib import os import shlex @@ -15,26 +16,37 @@ import shlex USE_PYTHON3 = True -def _HasLocalChanges(input_api): - ret = input_api.subprocess.call(['git', 'diff', '--quiet']) - return ret != 0 - - def CheckPatchFormatted(input_api, output_api): results = [] file_filter = lambda x: x.LocalPath().endswith('.pyl') - affected_files = input_api.AffectedFiles(include_deletes=False, - file_filter=file_filter) + affected_files = input_api.AffectedFiles( + include_deletes=False, file_filter=file_filter + ) + diffs = [] for f in affected_files: + # NewContents just reads the file. + prev_content = f.NewContents() + cmd = ['yapf', '-i', f.AbsoluteLocalPath()] if input_api.subprocess.call(cmd): results.append( - output_api.PresubmitError('Error calling "' + shlex.join(cmd) + '"')) + output_api.PresubmitError('Error calling "' + shlex.join(cmd) + '"') + ) - if _HasLocalChanges(input_api): - msg = ('Diff found after running "yapf -i" on modified .pyl files.\n' - 'Please commit or discard the new changes.') + new_content = f.NewContents() + if new_content != prev_content: + path = f.LocalPath() + diff = difflib.unified_diff(prev_content, new_content, path, path) + diffs.append(''.join(diff)) + + if diffs: + combined_diffs = '\n'.join(diffs) + msg = ( + 'Diff found after running "yapf -i" on modified .pyl files:\n' + f'{combined_diffs}\n' + 'Please commit or discard the new changes.' + ) results.append(output_api.PresubmitError(msg)) return results