]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Scripts/PatchCheck.py
2 # Check a patch for various format issues
4 # Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.<BR>
5 # Copyright (C) 2020, Red Hat, Inc.<BR>
7 # SPDX-License-Identifier: BSD-2-Clause-Patent
10 from __future__
import print_function
13 __copyright__
= "Copyright (c) 2015 - 2016, Intel Corporation All rights reserved."
23 SILENT
, ONELINE
, NORMAL
= range(3)
26 class EmailAddressCheck
:
27 """Checks an email address."""
29 def __init__(self
, email
, description
):
33 self
.error('Email address is missing!')
35 if description
is None:
36 self
.error('Email description is missing!')
39 self
.description
= "'" + description
+ "'"
40 self
.check_email_address(email
)
42 def error(self
, *err
):
43 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
44 print('The ' + self
.description
+ ' email address is not valid:')
46 if Verbose
.level
< Verbose
.NORMAL
:
50 prefix
= (' *', ' ')[count
> 0]
54 email_re1
= re
.compile(r
'(?:\s*)(.*?)(\s*)<(.+)>\s*$',
55 re
.MULTILINE|re
.IGNORECASE
)
57 def check_email_address(self
, email
):
59 mo
= self
.email_re1
.match(email
)
61 self
.error("Email format is invalid: " + email
.strip())
64 name
= mo
.group(1).strip()
66 self
.error("Name is not provided with email address: " +
69 quoted
= len(name
) > 2 and name
[0] == '"' and name
[-1] == '"'
70 if name
.find(',') >= 0 and not quoted
:
71 self
.error('Add quotes (") around name with a comma: ' +
75 self
.error("There should be a space between the name and " +
76 "email address: " + email
)
78 if mo
.group(3).find(' ') >= 0:
79 self
.error("The email address cannot contain a space: " +
82 if ' via Groups.Io' in name
and mo
.group(3).endswith('@groups.io'):
83 self
.error("Email rewritten by lists DMARC / DKIM / SPF: " +
86 class CommitMessageCheck
:
87 """Checks the contents of a git commit message."""
89 def __init__(self
, subject
, message
):
92 if subject
is None and message
is None:
93 self
.error('Commit message is missing!')
96 self
.subject
= subject
101 self
.check_contributed_under()
102 self
.check_signed_off_by()
103 self
.check_misc_signatures()
104 self
.check_overall_format()
105 self
.report_message_result()
107 url
= 'https://github.com/tianocore/tianocore.github.io/wiki/Commit-Message-Format'
109 def report_message_result(self
):
110 if Verbose
.level
< Verbose
.NORMAL
:
115 print('The commit message format passed all checks.')
121 def error(self
, *err
):
122 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
123 print('The commit message format is not valid:')
125 if Verbose
.level
< Verbose
.NORMAL
:
129 prefix
= (' *', ' ')[count
> 0]
133 # Find 'contributed-under:' at the start of a line ignoring case and
134 # requires ':' to be present. Matches if there is white space before
135 # the tag or between the tag and the ':'.
136 contributed_under_re
= \
137 re
.compile(r
'^\s*contributed-under\s*:', re
.MULTILINE|re
.IGNORECASE
)
139 def check_contributed_under(self
):
140 match
= self
.contributed_under_re
.search(self
.msg
)
141 if match
is not None:
142 self
.error('Contributed-under! (Note: this must be ' +
143 'removed by the code contributor!)')
146 def make_signature_re(sig
, re_input
=False):
150 sub_re
= sig
.replace('-', r
'[-\s]+')
151 re_str
= (r
'^(?P<tag>' + sub_re
+
152 r
')(\s*):(\s*)(?P<value>\S.*?)(?:\s*)$')
154 return re
.compile(re_str
, re
.MULTILINE|re
.IGNORECASE
)
156 print("Tried to compile re:", re_str
)
161 (?: (?P<tag>[^:]+) \s* : \s*
164 (?: \[ (?P<updater>[^:]+) \s* : \s*
165 (?P<note>.+?) \s* \] )
167 re
.VERBOSE | re
.MULTILINE
)
169 def find_signatures(self
, sig
):
170 if not sig
.endswith('-by') and sig
!= 'Cc':
172 regex
= self
.make_signature_re(sig
)
174 sigs
= regex
.findall(self
.msg
)
176 bad_case_sigs
= filter(lambda m
: m
[0] != sig
, sigs
)
177 for s
in bad_case_sigs
:
178 self
.error("'" +s
[0] + "' should be '" + sig
+ "'")
182 self
.error('There should be no spaces between ' + sig
+
185 self
.error("There should be a space after '" + sig
+ ":'")
187 EmailAddressCheck(s
[3], sig
)
191 def check_signed_off_by(self
):
193 if self
.msg
.find(sob
) < 0:
194 self
.error('Missing Signed-off-by! (Note: this must be ' +
195 'added by the code contributor!)')
198 sobs
= self
.find_signatures('Signed-off')
201 self
.error('Invalid Signed-off-by format!')
213 def check_misc_signatures(self
):
214 for sig
in self
.sig_types
:
215 self
.find_signatures(sig
)
217 cve_re
= re
.compile('CVE-[0-9]{4}-[0-9]{5}[^0-9]')
219 def check_overall_format(self
):
220 lines
= self
.msg
.splitlines()
222 if len(lines
) >= 1 and lines
[0].endswith('\r\n'):
227 lines
.insert(0, empty_line
)
228 lines
.insert(0, self
.subject
+ empty_line
)
233 self
.error('Empty commit message!')
236 if count
>= 1 and re
.search(self
.cve_re
, lines
[0]):
238 # If CVE-xxxx-xxxxx is present in subject line, then limit length of
239 # subject line to 92 characters
241 if len(lines
[0].rstrip()) >= 93:
243 'First line of commit message (subject line) is too long (%d >= 93).' %
244 (len(lines
[0].rstrip()))
248 # If CVE-xxxx-xxxxx is not present in subject line, then limit
249 # length of subject line to 75 characters
251 if len(lines
[0].rstrip()) >= 76:
253 'First line of commit message (subject line) is too long (%d >= 76).' %
254 (len(lines
[0].rstrip()))
257 if count
>= 1 and len(lines
[0].strip()) == 0:
258 self
.error('First line of commit message (subject line) ' +
261 if count
>= 2 and lines
[1].strip() != '':
262 self
.error('Second line of commit message should be ' +
265 for i
in range(2, count
):
266 if (len(lines
[i
]) >= 76 and
267 len(lines
[i
].split()) > 1 and
268 not lines
[i
].startswith('git-svn-id:')):
270 # Print a warning if body line is longer than 75 characters
273 'WARNING - Line %d of commit message is too long (%d >= 76).' %
274 (i
+ 1, len(lines
[i
]))
279 for i
in range(count
- 1, 0, -1):
281 mo
= self
.sig_block_re
.match(line
)
283 if line
.strip() == '':
285 elif last_sig_line
is not None:
286 err2
= 'Add empty line before "%s"?' % last_sig_line
287 self
.error('The line before the signature block ' +
288 'should be empty', err2
)
290 self
.error('The signature block was not found')
292 last_sig_line
= line
.strip()
294 (START
, PRE_PATCH
, PATCH
) = range(3)
297 """Checks the contents of a git diff."""
299 def __init__(self
, diff
):
301 self
.format_ok
= True
302 self
.lines
= diff
.splitlines(True)
303 self
.count
= len(self
.lines
)
307 while self
.line_num
< self
.count
and self
.format_ok
:
308 line_num
= self
.line_num
310 assert(self
.line_num
> line_num
)
311 self
.report_message_result()
313 def report_message_result(self
):
314 if Verbose
.level
< Verbose
.NORMAL
:
317 print('The code passed all checks.')
319 print('\nWARNING - The following binary files will be added ' +
320 'into the repository:')
321 for binary
in self
.new_bin
:
325 line
= self
.lines
[self
.line_num
]
327 if self
.state
in (PRE_PATCH
, PATCH
):
328 if line
.startswith('diff --git'):
330 if self
.state
== PATCH
:
331 if line
.startswith('@@ '):
332 self
.state
= PRE_PATCH
333 elif len(line
) >= 1 and line
[0] not in ' -+' and \
334 not line
.startswith('\r\n') and \
335 not line
.startswith(r
'\ No newline ') and not self
.binary
:
336 for line
in self
.lines
[self
.line_num
+ 1:]:
337 if line
.startswith('diff --git'):
338 self
.format_error('diff found after end of patch')
340 self
.line_num
= self
.count
343 if self
.state
== START
:
344 if line
.startswith('diff --git'):
345 self
.state
= PRE_PATCH
346 self
.filename
= line
[13:].split(' ', 1)[0]
347 self
.is_newfile
= False
348 self
.force_crlf
= True
349 self
.force_notabs
= True
350 if self
.filename
.endswith('.sh'):
352 # Do not enforce CR/LF line endings for linux shell scripts.
354 self
.force_crlf
= False
355 if self
.filename
== '.gitmodules':
357 # .gitmodules is updated by git and uses tabs and LF line
358 # endings. Do not enforce no tabs and do not enforce
359 # CR/LF line endings.
361 self
.force_crlf
= False
362 self
.force_notabs
= False
363 elif len(line
.rstrip()) != 0:
364 self
.format_error("didn't find diff command")
366 elif self
.state
== PRE_PATCH
:
367 if line
.startswith('@@ '):
370 elif line
.startswith('GIT binary patch') or \
371 line
.startswith('Binary files'):
375 self
.new_bin
.append(self
.filename
)
376 elif line
.startswith('new file mode 160000'):
378 # New submodule. Do not enforce CR/LF line endings
380 self
.force_crlf
= False
383 self
.is_newfile
= self
.newfile_prefix_re
.match(line
)
384 for pfx
in self
.pre_patch_prefixes
:
385 if line
.startswith(pfx
):
388 self
.format_error("didn't find diff hunk marker (@@)")
390 elif self
.state
== PATCH
:
393 elif line
.startswith('-'):
395 elif line
.startswith('+'):
396 self
.check_added_line(line
[1:])
397 elif line
.startswith('\r\n'):
399 elif line
.startswith(r
'\ No newline '):
401 elif not line
.startswith(' '):
402 self
.format_error("unexpected patch line")
405 pre_patch_prefixes
= (
419 line_endings
= ('\r\n', '\n\r', '\n', '\r')
421 newfile_prefix_re
= \
427 def added_line_error(self
, msg
, line
):
429 if self
.filename
is not None:
430 lines
.append('File: ' + self
.filename
)
431 lines
.append('Line: ' + line
)
437 DEBUG \s* \( \s* \( \s*
438 (?: DEBUG_[A-Z_]+ \s* \| \s*)*
443 def check_added_line(self
, line
):
445 for an_eol
in self
.line_endings
:
446 if line
.endswith(an_eol
):
448 line
= line
[:-len(eol
)]
450 stripped
= line
.rstrip()
452 if self
.force_crlf
and eol
!= '\r\n':
453 self
.added_line_error('Line ending (%s) is not CRLF' % repr(eol
),
455 if self
.force_notabs
and '\t' in line
:
456 self
.added_line_error('Tab character used', line
)
457 if len(stripped
) < len(line
):
458 self
.added_line_error('Trailing whitespace found', line
)
460 mo
= self
.old_debug_re
.search(line
)
462 self
.added_line_error('EFI_D_' + mo
.group(1) + ' was used, '
463 'but DEBUG_' + mo
.group(1) +
464 ' is now recommended', line
)
466 split_diff_re
= re
.compile(r
'''
468 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
474 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
476 def format_error(self
, err
):
477 self
.format_ok
= False
478 err
= 'Patch format error: ' + err
479 err2
= 'Line: ' + self
.lines
[self
.line_num
].rstrip()
480 self
.error(err
, err2
)
482 def error(self
, *err
):
483 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
484 print('Code format is not valid:')
486 if Verbose
.level
< Verbose
.NORMAL
:
490 prefix
= (' *', ' ')[count
> 0]
495 """Checks the contents of a git email formatted patch.
497 Various checks are performed on both the commit message and the
501 def __init__(self
, name
, patch
):
503 self
.find_patch_pieces()
505 email_check
= EmailAddressCheck(self
.author_email
, 'Author')
506 email_ok
= email_check
.ok
508 msg_check
= CommitMessageCheck(self
.commit_subject
, self
.commit_msg
)
509 msg_ok
= msg_check
.ok
512 if self
.diff
is not None:
513 diff_check
= GitDiffCheck(self
.diff
)
514 diff_ok
= diff_check
.ok
516 self
.ok
= email_ok
and msg_ok
and diff_ok
518 if Verbose
.level
== Verbose
.ONELINE
:
524 result
.append('commit message')
526 result
.append('diff content')
527 result
= 'bad ' + ' and '.join(result
)
531 git_diff_re
= re
.compile(r
'''
532 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
534 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
538 (?P<commit_message> [\s\S\r\n]* )
541 (?: ^ \s+ .+ \s+ \| \s+ \d+ \s+ \+* \-*
546 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
548 subject_prefix_re
= \
551 [^\[\]]* # Allow all non-brackets
556 def find_patch_pieces(self
):
557 if sys
.version_info
< (3, 0):
558 patch
= self
.patch
.encode('ascii', 'ignore')
562 self
.commit_msg
= None
564 self
.commit_subject
= None
565 self
.commit_prefix
= None
568 if patch
.startswith('diff --git'):
572 pmail
= email
.message_from_string(patch
)
573 parts
= list(pmail
.walk())
574 assert(len(parts
) == 1)
575 assert(parts
[0].get_content_type() == 'text/plain')
576 content
= parts
[0].get_payload(decode
=True).decode('utf-8', 'ignore')
578 mo
= self
.git_diff_re
.search(content
)
580 self
.diff
= content
[mo
.start():]
581 content
= content
[:mo
.start()]
583 mo
= self
.stat_re
.search(content
)
585 self
.commit_msg
= content
587 self
.stat
= mo
.group('stat')
588 self
.commit_msg
= mo
.group('commit_message')
590 # Parse subject line from email header. The subject line may be
591 # composed of multiple parts with different encodings. Decode and
592 # combine all the parts to produce a single string with the contents of
593 # the decoded subject line.
595 parts
= email
.header
.decode_header(pmail
.get('subject'))
597 for (part
, encoding
) in parts
:
599 part
= part
.decode(encoding
)
605 subject
= subject
+ part
607 self
.commit_subject
= subject
.replace('\r\n', '')
608 self
.commit_subject
= self
.commit_subject
.replace('\n', '')
609 self
.commit_subject
= self
.subject_prefix_re
.sub('', self
.commit_subject
, 1)
611 self
.author_email
= pmail
['from']
613 class CheckGitCommits
:
614 """Reads patches from git based on the specified git revision range.
616 The patches are read from git, and then checked.
619 def __init__(self
, rev_spec
, max_count
):
620 commits
= self
.read_commit_list_from_git(rev_spec
, max_count
)
621 if len(commits
) == 1 and Verbose
.level
> Verbose
.ONELINE
:
622 commits
= [ rev_spec
]
625 for commit
in commits
:
626 if Verbose
.level
> Verbose
.ONELINE
:
631 print('Checking git commit:', commit
)
632 email
= self
.read_committer_email_address_from_git(commit
)
633 self
.ok
&= EmailAddressCheck(email
, 'Committer').ok
634 patch
= self
.read_patch_from_git(commit
)
635 self
.ok
&= CheckOnePatch(commit
, patch
).ok
637 print("Couldn't find commit matching: '{}'".format(rev_spec
))
639 def read_commit_list_from_git(self
, rev_spec
, max_count
):
640 # Run git to get the commit patch
641 cmd
= [ 'rev-list', '--abbrev-commit', '--no-walk' ]
642 if max_count
is not None:
643 cmd
.append('--max-count=' + str(max_count
))
645 out
= self
.run_git(*cmd
)
646 return out
.split() if out
else []
648 def read_patch_from_git(self
, commit
):
649 # Run git to get the commit patch
650 return self
.run_git('show', '--pretty=email', '--no-textconv',
651 '--no-use-mailmap', commit
)
653 def read_committer_email_address_from_git(self
, commit
):
654 # Run git to get the committer email
655 return self
.run_git('show', '--pretty=%cn <%ce>', '--no-patch',
656 '--no-use-mailmap', commit
)
658 def run_git(self
, *args
):
661 p
= subprocess
.Popen(cmd
,
662 stdout
=subprocess
.PIPE
,
663 stderr
=subprocess
.STDOUT
)
664 Result
= p
.communicate()
665 return Result
[0].decode('utf-8', 'ignore') if Result
[0] and Result
[0].find(b
"fatal")!=0 else None
667 class CheckOnePatchFile
:
668 """Performs a patch check for a single file.
670 stdin is used when the filename is '-'.
673 def __init__(self
, patch_filename
):
674 if patch_filename
== '-':
675 patch
= sys
.stdin
.read()
676 patch_filename
= 'stdin'
678 f
= open(patch_filename
, 'rb')
679 patch
= f
.read().decode('utf-8', 'ignore')
681 if Verbose
.level
> Verbose
.ONELINE
:
682 print('Checking patch file:', patch_filename
)
683 self
.ok
= CheckOnePatch(patch_filename
, patch
).ok
686 """Performs a patch check for a single command line argument.
688 The argument will be handed off to a file or git-commit based
692 def __init__(self
, param
, max_count
=None):
694 if param
== '-' or os
.path
.exists(param
):
695 checker
= CheckOnePatchFile(param
)
697 checker
= CheckGitCommits(param
, max_count
)
701 """Checks patches based on the command line arguments."""
705 patches
= self
.args
.patches
707 if len(patches
) == 0:
712 for patch
in patches
:
713 self
.process_one_arg(patch
)
715 if self
.count
is not None:
716 self
.process_one_arg('HEAD')
723 def process_one_arg(self
, arg
):
724 if len(arg
) >= 2 and arg
[0] == '-':
726 self
.count
= int(arg
[1:])
730 self
.ok
&= CheckOneArg(arg
, self
.count
).ok
733 def parse_options(self
):
734 parser
= argparse
.ArgumentParser(description
=__copyright__
)
735 parser
.add_argument('--version', action
='version',
736 version
='%(prog)s ' + VersionNumber
)
737 parser
.add_argument('patches', nargs
='*',
738 help='[patch file | git rev list]')
739 group
= parser
.add_mutually_exclusive_group()
740 group
.add_argument("--oneline",
742 help="Print one result per line")
743 group
.add_argument("--silent",
745 help="Print nothing")
746 self
.args
= parser
.parse_args()
747 if self
.args
.oneline
:
748 Verbose
.level
= Verbose
.ONELINE
750 Verbose
.level
= Verbose
.SILENT
752 if __name__
== "__main__":
753 sys
.exit(PatchCheckApp().retval
)