]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Scripts/PatchCheck.py
6aec15d0f0b23bd58c13efac5b0ecf3c5457f36e
2 # Check a patch for various format issues
4 # Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.<BR>
6 # SPDX-License-Identifier: BSD-2-Clause-Patent
9 from __future__
import print_function
12 __copyright__
= "Copyright (c) 2015 - 2016, Intel Corporation All rights reserved."
22 SILENT
, ONELINE
, NORMAL
= range(3)
25 class CommitMessageCheck
:
26 """Checks the contents of a git commit message."""
28 def __init__(self
, subject
, message
):
31 if subject
is None and message
is None:
32 self
.error('Commit message is missing!')
35 self
.subject
= subject
38 self
.check_contributed_under()
39 self
.check_signed_off_by()
40 self
.check_misc_signatures()
41 self
.check_overall_format()
42 self
.report_message_result()
44 url
= 'https://github.com/tianocore/tianocore.github.io/wiki/Commit-Message-Format'
46 def report_message_result(self
):
47 if Verbose
.level
< Verbose
.NORMAL
:
52 print('The commit message format passed all checks.')
58 def error(self
, *err
):
59 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
60 print('The commit message format is not valid:')
62 if Verbose
.level
< Verbose
.NORMAL
:
66 prefix
= (' *', ' ')[count
> 0]
70 # Find 'contributed-under:' at the start of a line ignoring case and
71 # requires ':' to be present. Matches if there is white space before
72 # the tag or between the tag and the ':'.
73 contributed_under_re
= \
74 re
.compile(r
'^\s*contributed-under\s*:', re
.MULTILINE|re
.IGNORECASE
)
76 def check_contributed_under(self
):
77 match
= self
.contributed_under_re
.search(self
.msg
)
79 self
.error('Contributed-under! (Note: this must be ' +
80 'removed by the code contributor!)')
83 def make_signature_re(sig
, re_input
=False):
87 sub_re
= sig
.replace('-', r
'[-\s]+')
88 re_str
= (r
'^(?P<tag>' + sub_re
+
89 r
')(\s*):(\s*)(?P<value>\S.*?)(?:\s*)$')
91 return re
.compile(re_str
, re
.MULTILINE|re
.IGNORECASE
)
93 print("Tried to compile re:", re_str
)
98 (?: (?P<tag>[^:]+) \s* : \s*
101 (?: \[ (?P<updater>[^:]+) \s* : \s*
102 (?P<note>.+?) \s* \] )
104 re
.VERBOSE | re
.MULTILINE
)
106 def find_signatures(self
, sig
):
107 if not sig
.endswith('-by') and sig
!= 'Cc':
109 regex
= self
.make_signature_re(sig
)
111 sigs
= regex
.findall(self
.msg
)
113 bad_case_sigs
= filter(lambda m
: m
[0] != sig
, sigs
)
114 for s
in bad_case_sigs
:
115 self
.error("'" +s
[0] + "' should be '" + sig
+ "'")
119 self
.error('There should be no spaces between ' + sig
+
122 self
.error("There should be a space after '" + sig
+ ":'")
124 self
.check_email_address(s
[3])
128 email_re1
= re
.compile(r
'(?:\s*)(.*?)(\s*)<(.+)>\s*$',
129 re
.MULTILINE|re
.IGNORECASE
)
131 def check_email_address(self
, email
):
132 email
= email
.strip()
133 mo
= self
.email_re1
.match(email
)
135 self
.error("Email format is invalid: " + email
.strip())
138 name
= mo
.group(1).strip()
140 self
.error("Name is not provided with email address: " +
143 quoted
= len(name
) > 2 and name
[0] == '"' and name
[-1] == '"'
144 if name
.find(',') >= 0 and not quoted
:
145 self
.error('Add quotes (") around name with a comma: ' +
148 if mo
.group(2) == '':
149 self
.error("There should be a space between the name and " +
150 "email address: " + email
)
152 if mo
.group(3).find(' ') >= 0:
153 self
.error("The email address cannot contain a space: " +
156 def check_signed_off_by(self
):
158 if self
.msg
.find(sob
) < 0:
159 self
.error('Missing Signed-off-by! (Note: this must be ' +
160 'added by the code contributor!)')
163 sobs
= self
.find_signatures('Signed-off')
166 self
.error('Invalid Signed-off-by format!')
178 def check_misc_signatures(self
):
179 for sig
in self
.sig_types
:
180 self
.find_signatures(sig
)
182 def check_overall_format(self
):
183 lines
= self
.msg
.splitlines()
185 if len(lines
) >= 1 and lines
[0].endswith('\r\n'):
190 lines
.insert(0, empty_line
)
191 lines
.insert(0, self
.subject
+ empty_line
)
196 self
.error('Empty commit message!')
199 if count
>= 1 and len(lines
[0]) >= 72:
200 self
.error('First line of commit message (subject line) ' +
203 if count
>= 1 and len(lines
[0].strip()) == 0:
204 self
.error('First line of commit message (subject line) ' +
207 if count
>= 2 and lines
[1].strip() != '':
208 self
.error('Second line of commit message should be ' +
211 for i
in range(2, count
):
212 if (len(lines
[i
]) >= 76 and
213 len(lines
[i
].split()) > 1 and
214 not lines
[i
].startswith('git-svn-id:')):
215 self
.error('Line %d of commit message is too long.' % (i
+ 1))
218 for i
in range(count
- 1, 0, -1):
220 mo
= self
.sig_block_re
.match(line
)
222 if line
.strip() == '':
224 elif last_sig_line
is not None:
225 err2
= 'Add empty line before "%s"?' % last_sig_line
226 self
.error('The line before the signature block ' +
227 'should be empty', err2
)
229 self
.error('The signature block was not found')
231 last_sig_line
= line
.strip()
233 (START
, PRE_PATCH
, PATCH
) = range(3)
236 """Checks the contents of a git diff."""
238 def __init__(self
, diff
):
240 self
.format_ok
= True
241 self
.lines
= diff
.splitlines(True)
242 self
.count
= len(self
.lines
)
246 while self
.line_num
< self
.count
and self
.format_ok
:
247 line_num
= self
.line_num
249 assert(self
.line_num
> line_num
)
250 self
.report_message_result()
252 def report_message_result(self
):
253 if Verbose
.level
< Verbose
.NORMAL
:
256 print('The code passed all checks.')
258 print('\nWARNING - The following binary files will be added ' +
259 'into the repository:')
260 for binary
in self
.new_bin
:
264 line
= self
.lines
[self
.line_num
]
266 if self
.state
in (PRE_PATCH
, PATCH
):
267 if line
.startswith('diff --git'):
269 if self
.state
== PATCH
:
270 if line
.startswith('@@ '):
271 self
.state
= PRE_PATCH
272 elif len(line
) >= 1 and line
[0] not in ' -+' and \
273 not line
.startswith(r
'\ No newline ') and not self
.binary
:
274 for line
in self
.lines
[self
.line_num
+ 1:]:
275 if line
.startswith('diff --git'):
276 self
.format_error('diff found after end of patch')
278 self
.line_num
= self
.count
281 if self
.state
== START
:
282 if line
.startswith('diff --git'):
283 self
.state
= PRE_PATCH
284 self
.filename
= line
[13:].split(' ', 1)[0]
285 self
.is_newfile
= False
286 self
.force_crlf
= not self
.filename
.endswith('.sh')
287 elif len(line
.rstrip()) != 0:
288 self
.format_error("didn't find diff command")
290 elif self
.state
== PRE_PATCH
:
291 if line
.startswith('@@ '):
294 elif line
.startswith('GIT binary patch') or \
295 line
.startswith('Binary files'):
299 self
.new_bin
.append(self
.filename
)
302 self
.is_newfile
= self
.newfile_prefix_re
.match(line
)
303 for pfx
in self
.pre_patch_prefixes
:
304 if line
.startswith(pfx
):
307 self
.format_error("didn't find diff hunk marker (@@)")
309 elif self
.state
== PATCH
:
312 elif line
.startswith('-'):
314 elif line
.startswith('+'):
315 self
.check_added_line(line
[1:])
316 elif line
.startswith(r
'\ No newline '):
318 elif not line
.startswith(' '):
319 self
.format_error("unexpected patch line")
322 pre_patch_prefixes
= (
334 line_endings
= ('\r\n', '\n\r', '\n', '\r')
336 newfile_prefix_re
= \
342 def added_line_error(self
, msg
, line
):
344 if self
.filename
is not None:
345 lines
.append('File: ' + self
.filename
)
346 lines
.append('Line: ' + line
)
352 DEBUG \s* \( \s* \( \s*
353 (?: DEBUG_[A-Z_]+ \s* \| \s*)*
358 def check_added_line(self
, line
):
360 for an_eol
in self
.line_endings
:
361 if line
.endswith(an_eol
):
363 line
= line
[:-len(eol
)]
365 stripped
= line
.rstrip()
367 if self
.force_crlf
and eol
!= '\r\n':
368 self
.added_line_error('Line ending (%s) is not CRLF' % repr(eol
),
371 self
.added_line_error('Tab character used', line
)
372 if len(stripped
) < len(line
):
373 self
.added_line_error('Trailing whitespace found', line
)
375 mo
= self
.old_debug_re
.search(line
)
377 self
.added_line_error('EFI_D_' + mo
.group(1) + ' was used, '
378 'but DEBUG_' + mo
.group(1) +
379 ' is now recommended', line
)
381 split_diff_re
= re
.compile(r
'''
383 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
389 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
391 def format_error(self
, err
):
392 self
.format_ok
= False
393 err
= 'Patch format error: ' + err
394 err2
= 'Line: ' + self
.lines
[self
.line_num
].rstrip()
395 self
.error(err
, err2
)
397 def error(self
, *err
):
398 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
399 print('Code format is not valid:')
401 if Verbose
.level
< Verbose
.NORMAL
:
405 prefix
= (' *', ' ')[count
> 0]
410 """Checks the contents of a git email formatted patch.
412 Various checks are performed on both the commit message and the
416 def __init__(self
, name
, patch
):
418 self
.find_patch_pieces()
420 msg_check
= CommitMessageCheck(self
.commit_subject
, self
.commit_msg
)
421 msg_ok
= msg_check
.ok
424 if self
.diff
is not None:
425 diff_check
= GitDiffCheck(self
.diff
)
426 diff_ok
= diff_check
.ok
428 self
.ok
= msg_ok
and diff_ok
430 if Verbose
.level
== Verbose
.ONELINE
:
436 result
.append('commit message')
438 result
.append('diff content')
439 result
= 'bad ' + ' and '.join(result
)
443 git_diff_re
= re
.compile(r
'''
444 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
446 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
450 (?P<commit_message> [\s\S\r\n]* )
453 (?: ^ \s+ .+ \s+ \| \s+ \d+ \s+ \+* \-*
458 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
460 subject_prefix_re
= \
463 [^\[\]]* # Allow all non-brackets
468 def find_patch_pieces(self
):
469 if sys
.version_info
< (3, 0):
470 patch
= self
.patch
.encode('ascii', 'ignore')
474 self
.commit_msg
= None
476 self
.commit_subject
= None
477 self
.commit_prefix
= None
480 if patch
.startswith('diff --git'):
484 pmail
= email
.message_from_string(patch
)
485 parts
= list(pmail
.walk())
486 assert(len(parts
) == 1)
487 assert(parts
[0].get_content_type() == 'text/plain')
488 content
= parts
[0].get_payload(decode
=True).decode('utf-8', 'ignore')
490 mo
= self
.git_diff_re
.search(content
)
492 self
.diff
= content
[mo
.start():]
493 content
= content
[:mo
.start()]
495 mo
= self
.stat_re
.search(content
)
497 self
.commit_msg
= content
499 self
.stat
= mo
.group('stat')
500 self
.commit_msg
= mo
.group('commit_message')
502 self
.commit_subject
= pmail
['subject'].replace('\r\n', '')
503 self
.commit_subject
= self
.commit_subject
.replace('\n', '')
504 self
.commit_subject
= self
.subject_prefix_re
.sub('', self
.commit_subject
, 1)
506 class CheckGitCommits
:
507 """Reads patches from git based on the specified git revision range.
509 The patches are read from git, and then checked.
512 def __init__(self
, rev_spec
, max_count
):
513 commits
= self
.read_commit_list_from_git(rev_spec
, max_count
)
514 if len(commits
) == 1 and Verbose
.level
> Verbose
.ONELINE
:
515 commits
= [ rev_spec
]
518 for commit
in commits
:
519 if Verbose
.level
> Verbose
.ONELINE
:
524 print('Checking git commit:', commit
)
525 patch
= self
.read_patch_from_git(commit
)
526 self
.ok
&= CheckOnePatch(commit
, patch
).ok
528 print("Couldn't find commit matching: '{}'".format(rev_spec
))
530 def read_commit_list_from_git(self
, rev_spec
, max_count
):
531 # Run git to get the commit patch
532 cmd
= [ 'rev-list', '--abbrev-commit', '--no-walk' ]
533 if max_count
is not None:
534 cmd
.append('--max-count=' + str(max_count
))
536 out
= self
.run_git(*cmd
)
537 return out
.split() if out
else []
539 def read_patch_from_git(self
, commit
):
540 # Run git to get the commit patch
541 return self
.run_git('show', '--pretty=email', commit
)
543 def run_git(self
, *args
):
546 p
= subprocess
.Popen(cmd
,
547 stdout
=subprocess
.PIPE
,
548 stderr
=subprocess
.STDOUT
)
549 Result
= p
.communicate()
550 return Result
[0].decode('utf-8', 'ignore') if Result
[0] and Result
[0].find(b
"fatal")!=0 else None
552 class CheckOnePatchFile
:
553 """Performs a patch check for a single file.
555 stdin is used when the filename is '-'.
558 def __init__(self
, patch_filename
):
559 if patch_filename
== '-':
560 patch
= sys
.stdin
.read()
561 patch_filename
= 'stdin'
563 f
= open(patch_filename
, 'rb')
564 patch
= f
.read().decode('utf-8', 'ignore')
566 if Verbose
.level
> Verbose
.ONELINE
:
567 print('Checking patch file:', patch_filename
)
568 self
.ok
= CheckOnePatch(patch_filename
, patch
).ok
571 """Performs a patch check for a single command line argument.
573 The argument will be handed off to a file or git-commit based
577 def __init__(self
, param
, max_count
=None):
579 if param
== '-' or os
.path
.exists(param
):
580 checker
= CheckOnePatchFile(param
)
582 checker
= CheckGitCommits(param
, max_count
)
586 """Checks patches based on the command line arguments."""
590 patches
= self
.args
.patches
592 if len(patches
) == 0:
597 for patch
in patches
:
598 self
.process_one_arg(patch
)
600 if self
.count
is not None:
601 self
.process_one_arg('HEAD')
608 def process_one_arg(self
, arg
):
609 if len(arg
) >= 2 and arg
[0] == '-':
611 self
.count
= int(arg
[1:])
615 self
.ok
&= CheckOneArg(arg
, self
.count
).ok
618 def parse_options(self
):
619 parser
= argparse
.ArgumentParser(description
=__copyright__
)
620 parser
.add_argument('--version', action
='version',
621 version
='%(prog)s ' + VersionNumber
)
622 parser
.add_argument('patches', nargs
='*',
623 help='[patch file | git rev list]')
624 group
= parser
.add_mutually_exclusive_group()
625 group
.add_argument("--oneline",
627 help="Print one result per line")
628 group
.add_argument("--silent",
630 help="Print nothing")
631 self
.args
= parser
.parse_args()
632 if self
.args
.oneline
:
633 Verbose
.level
= Verbose
.ONELINE
635 Verbose
.level
= Verbose
.SILENT
637 if __name__
== "__main__":
638 sys
.exit(PatchCheckApp().retval
)