]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Scripts/PatchCheck.py
2 # Check a patch for various format issues
4 # Copyright (c) 2015 - 2017, Intel Corporation. All rights reserved.<BR>
6 # This program and the accompanying materials are licensed and made
7 # available under the terms and conditions of the BSD License which
8 # accompanies this distribution. The full text of the license may be
9 # found at http://opensource.org/licenses/bsd-license.php
11 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS"
12 # BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
16 from __future__
import print_function
19 __copyright__
= "Copyright (c) 2015 - 2016, Intel Corporation All rights reserved."
29 SILENT
, ONELINE
, NORMAL
= range(3)
32 class CommitMessageCheck
:
33 """Checks the contents of a git commit message."""
35 def __init__(self
, subject
, message
):
38 if subject
is None and message
is None:
39 self
.error('Commit message is missing!')
42 self
.subject
= subject
45 self
.check_contributed_under()
46 self
.check_signed_off_by()
47 self
.check_misc_signatures()
48 self
.check_overall_format()
49 self
.report_message_result()
51 url
= 'https://github.com/tianocore/tianocore.github.io/wiki/Commit-Message-Format'
53 def report_message_result(self
):
54 if Verbose
.level
< Verbose
.NORMAL
:
59 print('The commit message format passed all checks.')
65 def error(self
, *err
):
66 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
67 print('The commit message format is not valid:')
69 if Verbose
.level
< Verbose
.NORMAL
:
73 prefix
= (' *', ' ')[count
> 0]
77 def check_contributed_under(self
):
78 cu_msg
='Contributed-under: TianoCore Contribution Agreement 1.1'
79 if self
.msg
.find(cu_msg
) < 0:
80 # Allow 1.0 for now while EDK II community transitions to 1.1
81 cu_msg
='Contributed-under: TianoCore Contribution Agreement 1.0'
82 if self
.msg
.find(cu_msg
) < 0:
83 self
.error('Missing Contributed-under! (Note: this must be ' +
84 'added by the code contributor!)')
87 def make_signature_re(sig
, re_input
=False):
91 sub_re
= sig
.replace('-', r
'[-\s]+')
92 re_str
= (r
'^(?P<tag>' + sub_re
+
93 r
')(\s*):(\s*)(?P<value>\S.*?)(?:\s*)$')
95 return re
.compile(re_str
, re
.MULTILINE|re
.IGNORECASE
)
97 print("Tried to compile re:", re_str
)
102 (?: (?P<tag>[^:]+) \s* : \s*
105 (?: \[ (?P<updater>[^:]+) \s* : \s*
106 (?P<note>.+?) \s* \] )
108 re
.VERBOSE | re
.MULTILINE
)
110 def find_signatures(self
, sig
):
111 if not sig
.endswith('-by') and sig
!= 'Cc':
113 regex
= self
.make_signature_re(sig
)
115 sigs
= regex
.findall(self
.msg
)
117 bad_case_sigs
= filter(lambda m
: m
[0] != sig
, sigs
)
118 for s
in bad_case_sigs
:
119 self
.error("'" +s
[0] + "' should be '" + sig
+ "'")
123 self
.error('There should be no spaces between ' + sig
+
126 self
.error("There should be a space after '" + sig
+ ":'")
128 self
.check_email_address(s
[3])
132 email_re1
= re
.compile(r
'(?:\s*)(.*?)(\s*)<(.+)>\s*$',
133 re
.MULTILINE|re
.IGNORECASE
)
135 def check_email_address(self
, email
):
136 email
= email
.strip()
137 mo
= self
.email_re1
.match(email
)
139 self
.error("Email format is invalid: " + email
.strip())
142 name
= mo
.group(1).strip()
144 self
.error("Name is not provided with email address: " +
147 quoted
= len(name
) > 2 and name
[0] == '"' and name
[-1] == '"'
148 if name
.find(',') >= 0 and not quoted
:
149 self
.error('Add quotes (") around name with a comma: ' +
152 if mo
.group(2) == '':
153 self
.error("There should be a space between the name and " +
154 "email address: " + email
)
156 if mo
.group(3).find(' ') >= 0:
157 self
.error("The email address cannot contain a space: " +
160 def check_signed_off_by(self
):
162 if self
.msg
.find(sob
) < 0:
163 self
.error('Missing Signed-off-by! (Note: this must be ' +
164 'added by the code contributor!)')
167 sobs
= self
.find_signatures('Signed-off')
170 self
.error('Invalid Signed-off-by format!')
182 def check_misc_signatures(self
):
183 for sig
in self
.sig_types
:
184 self
.find_signatures(sig
)
186 def check_overall_format(self
):
187 lines
= self
.msg
.splitlines()
189 if len(lines
) >= 1 and lines
[0].endswith('\r\n'):
194 lines
.insert(0, empty_line
)
195 lines
.insert(0, self
.subject
+ empty_line
)
200 self
.error('Empty commit message!')
203 if count
>= 1 and len(lines
[0]) >= 72:
204 self
.error('First line of commit message (subject line) ' +
207 if count
>= 1 and len(lines
[0].strip()) == 0:
208 self
.error('First line of commit message (subject line) ' +
211 if count
>= 2 and lines
[1].strip() != '':
212 self
.error('Second line of commit message should be ' +
215 for i
in range(2, count
):
216 if (len(lines
[i
]) >= 76 and
217 len(lines
[i
].split()) > 1 and
218 not lines
[i
].startswith('git-svn-id:')):
219 self
.error('Line %d of commit message is too long.' % (i
+ 1))
222 for i
in range(count
- 1, 0, -1):
224 mo
= self
.sig_block_re
.match(line
)
226 if line
.strip() == '':
228 elif last_sig_line
is not None:
229 err2
= 'Add empty line before "%s"?' % last_sig_line
230 self
.error('The line before the signature block ' +
231 'should be empty', err2
)
233 self
.error('The signature block was not found')
235 last_sig_line
= line
.strip()
237 (START
, PRE_PATCH
, PATCH
) = range(3)
240 """Checks the contents of a git diff."""
242 def __init__(self
, diff
):
244 self
.format_ok
= True
245 self
.lines
= diff
.splitlines(True)
246 self
.count
= len(self
.lines
)
250 while self
.line_num
< self
.count
and self
.format_ok
:
251 line_num
= self
.line_num
253 assert(self
.line_num
> line_num
)
254 self
.report_message_result()
256 def report_message_result(self
):
257 if Verbose
.level
< Verbose
.NORMAL
:
260 print('The code passed all checks.')
262 print('\nWARNING - The following binary files will be added ' +
263 'into the repository:')
264 for binary
in self
.new_bin
:
268 line
= self
.lines
[self
.line_num
]
270 if self
.state
in (PRE_PATCH
, PATCH
):
271 if line
.startswith('diff --git'):
273 if self
.state
== PATCH
:
274 if line
.startswith('@@ '):
275 self
.state
= PRE_PATCH
276 elif len(line
) >= 1 and line
[0] not in ' -+' and \
277 not line
.startswith(r
'\ No newline ') and not self
.binary
:
278 for line
in self
.lines
[self
.line_num
+ 1:]:
279 if line
.startswith('diff --git'):
280 self
.format_error('diff found after end of patch')
282 self
.line_num
= self
.count
285 if self
.state
== START
:
286 if line
.startswith('diff --git'):
287 self
.state
= PRE_PATCH
288 self
.filename
= line
[13:].split(' ',1)[0]
289 self
.is_newfile
= False
290 self
.force_crlf
= not self
.filename
.endswith('.sh')
291 elif len(line
.rstrip()) != 0:
292 self
.format_error("didn't find diff command")
294 elif self
.state
== PRE_PATCH
:
295 if line
.startswith('@@ '):
298 elif line
.startswith('GIT binary patch') or \
299 line
.startswith('Binary files'):
303 self
.new_bin
.append(self
.filename
)
306 self
.is_newfile
= self
.newfile_prefix_re
.match(line
)
307 for pfx
in self
.pre_patch_prefixes
:
308 if line
.startswith(pfx
):
311 self
.format_error("didn't find diff hunk marker (@@)")
313 elif self
.state
== PATCH
:
316 elif line
.startswith('-'):
318 elif line
.startswith('+'):
319 self
.check_added_line(line
[1:])
320 elif line
.startswith(r
'\ No newline '):
322 elif not line
.startswith(' '):
323 self
.format_error("unexpected patch line")
326 pre_patch_prefixes
= (
338 line_endings
= ('\r\n', '\n\r', '\n', '\r')
340 newfile_prefix_re
= \
346 def added_line_error(self
, msg
, line
):
348 if self
.filename
is not None:
349 lines
.append('File: ' + self
.filename
)
350 lines
.append('Line: ' + line
)
356 DEBUG \s* \( \s* \( \s*
357 (?: DEBUG_[A-Z_]+ \s* \| \s*)*
362 def check_added_line(self
, line
):
364 for an_eol
in self
.line_endings
:
365 if line
.endswith(an_eol
):
367 line
= line
[:-len(eol
)]
369 stripped
= line
.rstrip()
371 if self
.force_crlf
and eol
!= '\r\n':
372 self
.added_line_error('Line ending (%s) is not CRLF' % repr(eol
),
375 self
.added_line_error('Tab character used', line
)
376 if len(stripped
) < len(line
):
377 self
.added_line_error('Trailing whitespace found', line
)
379 mo
= self
.old_debug_re
.search(line
)
381 self
.added_line_error('EFI_D_' + mo
.group(1) + ' was used, '
382 'but DEBUG_' + mo
.group(1) +
383 ' is now recommended', line
)
385 split_diff_re
= re
.compile(r
'''
387 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
393 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
395 def format_error(self
, err
):
396 self
.format_ok
= False
397 err
= 'Patch format error: ' + err
398 err2
= 'Line: ' + self
.lines
[self
.line_num
].rstrip()
399 self
.error(err
, err2
)
401 def error(self
, *err
):
402 if self
.ok
and Verbose
.level
> Verbose
.ONELINE
:
403 print('Code format is not valid:')
405 if Verbose
.level
< Verbose
.NORMAL
:
409 prefix
= (' *', ' ')[count
> 0]
414 """Checks the contents of a git email formatted patch.
416 Various checks are performed on both the commit message and the
420 def __init__(self
, name
, patch
):
422 self
.find_patch_pieces()
424 msg_check
= CommitMessageCheck(self
.commit_subject
, self
.commit_msg
)
425 msg_ok
= msg_check
.ok
428 if self
.diff
is not None:
429 diff_check
= GitDiffCheck(self
.diff
)
430 diff_ok
= diff_check
.ok
432 self
.ok
= msg_ok
and diff_ok
434 if Verbose
.level
== Verbose
.ONELINE
:
440 result
.append('commit message')
442 result
.append('diff content')
443 result
= 'bad ' + ' and '.join(result
)
447 git_diff_re
= re
.compile(r
'''
448 ^ diff \s+ --git \s+ a/.+ \s+ b/.+ $
450 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
454 (?P<commit_message> [\s\S\r\n]* )
457 (?: ^ \s+ .+ \s+ \| \s+ \d+ \s+ \+* \-*
462 re
.IGNORECASE | re
.VERBOSE | re
.MULTILINE
)
464 subject_prefix_re
= \
467 [^\[\]]* # Allow all non-brackets
472 def find_patch_pieces(self
):
473 if sys
.version_info
< (3, 0):
474 patch
= self
.patch
.encode('ascii', 'ignore')
478 self
.commit_msg
= None
480 self
.commit_subject
= None
481 self
.commit_prefix
= None
484 if patch
.startswith('diff --git'):
488 pmail
= email
.message_from_string(patch
)
489 parts
= list(pmail
.walk())
490 assert(len(parts
) == 1)
491 assert(parts
[0].get_content_type() == 'text/plain')
492 content
= parts
[0].get_payload(decode
=True).decode('utf-8', 'ignore')
494 mo
= self
.git_diff_re
.search(content
)
496 self
.diff
= content
[mo
.start():]
497 content
= content
[:mo
.start()]
499 mo
= self
.stat_re
.search(content
)
501 self
.commit_msg
= content
503 self
.stat
= mo
.group('stat')
504 self
.commit_msg
= mo
.group('commit_message')
506 self
.commit_subject
= pmail
['subject'].replace('\r\n', '')
507 self
.commit_subject
= self
.commit_subject
.replace('\n', '')
508 self
.commit_subject
= self
.subject_prefix_re
.sub('', self
.commit_subject
, 1)
510 class CheckGitCommits
:
511 """Reads patches from git based on the specified git revision range.
513 The patches are read from git, and then checked.
516 def __init__(self
, rev_spec
, max_count
):
517 commits
= self
.read_commit_list_from_git(rev_spec
, max_count
)
518 if len(commits
) == 1 and Verbose
.level
> Verbose
.ONELINE
:
519 commits
= [ rev_spec
]
522 for commit
in commits
:
523 if Verbose
.level
> Verbose
.ONELINE
:
528 print('Checking git commit:', commit
)
529 patch
= self
.read_patch_from_git(commit
)
530 self
.ok
&= CheckOnePatch(commit
, patch
).ok
532 def read_commit_list_from_git(self
, rev_spec
, max_count
):
533 # Run git to get the commit patch
534 cmd
= [ 'rev-list', '--abbrev-commit', '--no-walk' ]
535 if max_count
is not None:
536 cmd
.append('--max-count=' + str(max_count
))
538 out
= self
.run_git(*cmd
)
541 def read_patch_from_git(self
, commit
):
542 # Run git to get the commit patch
543 return self
.run_git('show', '--pretty=email', commit
)
545 def run_git(self
, *args
):
548 p
= subprocess
.Popen(cmd
,
549 stdout
=subprocess
.PIPE
,
550 stderr
=subprocess
.STDOUT
)
551 return p
.communicate()[0].decode('utf-8', 'ignore')
553 class CheckOnePatchFile
:
554 """Performs a patch check for a single file.
556 stdin is used when the filename is '-'.
559 def __init__(self
, patch_filename
):
560 if patch_filename
== '-':
561 patch
= sys
.stdin
.read()
562 patch_filename
= 'stdin'
564 f
= open(patch_filename
, 'rb')
565 patch
= f
.read().decode('utf-8', 'ignore')
567 if Verbose
.level
> Verbose
.ONELINE
:
568 print('Checking patch file:', patch_filename
)
569 self
.ok
= CheckOnePatch(patch_filename
, patch
).ok
572 """Performs a patch check for a single command line argument.
574 The argument will be handed off to a file or git-commit based
578 def __init__(self
, param
, max_count
=None):
580 if param
== '-' or os
.path
.exists(param
):
581 checker
= CheckOnePatchFile(param
)
583 checker
= CheckGitCommits(param
, max_count
)
587 """Checks patches based on the command line arguments."""
591 patches
= self
.args
.patches
593 if len(patches
) == 0:
598 for patch
in patches
:
599 self
.process_one_arg(patch
)
601 if self
.count
is not None:
602 self
.process_one_arg('HEAD')
609 def process_one_arg(self
, arg
):
610 if len(arg
) >= 2 and arg
[0] == '-':
612 self
.count
= int(arg
[1:])
616 self
.ok
&= CheckOneArg(arg
, self
.count
).ok
619 def parse_options(self
):
620 parser
= argparse
.ArgumentParser(description
=__copyright__
)
621 parser
.add_argument('--version', action
='version',
622 version
='%(prog)s ' + VersionNumber
)
623 parser
.add_argument('patches', nargs
='*',
624 help='[patch file | git rev list]')
625 group
= parser
.add_mutually_exclusive_group()
626 group
.add_argument("--oneline",
628 help="Print one result per line")
629 group
.add_argument("--silent",
631 help="Print nothing")
632 self
.args
= parser
.parse_args()
633 if self
.args
.oneline
:
634 Verbose
.level
= Verbose
.ONELINE
636 Verbose
.level
= Verbose
.SILENT
638 if __name__
== "__main__":
639 sys
.exit(PatchCheckApp().retval
)