]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Scripts/PatchCheck.py
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\n') and \
274 not line
.startswith(r
'\ No newline ') and not self
.binary
:
275 for line
in self
.lines
[self
.line_num
+ 1:]:
276 if line
.startswith('diff --git'):
277 self
.format_error('diff found after end of patch')
279 self
.line_num
= self
.count
282 if self
.state
== START
:
283 if line
.startswith('diff --git'):
284 self
.state
= PRE_PATCH
285 self
.filename
= line
[13:].split(' ', 1)[0]
286 self
.is_newfile
= False
287 self
.force_crlf
= not self
.filename
.endswith('.sh')
288 elif len(line
.rstrip()) != 0:
289 self
.format_error("didn't find diff command")
291 elif self
.state
== PRE_PATCH
:
292 if line
.startswith('@@ '):
295 elif line
.startswith('GIT binary patch') or \
296 line
.startswith('Binary files'):
300 self
.new_bin
.append(self
.filename
)
303 self
.is_newfile
= self
.newfile_prefix_re
.match(line
)
304 for pfx
in self
.pre_patch_prefixes
:
305 if line
.startswith(pfx
):
308 self
.format_error("didn't find diff hunk marker (@@)")
310 elif self
.state
== PATCH
:
313 elif line
.startswith('-'):
315 elif line
.startswith('+'):
316 self
.check_added_line(line
[1:])
317 elif line
.startswith('\r\n'):
319 elif line
.startswith(r
'\ No newline '):
321 elif not line
.startswith(' '):
322 self
.format_error("unexpected patch line")
325 pre_patch_prefixes
= (
339 line_endings
= ('\r\n', '\n\r', '\n', '\r')
341 newfile_prefix_re
= \
347 def added_line_error(self
, msg
, line
):
349 if self
.filename
is not None:
350 lines
.append('File: ' + self
.filename
)
351 lines
.append('Line: ' + line
)
357 DEBUG \s* \( \s* \( \s*
358 (?: DEBUG_[A-Z_]+ \s* \| \s*)*
363 def check_added_line(self
, line
):
365 for an_eol
in self
.line_endings
:
366 if line
.endswith(an_eol
):
368 line
= line
[:-len(eol
)]
370 stripped
= line
.rstrip()
372 if self
.force_crlf
and eol
!= '\r\n':
373 self
.added_line_error('Line ending (%s) is not CRLF' % repr(eol
),
376 self
.added_line_error('Tab character used', line
)
377 if len(stripped
) < len(line
):
378 self
.added_line_error('Trailing whitespace found', line
)
380 mo
= self
.old_debug_re
.search(line
)
382 self
.added_line_error('EFI_D_' + mo
.group(1) + ' was used, '
383 'but DEBUG_' + mo
.group(1) +
384 ' is now recommended', line
)
386 split_diff_re
= re
.compile(r
'''
388 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
394 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
396 def format_error(self
, err
):
397 self
.format_ok
= False
398 err
= 'Patch format error: ' + err
399 err2
= 'Line: ' + self
.lines
[self
.line_num
].rstrip()
400 self
.error(err
, err2
)
402 def error(self
, *err
):
403 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
404 print('Code format is not valid:')
406 if Verbose
.level
< Verbose
.NORMAL
:
410 prefix
= (' *', ' ')[count
> 0]
415 """Checks the contents of a git email formatted patch.
417 Various checks are performed on both the commit message and the
421 def __init__(self
, name
, patch
):
423 self
.find_patch_pieces()
425 msg_check
= CommitMessageCheck(self
.commit_subject
, self
.commit_msg
)
426 msg_ok
= msg_check
.ok
429 if self
.diff
is not None:
430 diff_check
= GitDiffCheck(self
.diff
)
431 diff_ok
= diff_check
.ok
433 self
.ok
= msg_ok
and diff_ok
435 if Verbose
.level
== Verbose
.ONELINE
:
441 result
.append('commit message')
443 result
.append('diff content')
444 result
= 'bad ' + ' and '.join(result
)
448 git_diff_re
= re
.compile(r
'''
449 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
451 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
455 (?P<commit_message> [\s\S\r\n]* )
458 (?: ^ \s+ .+ \s+ \| \s+ \d+ \s+ \+* \-*
463 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
465 subject_prefix_re
= \
468 [^\[\]]* # Allow all non-brackets
473 def find_patch_pieces(self
):
474 if sys
.version_info
< (3, 0):
475 patch
= self
.patch
.encode('ascii', 'ignore')
479 self
.commit_msg
= None
481 self
.commit_subject
= None
482 self
.commit_prefix
= None
485 if patch
.startswith('diff --git'):
489 pmail
= email
.message_from_string(patch
)
490 parts
= list(pmail
.walk())
491 assert(len(parts
) == 1)
492 assert(parts
[0].get_content_type() == 'text/plain')
493 content
= parts
[0].get_payload(decode
=True).decode('utf-8', 'ignore')
495 mo
= self
.git_diff_re
.search(content
)
497 self
.diff
= content
[mo
.start():]
498 content
= content
[:mo
.start()]
500 mo
= self
.stat_re
.search(content
)
502 self
.commit_msg
= content
504 self
.stat
= mo
.group('stat')
505 self
.commit_msg
= mo
.group('commit_message')
507 self
.commit_subject
= pmail
['subject'].replace('\r\n', '')
508 self
.commit_subject
= self
.commit_subject
.replace('\n', '')
509 self
.commit_subject
= self
.subject_prefix_re
.sub('', self
.commit_subject
, 1)
511 class CheckGitCommits
:
512 """Reads patches from git based on the specified git revision range.
514 The patches are read from git, and then checked.
517 def __init__(self
, rev_spec
, max_count
):
518 commits
= self
.read_commit_list_from_git(rev_spec
, max_count
)
519 if len(commits
) == 1 and Verbose
.level
> Verbose
.ONELINE
:
520 commits
= [ rev_spec
]
523 for commit
in commits
:
524 if Verbose
.level
> Verbose
.ONELINE
:
529 print('Checking git commit:', commit
)
530 patch
= self
.read_patch_from_git(commit
)
531 self
.ok
&= CheckOnePatch(commit
, patch
).ok
533 print("Couldn't find commit matching: '{}'".format(rev_spec
))
535 def read_commit_list_from_git(self
, rev_spec
, max_count
):
536 # Run git to get the commit patch
537 cmd
= [ 'rev-list', '--abbrev-commit', '--no-walk' ]
538 if max_count
is not None:
539 cmd
.append('--max-count=' + str(max_count
))
541 out
= self
.run_git(*cmd
)
542 return out
.split() if out
else []
544 def read_patch_from_git(self
, commit
):
545 # Run git to get the commit patch
546 return self
.run_git('show', '--pretty=email', '--no-textconv', commit
)
548 def run_git(self
, *args
):
551 p
= subprocess
.Popen(cmd
,
552 stdout
=subprocess
.PIPE
,
553 stderr
=subprocess
.STDOUT
)
554 Result
= p
.communicate()
555 return Result
[0].decode('utf-8', 'ignore') if Result
[0] and Result
[0].find(b
"fatal")!=0 else None
557 class CheckOnePatchFile
:
558 """Performs a patch check for a single file.
560 stdin is used when the filename is '-'.
563 def __init__(self
, patch_filename
):
564 if patch_filename
== '-':
565 patch
= sys
.stdin
.read()
566 patch_filename
= 'stdin'
568 f
= open(patch_filename
, 'rb')
569 patch
= f
.read().decode('utf-8', 'ignore')
571 if Verbose
.level
> Verbose
.ONELINE
:
572 print('Checking patch file:', patch_filename
)
573 self
.ok
= CheckOnePatch(patch_filename
, patch
).ok
576 """Performs a patch check for a single command line argument.
578 The argument will be handed off to a file or git-commit based
582 def __init__(self
, param
, max_count
=None):
584 if param
== '-' or os
.path
.exists(param
):
585 checker
= CheckOnePatchFile(param
)
587 checker
= CheckGitCommits(param
, max_count
)
591 """Checks patches based on the command line arguments."""
595 patches
= self
.args
.patches
597 if len(patches
) == 0:
602 for patch
in patches
:
603 self
.process_one_arg(patch
)
605 if self
.count
is not None:
606 self
.process_one_arg('HEAD')
613 def process_one_arg(self
, arg
):
614 if len(arg
) >= 2 and arg
[0] == '-':
616 self
.count
= int(arg
[1:])
620 self
.ok
&= CheckOneArg(arg
, self
.count
).ok
623 def parse_options(self
):
624 parser
= argparse
.ArgumentParser(description
=__copyright__
)
625 parser
.add_argument('--version', action
='version',
626 version
='%(prog)s ' + VersionNumber
)
627 parser
.add_argument('patches', nargs
='*',
628 help='[patch file | git rev list]')
629 group
= parser
.add_mutually_exclusive_group()
630 group
.add_argument("--oneline",
632 help="Print one result per line")
633 group
.add_argument("--silent",
635 help="Print nothing")
636 self
.args
= parser
.parse_args()
637 if self
.args
.oneline
:
638 Verbose
.level
= Verbose
.ONELINE
640 Verbose
.level
= Verbose
.SILENT
642 if __name__
== "__main__":
643 sys
.exit(PatchCheckApp().retval
)