]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Scripts/PatchCheck.py
2 # Check a patch for various format issues
4 # Copyright (c) 2015 - 2021, Intel Corporation. All rights reserved.<BR>
5 # Copyright (C) 2020, Red Hat, Inc.<BR>
6 # Copyright (c) 2020, ARM Ltd. All rights reserved.<BR>
8 # SPDX-License-Identifier: BSD-2-Clause-Patent
11 from __future__
import print_function
14 __copyright__
= "Copyright (c) 2015 - 2016, Intel Corporation All rights reserved."
26 SILENT
, ONELINE
, NORMAL
= range(3)
29 class EmailAddressCheck
:
30 """Checks an email address."""
32 def __init__(self
, email
, description
):
36 self
.error('Email address is missing!')
38 if description
is None:
39 self
.error('Email description is missing!')
42 self
.description
= "'" + description
+ "'"
43 self
.check_email_address(email
)
45 def error(self
, *err
):
46 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
47 print('The ' + self
.description
+ ' email address is not valid:')
49 if Verbose
.level
< Verbose
.NORMAL
:
53 prefix
= (' *', ' ')[count
> 0]
57 email_re1
= re
.compile(r
'(?:\s*)(.*?)(\s*)<(.+)>\s*$',
58 re
.MULTILINE|re
.IGNORECASE
)
60 def check_email_address(self
, email
):
62 mo
= self
.email_re1
.match(email
)
64 self
.error("Email format is invalid: " + email
.strip())
67 name
= mo
.group(1).strip()
69 self
.error("Name is not provided with email address: " +
72 quoted
= len(name
) > 2 and name
[0] == '"' and name
[-1] == '"'
73 if name
.find(',') >= 0 and not quoted
:
74 self
.error('Add quotes (") around name with a comma: ' +
78 self
.error("There should be a space between the name and " +
79 "email address: " + email
)
81 if mo
.group(3).find(' ') >= 0:
82 self
.error("The email address cannot contain a space: " +
85 if ' via Groups.Io' in name
and mo
.group(3).endswith('@groups.io'):
86 self
.error("Email rewritten by lists DMARC / DKIM / SPF: " +
89 class CommitMessageCheck
:
90 """Checks the contents of a git commit message."""
92 def __init__(self
, subject
, message
, author_email
):
95 if subject
is None and message
is None:
96 self
.error('Commit message is missing!')
100 if "mergify[bot]@users.noreply.github.com" in author_email
:
101 if "Merge branch" in subject
:
104 self
.subject
= subject
109 self
.check_contributed_under()
111 self
.check_signed_off_by()
112 self
.check_misc_signatures()
113 self
.check_overall_format()
114 self
.report_message_result()
116 url
= 'https://github.com/tianocore/tianocore.github.io/wiki/Commit-Message-Format'
118 def report_message_result(self
):
119 if Verbose
.level
< Verbose
.NORMAL
:
124 print('The commit message format passed all checks.')
130 def error(self
, *err
):
131 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
132 print('The commit message format is not valid:')
134 if Verbose
.level
< Verbose
.NORMAL
:
138 prefix
= (' *', ' ')[count
> 0]
142 # Find 'contributed-under:' at the start of a line ignoring case and
143 # requires ':' to be present. Matches if there is white space before
144 # the tag or between the tag and the ':'.
145 contributed_under_re
= \
146 re
.compile(r
'^\s*contributed-under\s*:', re
.MULTILINE|re
.IGNORECASE
)
148 def check_contributed_under(self
):
149 match
= self
.contributed_under_re
.search(self
.msg
)
150 if match
is not None:
151 self
.error('Contributed-under! (Note: this must be ' +
152 'removed by the code contributor!)')
155 def make_signature_re(sig
, re_input
=False):
159 sub_re
= sig
.replace('-', r
'[-\s]+')
160 re_str
= (r
'^(?P<tag>' + sub_re
+
161 r
')(\s*):(\s*)(?P<value>\S.*?)(?:\s*)$')
163 return re
.compile(re_str
, re
.MULTILINE|re
.IGNORECASE
)
165 print("Tried to compile re:", re_str
)
170 (?: (?P<tag>[^:]+) \s* : \s*
173 (?: \[ (?P<updater>[^:]+) \s* : \s*
174 (?P<note>.+?) \s* \] )
176 re
.VERBOSE | re
.MULTILINE
)
178 def find_signatures(self
, sig
):
179 if not sig
.endswith('-by') and sig
!= 'Cc':
181 regex
= self
.make_signature_re(sig
)
183 sigs
= regex
.findall(self
.msg
)
185 bad_case_sigs
= filter(lambda m
: m
[0] != sig
, sigs
)
186 for s
in bad_case_sigs
:
187 self
.error("'" +s
[0] + "' should be '" + sig
+ "'")
191 self
.error('There should be no spaces between ' + sig
+
194 self
.error("There should be a space after '" + sig
+ ":'")
196 EmailAddressCheck(s
[3], sig
)
200 def check_signed_off_by(self
):
202 if self
.msg
.find(sob
) < 0:
203 self
.error('Missing Signed-off-by! (Note: this must be ' +
204 'added by the code contributor!)')
207 sobs
= self
.find_signatures('Signed-off')
210 self
.error('Invalid Signed-off-by format!')
222 def check_misc_signatures(self
):
223 for sig
in self
.sig_types
:
224 self
.find_signatures(sig
)
226 cve_re
= re
.compile('CVE-[0-9]{4}-[0-9]{5}[^0-9]')
228 def check_overall_format(self
):
229 lines
= self
.msg
.splitlines()
231 if len(lines
) >= 1 and lines
[0].endswith('\r\n'):
236 lines
.insert(0, empty_line
)
237 lines
.insert(0, self
.subject
+ empty_line
)
242 self
.error('Empty commit message!')
245 if count
>= 1 and re
.search(self
.cve_re
, lines
[0]):
247 # If CVE-xxxx-xxxxx is present in subject line, then limit length of
248 # subject line to 92 characters
250 if len(lines
[0].rstrip()) >= 93:
252 'First line of commit message (subject line) is too long (%d >= 93).' %
253 (len(lines
[0].rstrip()))
257 # If CVE-xxxx-xxxxx is not present in subject line, then limit
258 # length of subject line to 75 characters
260 if len(lines
[0].rstrip()) >= 76:
262 'First line of commit message (subject line) is too long (%d >= 76).' %
263 (len(lines
[0].rstrip()))
266 if count
>= 1 and len(lines
[0].strip()) == 0:
267 self
.error('First line of commit message (subject line) ' +
270 if count
>= 2 and lines
[1].strip() != '':
271 self
.error('Second line of commit message should be ' +
274 for i
in range(2, count
):
275 if (len(lines
[i
]) >= 76 and
276 len(lines
[i
].split()) > 1 and
277 not lines
[i
].startswith('git-svn-id:') and
278 not lines
[i
].startswith('Reviewed-by') and
279 not lines
[i
].startswith('Acked-by:') and
280 not lines
[i
].startswith('Tested-by:') and
281 not lines
[i
].startswith('Reported-by:') and
282 not lines
[i
].startswith('Suggested-by:') and
283 not lines
[i
].startswith('Signed-off-by:') and
284 not lines
[i
].startswith('Cc:')):
286 # Print a warning if body line is longer than 75 characters
289 'WARNING - Line %d of commit message is too long (%d >= 76).' %
290 (i
+ 1, len(lines
[i
]))
295 for i
in range(count
- 1, 0, -1):
297 mo
= self
.sig_block_re
.match(line
)
299 if line
.strip() == '':
301 elif last_sig_line
is not None:
302 err2
= 'Add empty line before "%s"?' % last_sig_line
303 self
.error('The line before the signature block ' +
304 'should be empty', err2
)
306 self
.error('The signature block was not found')
308 last_sig_line
= line
.strip()
310 (START
, PRE_PATCH
, PATCH
) = range(3)
313 """Checks the contents of a git diff."""
315 def __init__(self
, diff
):
317 self
.format_ok
= True
318 self
.lines
= diff
.splitlines(True)
319 self
.count
= len(self
.lines
)
323 while self
.line_num
< self
.count
and self
.format_ok
:
324 line_num
= self
.line_num
326 assert(self
.line_num
> line_num
)
327 self
.report_message_result()
329 def report_message_result(self
):
330 if Verbose
.level
< Verbose
.NORMAL
:
333 print('The code passed all checks.')
335 print('\nWARNING - The following binary files will be added ' +
336 'into the repository:')
337 for binary
in self
.new_bin
:
341 line
= self
.lines
[self
.line_num
]
343 if self
.state
in (PRE_PATCH
, PATCH
):
344 if line
.startswith('diff --git'):
346 if self
.state
== PATCH
:
347 if line
.startswith('@@ '):
348 self
.state
= PRE_PATCH
349 elif len(line
) >= 1 and line
[0] not in ' -+' and \
350 not line
.startswith('\r\n') and \
351 not line
.startswith(r
'\ No newline ') and not self
.binary
:
352 for line
in self
.lines
[self
.line_num
+ 1:]:
353 if line
.startswith('diff --git'):
354 self
.format_error('diff found after end of patch')
356 self
.line_num
= self
.count
359 if self
.state
== START
:
360 if line
.startswith('diff --git'):
361 self
.state
= PRE_PATCH
362 self
.filename
= line
[13:].split(' ', 1)[0]
363 self
.is_newfile
= False
364 self
.force_crlf
= True
365 self
.force_notabs
= True
366 if self
.filename
.endswith('.sh') or \
367 self
.filename
.startswith('BaseTools/BinWrappers/PosixLike/') or \
368 self
.filename
.startswith('BaseTools/BinPipWrappers/PosixLike/') or \
369 self
.filename
== 'BaseTools/BuildEnv':
371 # Do not enforce CR/LF line endings for linux shell scripts.
372 # Some linux shell scripts don't end with the ".sh" extension,
373 # they are identified by their path.
375 self
.force_crlf
= False
376 if self
.filename
== '.gitmodules' or \
377 self
.filename
== 'BaseTools/Conf/diff.order':
379 # .gitmodules and diff orderfiles are used internally by git
380 # use tabs and LF line endings. Do not enforce no tabs and
381 # do not enforce CR/LF line endings.
383 self
.force_crlf
= False
384 self
.force_notabs
= False
385 if os
.path
.basename(self
.filename
) == 'GNUmakefile' or \
386 os
.path
.basename(self
.filename
) == 'Makefile':
387 self
.force_notabs
= False
388 elif len(line
.rstrip()) != 0:
389 self
.format_error("didn't find diff command")
391 elif self
.state
== PRE_PATCH
:
392 if line
.startswith('@@ '):
395 elif line
.startswith('GIT binary patch') or \
396 line
.startswith('Binary files'):
400 self
.new_bin
.append(self
.filename
)
401 elif line
.startswith('new file mode 160000'):
403 # New submodule. Do not enforce CR/LF line endings
405 self
.force_crlf
= False
408 self
.is_newfile
= self
.newfile_prefix_re
.match(line
)
409 for pfx
in self
.pre_patch_prefixes
:
410 if line
.startswith(pfx
):
413 self
.format_error("didn't find diff hunk marker (@@)")
415 elif self
.state
== PATCH
:
418 elif line
.startswith('-'):
420 elif line
.startswith('+'):
421 self
.check_added_line(line
[1:])
422 elif line
.startswith('\r\n'):
424 elif line
.startswith(r
'\ No newline '):
426 elif not line
.startswith(' '):
427 self
.format_error("unexpected patch line")
430 pre_patch_prefixes
= (
444 line_endings
= ('\r\n', '\n\r', '\n', '\r')
446 newfile_prefix_re
= \
452 def added_line_error(self
, msg
, line
):
454 if self
.filename
is not None:
455 lines
.append('File: ' + self
.filename
)
456 lines
.append('Line: ' + line
)
462 DEBUG \s* \( \s* \( \s*
463 (?: DEBUG_[A-Z_]+ \s* \| \s*)*
468 def check_added_line(self
, line
):
470 for an_eol
in self
.line_endings
:
471 if line
.endswith(an_eol
):
473 line
= line
[:-len(eol
)]
475 stripped
= line
.rstrip()
477 if self
.force_crlf
and eol
!= '\r\n' and (line
.find('Subproject commit') == -1):
478 self
.added_line_error('Line ending (%s) is not CRLF' % repr(eol
),
480 if self
.force_notabs
and '\t' in line
:
481 self
.added_line_error('Tab character used', line
)
482 if len(stripped
) < len(line
):
483 self
.added_line_error('Trailing whitespace found', line
)
485 mo
= self
.old_debug_re
.search(line
)
487 self
.added_line_error('EFI_D_' + mo
.group(1) + ' was used, '
488 'but DEBUG_' + mo
.group(1) +
489 ' is now recommended', line
)
491 split_diff_re
= re
.compile(r
'''
493 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
499 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
501 def format_error(self
, err
):
502 self
.format_ok
= False
503 err
= 'Patch format error: ' + err
504 err2
= 'Line: ' + self
.lines
[self
.line_num
].rstrip()
505 self
.error(err
, err2
)
507 def error(self
, *err
):
508 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
509 print('Code format is not valid:')
511 if Verbose
.level
< Verbose
.NORMAL
:
515 prefix
= (' *', ' ')[count
> 0]
520 """Checks the contents of a git email formatted patch.
522 Various checks are performed on both the commit message and the
526 def __init__(self
, name
, patch
):
528 self
.find_patch_pieces()
530 email_check
= EmailAddressCheck(self
.author_email
, 'Author')
531 email_ok
= email_check
.ok
533 msg_check
= CommitMessageCheck(self
.commit_subject
, self
.commit_msg
, self
.author_email
)
534 msg_ok
= msg_check
.ok
537 if self
.diff
is not None:
538 diff_check
= GitDiffCheck(self
.diff
)
539 diff_ok
= diff_check
.ok
541 self
.ok
= email_ok
and msg_ok
and diff_ok
543 if Verbose
.level
== Verbose
.ONELINE
:
549 result
.append('commit message')
551 result
.append('diff content')
552 result
= 'bad ' + ' and '.join(result
)
556 git_diff_re
= re
.compile(r
'''
557 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
559 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
563 (?P<commit_message> [\s\S\r\n]* )
566 (?: ^ \s+ .+ \s+ \| \s+ \d+ \s+ \+* \-*
571 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
573 subject_prefix_re
= \
576 [^\[\]]* # Allow all non-brackets
581 def find_patch_pieces(self
):
582 if sys
.version_info
< (3, 0):
583 patch
= self
.patch
.encode('ascii', 'ignore')
587 self
.commit_msg
= None
589 self
.commit_subject
= None
590 self
.commit_prefix
= None
593 if patch
.startswith('diff --git'):
597 pmail
= email
.message_from_string(patch
)
598 parts
= list(pmail
.walk())
599 assert(len(parts
) == 1)
600 assert(parts
[0].get_content_type() == 'text/plain')
601 content
= parts
[0].get_payload(decode
=True).decode('utf-8', 'ignore')
603 mo
= self
.git_diff_re
.search(content
)
605 self
.diff
= content
[mo
.start():]
606 content
= content
[:mo
.start()]
608 mo
= self
.stat_re
.search(content
)
610 self
.commit_msg
= content
612 self
.stat
= mo
.group('stat')
613 self
.commit_msg
= mo
.group('commit_message')
615 # Parse subject line from email header. The subject line may be
616 # composed of multiple parts with different encodings. Decode and
617 # combine all the parts to produce a single string with the contents of
618 # the decoded subject line.
620 parts
= email
.header
.decode_header(pmail
.get('subject'))
622 for (part
, encoding
) in parts
:
624 part
= part
.decode(encoding
)
630 subject
= subject
+ part
632 self
.commit_subject
= subject
.replace('\r\n', '')
633 self
.commit_subject
= self
.commit_subject
.replace('\n', '')
634 self
.commit_subject
= self
.subject_prefix_re
.sub('', self
.commit_subject
, 1)
636 self
.author_email
= pmail
['from']
638 class CheckGitCommits
:
639 """Reads patches from git based on the specified git revision range.
641 The patches are read from git, and then checked.
644 def __init__(self
, rev_spec
, max_count
):
645 commits
= self
.read_commit_list_from_git(rev_spec
, max_count
)
646 if len(commits
) == 1 and Verbose
.level
> Verbose
.ONELINE
:
647 commits
= [ rev_spec
]
650 for commit
in commits
:
651 if Verbose
.level
> Verbose
.ONELINE
:
656 print('Checking git commit:', commit
)
657 email
= self
.read_committer_email_address_from_git(commit
)
658 self
.ok
&= EmailAddressCheck(email
, 'Committer').ok
659 patch
= self
.read_patch_from_git(commit
)
660 self
.ok
&= CheckOnePatch(commit
, patch
).ok
662 print("Couldn't find commit matching: '{}'".format(rev_spec
))
664 def read_commit_list_from_git(self
, rev_spec
, max_count
):
665 # Run git to get the commit patch
666 cmd
= [ 'rev-list', '--abbrev-commit', '--no-walk' ]
667 if max_count
is not None:
668 cmd
.append('--max-count=' + str(max_count
))
670 out
= self
.run_git(*cmd
)
671 return out
.split() if out
else []
673 def read_patch_from_git(self
, commit
):
674 # Run git to get the commit patch
675 return self
.run_git('show', '--pretty=email', '--no-textconv',
676 '--no-use-mailmap', commit
)
678 def read_committer_email_address_from_git(self
, commit
):
679 # Run git to get the committer email
680 return self
.run_git('show', '--pretty=%cn <%ce>', '--no-patch',
681 '--no-use-mailmap', commit
)
683 def run_git(self
, *args
):
686 p
= subprocess
.Popen(cmd
,
687 stdout
=subprocess
.PIPE
,
688 stderr
=subprocess
.STDOUT
)
689 Result
= p
.communicate()
690 return Result
[0].decode('utf-8', 'ignore') if Result
[0] and Result
[0].find(b
"fatal")!=0 else None
692 class CheckOnePatchFile
:
693 """Performs a patch check for a single file.
695 stdin is used when the filename is '-'.
698 def __init__(self
, patch_filename
):
699 if patch_filename
== '-':
700 patch
= sys
.stdin
.read()
701 patch_filename
= 'stdin'
703 f
= open(patch_filename
, 'rb')
704 patch
= f
.read().decode('utf-8', 'ignore')
706 if Verbose
.level
> Verbose
.ONELINE
:
707 print('Checking patch file:', patch_filename
)
708 self
.ok
= CheckOnePatch(patch_filename
, patch
).ok
711 """Performs a patch check for a single command line argument.
713 The argument will be handed off to a file or git-commit based
717 def __init__(self
, param
, max_count
=None):
719 if param
== '-' or os
.path
.exists(param
):
720 checker
= CheckOnePatchFile(param
)
722 checker
= CheckGitCommits(param
, max_count
)
726 """Checks patches based on the command line arguments."""
730 patches
= self
.args
.patches
732 if len(patches
) == 0:
737 for patch
in patches
:
738 self
.process_one_arg(patch
)
740 if self
.count
is not None:
741 self
.process_one_arg('HEAD')
748 def process_one_arg(self
, arg
):
749 if len(arg
) >= 2 and arg
[0] == '-':
751 self
.count
= int(arg
[1:])
755 self
.ok
&= CheckOneArg(arg
, self
.count
).ok
758 def parse_options(self
):
759 parser
= argparse
.ArgumentParser(description
=__copyright__
)
760 parser
.add_argument('--version', action
='version',
761 version
='%(prog)s ' + VersionNumber
)
762 parser
.add_argument('patches', nargs
='*',
763 help='[patch file | git rev list]')
764 group
= parser
.add_mutually_exclusive_group()
765 group
.add_argument("--oneline",
767 help="Print one result per line")
768 group
.add_argument("--silent",
770 help="Print nothing")
771 self
.args
= parser
.parse_args()
772 if self
.args
.oneline
:
773 Verbose
.level
= Verbose
.ONELINE
775 Verbose
.level
= Verbose
.SILENT
777 if __name__
== "__main__":
778 sys
.exit(PatchCheckApp().retval
)