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 <jleconte@google.com>
Commit-Queue: Jeremy Leconte <jleconte@webrtc.org>
Reviewed-by: Jeremy Leconte <jleconte@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#42674}
This commit is contained in:
Gavin Mak 2024-07-25 20:16:31 +00:00 committed by WebRTC LUCI CQ
parent e9d066d3b7
commit d7d21337d1

View File

@ -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