]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Scripts/PatchCheck.py
2 # Check a patch for various format issues
4 # Copyright (c) 2015 - 2018, 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 def check_contributed_under(self
):
71 cu_msg
='Contributed-under: TianoCore Contribution Agreement 1.1'
72 if self
.msg
.find(cu_msg
) < 0:
73 # Allow 1.0 for now while EDK II community transitions to 1.1
74 cu_msg
='Contributed-under: TianoCore Contribution Agreement 1.0'
75 if self
.msg
.find(cu_msg
) < 0:
76 self
.error('Missing Contributed-under! (Note: this must be ' +
77 'added by the code contributor!)')
80 def make_signature_re(sig
, re_input
=False):
84 sub_re
= sig
.replace('-', r
'[-\s]+')
85 re_str
= (r
'^(?P<tag>' + sub_re
+
86 r
')(\s*):(\s*)(?P<value>\S.*?)(?:\s*)$')
88 return re
.compile(re_str
, re
.MULTILINE|re
.IGNORECASE
)
90 print("Tried to compile re:", re_str
)
95 (?: (?P<tag>[^:]+) \s* : \s*
98 (?: \[ (?P<updater>[^:]+) \s* : \s*
99 (?P<note>.+?) \s* \] )
101 re
.VERBOSE | re
.MULTILINE
)
103 def find_signatures(self
, sig
):
104 if not sig
.endswith('-by') and sig
!= 'Cc':
106 regex
= self
.make_signature_re(sig
)
108 sigs
= regex
.findall(self
.msg
)
110 bad_case_sigs
= filter(lambda m
: m
[0] != sig
, sigs
)
111 for s
in bad_case_sigs
:
112 self
.error("'" +s
[0] + "' should be '" + sig
+ "'")
116 self
.error('There should be no spaces between ' + sig
+
119 self
.error("There should be a space after '" + sig
+ ":'")
121 self
.check_email_address(s
[3])
125 email_re1
= re
.compile(r
'(?:\s*)(.*?)(\s*)<(.+)>\s*$',
126 re
.MULTILINE|re
.IGNORECASE
)
128 def check_email_address(self
, email
):
129 email
= email
.strip()
130 mo
= self
.email_re1
.match(email
)
132 self
.error("Email format is invalid: " + email
.strip())
135 name
= mo
.group(1).strip()
137 self
.error("Name is not provided with email address: " +
140 quoted
= len(name
) > 2 and name
[0] == '"' and name
[-1] == '"'
141 if name
.find(',') >= 0 and not quoted
:
142 self
.error('Add quotes (") around name with a comma: ' +
145 if mo
.group(2) == '':
146 self
.error("There should be a space between the name and " +
147 "email address: " + email
)
149 if mo
.group(3).find(' ') >= 0:
150 self
.error("The email address cannot contain a space: " +
153 def check_signed_off_by(self
):
155 if self
.msg
.find(sob
) < 0:
156 self
.error('Missing Signed-off-by! (Note: this must be ' +
157 'added by the code contributor!)')
160 sobs
= self
.find_signatures('Signed-off')
163 self
.error('Invalid Signed-off-by format!')
175 def check_misc_signatures(self
):
176 for sig
in self
.sig_types
:
177 self
.find_signatures(sig
)
179 def check_overall_format(self
):
180 lines
= self
.msg
.splitlines()
182 if len(lines
) >= 1 and lines
[0].endswith('\r\n'):
187 lines
.insert(0, empty_line
)
188 lines
.insert(0, self
.subject
+ empty_line
)
193 self
.error('Empty commit message!')
196 if count
>= 1 and len(lines
[0]) >= 72:
197 self
.error('First line of commit message (subject line) ' +
200 if count
>= 1 and len(lines
[0].strip()) == 0:
201 self
.error('First line of commit message (subject line) ' +
204 if count
>= 2 and lines
[1].strip() != '':
205 self
.error('Second line of commit message should be ' +
208 for i
in range(2, count
):
209 if (len(lines
[i
]) >= 76 and
210 len(lines
[i
].split()) > 1 and
211 not lines
[i
].startswith('git-svn-id:')):
212 self
.error('Line %d of commit message is too long.' % (i
+ 1))
215 for i
in range(count
- 1, 0, -1):
217 mo
= self
.sig_block_re
.match(line
)
219 if line
.strip() == '':
221 elif last_sig_line
is not None:
222 err2
= 'Add empty line before "%s"?' % last_sig_line
223 self
.error('The line before the signature block ' +
224 'should be empty', err2
)
226 self
.error('The signature block was not found')
228 last_sig_line
= line
.strip()
230 (START
, PRE_PATCH
, PATCH
) = range(3)
233 """Checks the contents of a git diff."""
235 def __init__(self
, diff
):
237 self
.format_ok
= True
238 self
.lines
= diff
.splitlines(True)
239 self
.count
= len(self
.lines
)
243 while self
.line_num
< self
.count
and self
.format_ok
:
244 line_num
= self
.line_num
246 assert(self
.line_num
> line_num
)
247 self
.report_message_result()
249 def report_message_result(self
):
250 if Verbose
.level
< Verbose
.NORMAL
:
253 print('The code passed all checks.')
255 print('\nWARNING - The following binary files will be added ' +
256 'into the repository:')
257 for binary
in self
.new_bin
:
261 line
= self
.lines
[self
.line_num
]
263 if self
.state
in (PRE_PATCH
, PATCH
):
264 if line
.startswith('diff --git'):
266 if self
.state
== PATCH
:
267 if line
.startswith('@@ '):
268 self
.state
= PRE_PATCH
269 elif len(line
) >= 1 and line
[0] not in ' -+' and \
270 not line
.startswith(r
'\ No newline ') and not self
.binary
:
271 for line
in self
.lines
[self
.line_num
+ 1:]:
272 if line
.startswith('diff --git'):
273 self
.format_error('diff found after end of patch')
275 self
.line_num
= self
.count
278 if self
.state
== START
:
279 if line
.startswith('diff --git'):
280 self
.state
= PRE_PATCH
281 self
.filename
= line
[13:].split(' ', 1)[0]
282 self
.is_newfile
= False
283 self
.force_crlf
= not self
.filename
.endswith('.sh')
284 elif len(line
.rstrip()) != 0:
285 self
.format_error("didn't find diff command")
287 elif self
.state
== PRE_PATCH
:
288 if line
.startswith('@@ '):
291 elif line
.startswith('GIT binary patch') or \
292 line
.startswith('Binary files'):
296 self
.new_bin
.append(self
.filename
)
299 self
.is_newfile
= self
.newfile_prefix_re
.match(line
)
300 for pfx
in self
.pre_patch_prefixes
:
301 if line
.startswith(pfx
):
304 self
.format_error("didn't find diff hunk marker (@@)")
306 elif self
.state
== PATCH
:
309 elif line
.startswith('-'):
311 elif line
.startswith('+'):
312 self
.check_added_line(line
[1:])
313 elif line
.startswith(r
'\ No newline '):
315 elif not line
.startswith(' '):
316 self
.format_error("unexpected patch line")
319 pre_patch_prefixes
= (
331 line_endings
= ('\r\n', '\n\r', '\n', '\r')
333 newfile_prefix_re
= \
339 def added_line_error(self
, msg
, line
):
341 if self
.filename
is not None:
342 lines
.append('File: ' + self
.filename
)
343 lines
.append('Line: ' + line
)
349 DEBUG \s* \( \s* \( \s*
350 (?: DEBUG_[A-Z_]+ \s* \| \s*)*
355 def check_added_line(self
, line
):
357 for an_eol
in self
.line_endings
:
358 if line
.endswith(an_eol
):
360 line
= line
[:-len(eol
)]
362 stripped
= line
.rstrip()
364 if self
.force_crlf
and eol
!= '\r\n':
365 self
.added_line_error('Line ending (%s) is not CRLF' % repr(eol
),
368 self
.added_line_error('Tab character used', line
)
369 if len(stripped
) < len(line
):
370 self
.added_line_error('Trailing whitespace found', line
)
372 mo
= self
.old_debug_re
.search(line
)
374 self
.added_line_error('EFI_D_' + mo
.group(1) + ' was used, '
375 'but DEBUG_' + mo
.group(1) +
376 ' is now recommended', line
)
378 split_diff_re
= re
.compile(r
'''
380 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
386 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
388 def format_error(self
, err
):
389 self
.format_ok
= False
390 err
= 'Patch format error: ' + err
391 err2
= 'Line: ' + self
.lines
[self
.line_num
].rstrip()
392 self
.error(err
, err2
)
394 def error(self
, *err
):
395 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
396 print('Code format is not valid:')
398 if Verbose
.level
< Verbose
.NORMAL
:
402 prefix
= (' *', ' ')[count
> 0]
407 """Checks the contents of a git email formatted patch.
409 Various checks are performed on both the commit message and the
413 def __init__(self
, name
, patch
):
415 self
.find_patch_pieces()
417 msg_check
= CommitMessageCheck(self
.commit_subject
, self
.commit_msg
)
418 msg_ok
= msg_check
.ok
421 if self
.diff
is not None:
422 diff_check
= GitDiffCheck(self
.diff
)
423 diff_ok
= diff_check
.ok
425 self
.ok
= msg_ok
and diff_ok
427 if Verbose
.level
== Verbose
.ONELINE
:
433 result
.append('commit message')
435 result
.append('diff content')
436 result
= 'bad ' + ' and '.join(result
)
440 git_diff_re
= re
.compile(r
'''
441 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
443 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
447 (?P<commit_message> [\s\S\r\n]* )
450 (?: ^ \s+ .+ \s+ \| \s+ \d+ \s+ \+* \-*
455 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
457 subject_prefix_re
= \
460 [^\[\]]* # Allow all non-brackets
465 def find_patch_pieces(self
):
466 if sys
.version_info
< (3, 0):
467 patch
= self
.patch
.encode('ascii', 'ignore')
471 self
.commit_msg
= None
473 self
.commit_subject
= None
474 self
.commit_prefix
= None
477 if patch
.startswith('diff --git'):
481 pmail
= email
.message_from_string(patch
)
482 parts
= list(pmail
.walk())
483 assert(len(parts
) == 1)
484 assert(parts
[0].get_content_type() == 'text/plain')
485 content
= parts
[0].get_payload(decode
=True).decode('utf-8', 'ignore')
487 mo
= self
.git_diff_re
.search(content
)
489 self
.diff
= content
[mo
.start():]
490 content
= content
[:mo
.start()]
492 mo
= self
.stat_re
.search(content
)
494 self
.commit_msg
= content
496 self
.stat
= mo
.group('stat')
497 self
.commit_msg
= mo
.group('commit_message')
499 self
.commit_subject
= pmail
['subject'].replace('\r\n', '')
500 self
.commit_subject
= self
.commit_subject
.replace('\n', '')
501 self
.commit_subject
= self
.subject_prefix_re
.sub('', self
.commit_subject
, 1)
503 class CheckGitCommits
:
504 """Reads patches from git based on the specified git revision range.
506 The patches are read from git, and then checked.
509 def __init__(self
, rev_spec
, max_count
):
510 commits
= self
.read_commit_list_from_git(rev_spec
, max_count
)
511 if len(commits
) == 1 and Verbose
.level
> Verbose
.ONELINE
:
512 commits
= [ rev_spec
]
515 for commit
in commits
:
516 if Verbose
.level
> Verbose
.ONELINE
:
521 print('Checking git commit:', commit
)
522 patch
= self
.read_patch_from_git(commit
)
523 self
.ok
&= CheckOnePatch(commit
, patch
).ok
525 print("Couldn't find commit matching: '{}'".format(rev_spec
))
527 def read_commit_list_from_git(self
, rev_spec
, max_count
):
528 # Run git to get the commit patch
529 cmd
= [ 'rev-list', '--abbrev-commit', '--no-walk' ]
530 if max_count
is not None:
531 cmd
.append('--max-count=' + str(max_count
))
533 out
= self
.run_git(*cmd
)
534 return out
.split() if out
else []
536 def read_patch_from_git(self
, commit
):
537 # Run git to get the commit patch
538 return self
.run_git('show', '--pretty=email', commit
)
540 def run_git(self
, *args
):
543 p
= subprocess
.Popen(cmd
,
544 stdout
=subprocess
.PIPE
,
545 stderr
=subprocess
.STDOUT
)
546 Result
= p
.communicate()
547 return Result
[0].decode('utf-8', 'ignore') if Result
[0] and Result
[0].find(b
"fatal")!=0 else None
549 class CheckOnePatchFile
:
550 """Performs a patch check for a single file.
552 stdin is used when the filename is '-'.
555 def __init__(self
, patch_filename
):
556 if patch_filename
== '-':
557 patch
= sys
.stdin
.read()
558 patch_filename
= 'stdin'
560 f
= open(patch_filename
, 'rb')
561 patch
= f
.read().decode('utf-8', 'ignore')
563 if Verbose
.level
> Verbose
.ONELINE
:
564 print('Checking patch file:', patch_filename
)
565 self
.ok
= CheckOnePatch(patch_filename
, patch
).ok
568 """Performs a patch check for a single command line argument.
570 The argument will be handed off to a file or git-commit based
574 def __init__(self
, param
, max_count
=None):
576 if param
== '-' or os
.path
.exists(param
):
577 checker
= CheckOnePatchFile(param
)
579 checker
= CheckGitCommits(param
, max_count
)
583 """Checks patches based on the command line arguments."""
587 patches
= self
.args
.patches
589 if len(patches
) == 0:
594 for patch
in patches
:
595 self
.process_one_arg(patch
)
597 if self
.count
is not None:
598 self
.process_one_arg('HEAD')
605 def process_one_arg(self
, arg
):
606 if len(arg
) >= 2 and arg
[0] == '-':
608 self
.count
= int(arg
[1:])
612 self
.ok
&= CheckOneArg(arg
, self
.count
).ok
615 def parse_options(self
):
616 parser
= argparse
.ArgumentParser(description
=__copyright__
)
617 parser
.add_argument('--version', action
='version',
618 version
='%(prog)s ' + VersionNumber
)
619 parser
.add_argument('patches', nargs
='*',
620 help='[patch file | git rev list]')
621 group
= parser
.add_mutually_exclusive_group()
622 group
.add_argument("--oneline",
624 help="Print one result per line")
625 group
.add_argument("--silent",
627 help="Print nothing")
628 self
.args
= parser
.parse_args()
629 if self
.args
.oneline
:
630 Verbose
.level
= Verbose
.ONELINE
632 Verbose
.level
= Verbose
.SILENT
634 if __name__
== "__main__":
635 sys
.exit(PatchCheckApp().retval
)