From d7d21337d1d027740a57dfa4e7f12e722a415547 Mon Sep 17 00:00:00 2001 From: Gavin Mak Date: Thu, 25 Jul 2024 20:16:31 +0000 Subject: [PATCH] Support infra/specs/PRESUBMIT.py on cog cog workspaces don't have a git directory and can't run "git diff". Replace it with python's difflib instead. Bug: b/333744051 Change-Id: I5bd8ccd873a0db55f0bbadf165180b3f2aa42903 Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/357900 Reviewed-by: Jeremy Leconte Commit-Queue: Jeremy Leconte Reviewed-by: Jeremy Leconte Cr-Commit-Position: refs/heads/main@{#42674} --- infra/specs/PRESUBMIT.py | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) 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