1 # Copyright (c) 2011 The Chromium OS Authors.
3 # SPDX-License-Identifier: GPL-2.0+
17 # True to use --no-decorate - we check this in Setup()
18 use_no_decorate = True
20 def LogCmd(commit_range, git_dir=None, oneline=False, reverse=False,
22 """Create a command to perform a 'git log'
25 commit_range: Range expression to use for log, None for none
26 git_dir: Path to git repositiory (None to use default)
27 oneline: True to use --oneline, else False
28 reverse: True to reverse the log (--reverse)
29 count: Number of commits to list, or None for no limit
31 List containing command and arguments to run
35 cmd += ['--git-dir', git_dir]
36 cmd += ['log', '--no-color']
38 cmd.append('--oneline')
40 cmd.append('--no-decorate')
42 cmd.append('-n%d' % count)
44 cmd.append(commit_range)
47 def CountCommitsToBranch():
48 """Returns number of commits between HEAD and the tracking branch.
50 This looks back to the tracking branch and works out the number of commits
54 Number of patches that exist on top of the branch
56 pipe = [LogCmd('@{upstream}..', oneline=True),
58 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
59 patch_count = int(stdout)
62 def GetUpstream(git_dir, branch):
63 """Returns the name of the upstream for a branch
66 git_dir: Git directory containing repo
67 branch: Name of branch
70 Name of upstream branch (e.g. 'upstream/master') or None if none
73 remote = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
74 'branch.%s.remote' % branch)
75 merge = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
76 'branch.%s.merge' % branch)
82 elif remote and merge:
83 leaf = merge.split('/')[-1]
84 return '%s/%s' % (remote, leaf)
86 raise ValueError, ("Cannot determine upstream branch for branch "
87 "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
90 def GetRangeInBranch(git_dir, branch, include_upstream=False):
91 """Returns an expression for the commits in the given branch.
94 git_dir: Directory containing git repo
95 branch: Name of branch
97 Expression in the form 'upstream..branch' which can be used to
98 access the commits. If the branch does not exist, returns None.
100 upstream = GetUpstream(git_dir, branch)
103 return '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
105 def CountCommitsInBranch(git_dir, branch, include_upstream=False):
106 """Returns the number of commits in the given branch.
109 git_dir: Directory containing git repo
110 branch: Name of branch
112 Number of patches that exist on top of the branch, or None if the
113 branch does not exist.
115 range_expr = GetRangeInBranch(git_dir, branch, include_upstream)
118 pipe = [LogCmd(range_expr, git_dir=git_dir, oneline=True),
120 result = command.RunPipe(pipe, capture=True, oneline=True)
121 patch_count = int(result.stdout)
124 def CountCommits(commit_range):
125 """Returns the number of commits in the given range.
128 commit_range: Range of commits to count (e.g. 'HEAD..base')
130 Number of patches that exist on top of the branch
132 pipe = [LogCmd(commit_range, oneline=True),
134 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
135 patch_count = int(stdout)
138 def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
139 """Checkout the selected commit for this build
142 commit_hash: Commit hash to check out
146 pipe.extend(['--git-dir', git_dir])
148 pipe.extend(['--work-tree', work_tree])
149 pipe.append('checkout')
152 pipe.append(commit_hash)
153 result = command.RunPipe([pipe], capture=True, raise_on_error=False)
154 if result.return_code != 0:
155 raise OSError, 'git checkout (%s): %s' % (pipe, result.stderr)
157 def Clone(git_dir, output_dir):
158 """Checkout the selected commit for this build
161 commit_hash: Commit hash to check out
163 pipe = ['git', 'clone', git_dir, '.']
164 result = command.RunPipe([pipe], capture=True, cwd=output_dir)
165 if result.return_code != 0:
166 raise OSError, 'git clone: %s' % result.stderr
168 def Fetch(git_dir=None, work_tree=None):
169 """Fetch from the origin repo
172 commit_hash: Commit hash to check out
176 pipe.extend(['--git-dir', git_dir])
178 pipe.extend(['--work-tree', work_tree])
180 result = command.RunPipe([pipe], capture=True)
181 if result.return_code != 0:
182 raise OSError, 'git fetch: %s' % result.stderr
184 def CreatePatches(start, count, series):
185 """Create a series of patches from the top of the current branch.
187 The patch files are written to the current directory using
191 start: Commit to start from: 0=HEAD, 1=next one, etc.
192 count: number of commits to include
194 Filename of cover letter
195 List of filenames of patch files
197 if series.get('version'):
198 version = '%s ' % series['version']
199 cmd = ['git', 'format-patch', '-M', '--signoff']
200 if series.get('cover'):
201 cmd.append('--cover-letter')
202 prefix = series.GetPatchPrefix()
204 cmd += ['--subject-prefix=%s' % prefix]
205 cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
207 stdout = command.RunList(cmd)
208 files = stdout.splitlines()
210 # We have an extra file if there is a cover letter
211 if series.get('cover'):
212 return files[0], files[1:]
216 def ApplyPatch(verbose, fname):
217 """Apply a patch with git am to test it
219 TODO: Convert these to use command, with stderr option
222 fname: filename of patch file to apply
224 col = terminal.Color()
225 cmd = ['git', 'am', fname]
226 pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
227 stderr=subprocess.PIPE)
228 stdout, stderr = pipe.communicate()
229 re_error = re.compile('^error: patch failed: (.+):(\d+)')
230 for line in stderr.splitlines():
233 match = re_error.match(line)
235 print checkpatch.GetWarningMsg(col, 'warning', match.group(1),
236 int(match.group(2)), 'Patch failed')
237 return pipe.returncode == 0, stdout
239 def ApplyPatches(verbose, args, start_point):
240 """Apply the patches with git am to make sure all is well
243 verbose: Print out 'git am' output verbatim
244 args: List of patch files to apply
245 start_point: Number of commits back from HEAD to start applying.
246 Normally this is len(args), but it can be larger if a start
250 col = terminal.Color()
252 # Figure out our current position
253 cmd = ['git', 'name-rev', 'HEAD', '--name-only']
254 pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
255 stdout, stderr = pipe.communicate()
257 str = 'Could not find current commit name'
258 print col.Color(col.RED, str)
261 old_head = stdout.splitlines()[0]
262 if old_head == 'undefined':
263 str = "Invalid HEAD '%s'" % stdout.strip()
264 print col.Color(col.RED, str)
267 # Checkout the required start point
268 cmd = ['git', 'checkout', 'HEAD~%d' % start_point]
269 pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
270 stderr=subprocess.PIPE)
271 stdout, stderr = pipe.communicate()
273 str = 'Could not move to commit before patch series'
274 print col.Color(col.RED, str)
278 # Apply all the patches
280 ok, stdout = ApplyPatch(verbose, fname)
282 print col.Color(col.RED, 'git am returned errors for %s: will '
283 'skip this patch' % fname)
287 cmd = ['git', 'am', '--skip']
288 pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
289 stdout, stderr = pipe.communicate()
290 if pipe.returncode != 0:
291 print col.Color(col.RED, 'Unable to skip patch! Aborting...')
295 # Return to our previous position
296 cmd = ['git', 'checkout', old_head]
297 pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
298 stdout, stderr = pipe.communicate()
300 print col.Color(col.RED, 'Could not move back to head commit')
302 return error_count == 0
304 def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
305 """Build a list of email addresses based on an input list.
307 Takes a list of email addresses and aliases, and turns this into a list
308 of only email address, by resolving any aliases that are present.
310 If the tag is given, then each email address is prepended with this
311 tag and a space. If the tag starts with a minus sign (indicating a
312 command line parameter) then the email address is quoted.
315 in_list: List of aliases/email addresses
316 tag: Text to put before each address
317 alias: Alias dictionary
318 raise_on_error: True to raise an error when an alias fails to match,
319 False to just print a message.
322 List of email addresses
325 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
326 >>> alias['john'] = ['j.bloggs@napier.co.nz']
327 >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
328 >>> alias['boys'] = ['fred', ' john']
329 >>> alias['all'] = ['fred ', 'john', ' mary ']
330 >>> BuildEmailList(['john', 'mary'], None, alias)
331 ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
332 >>> BuildEmailList(['john', 'mary'], '--to', alias)
333 ['--to "j.bloggs@napier.co.nz"', \
334 '--to "Mary Poppins <m.poppins@cloud.net>"']
335 >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
336 ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
338 quote = '"' if tag and tag[0] == '-' else ''
341 raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
344 if not item in result:
347 return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
350 def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
351 self_only=False, alias=None, in_reply_to=None):
352 """Email a patch series.
355 series: Series object containing destination info
356 cover_fname: filename of cover letter
357 args: list of filenames of patch files
358 dry_run: Just return the command that would be run
359 raise_on_error: True to raise an error when an alias fails to match,
360 False to just print a message.
361 cc_fname: Filename of Cc file for per-commit Cc
362 self_only: True to just email to yourself as a test
363 in_reply_to: If set we'll pass this to git as --in-reply-to.
364 Should be a message ID that this is in reply to.
367 Git command that was/would be run
369 # For the duration of this doctest pretend that we ran patman with ./patman
370 >>> _old_argv0 = sys.argv[0]
371 >>> sys.argv[0] = './patman'
374 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
375 >>> alias['john'] = ['j.bloggs@napier.co.nz']
376 >>> alias['mary'] = ['m.poppins@cloud.net']
377 >>> alias['boys'] = ['fred', ' john']
378 >>> alias['all'] = ['fred ', 'john', ' mary ']
379 >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
380 >>> series = series.Series()
381 >>> series.to = ['fred']
382 >>> series.cc = ['mary']
383 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
385 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
386 "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
387 >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
389 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
390 "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
391 >>> series.cc = ['all']
392 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
394 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
395 --cc-cmd cc-fname" cover p1 p2'
396 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
398 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
399 "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
400 "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
402 # Restore argv[0] since we clobbered it.
403 >>> sys.argv[0] = _old_argv0
405 to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
407 git_config_to = command.Output('git', 'config', 'sendemail.to')
408 if not git_config_to:
409 print ("No recipient.\n"
410 "Please add something like this to a commit\n"
411 "Series-to: Fred Bloggs <f.blogs@napier.co.nz>\n"
412 "Or do something like this\n"
413 "git config sendemail.to u-boot@lists.denx.de")
415 cc = BuildEmailList(series.get('cc'), '--cc', alias, raise_on_error)
417 to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
419 cmd = ['git', 'send-email', '--annotate']
421 cmd.append('--in-reply-to="%s"' % in_reply_to)
425 cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
427 cmd.append(cover_fname)
435 def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
436 """If an email address is an alias, look it up and return the full name
438 TODO: Why not just use git's own alias feature?
441 lookup_name: Alias or email address to look up
442 alias: Dictionary containing aliases (None to use settings default)
443 raise_on_error: True to raise an error when an alias fails to match,
444 False to just print a message.
448 list containing a list of email addresses
451 OSError if a recursive alias reference was found
452 ValueError if an alias was not found
455 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
456 >>> alias['john'] = ['j.bloggs@napier.co.nz']
457 >>> alias['mary'] = ['m.poppins@cloud.net']
458 >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
459 >>> alias['all'] = ['fred ', 'john', ' mary ']
460 >>> alias['loop'] = ['other', 'john', ' mary ']
461 >>> alias['other'] = ['loop', 'john', ' mary ']
462 >>> LookupEmail('mary', alias)
463 ['m.poppins@cloud.net']
464 >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
465 ['arthur.wellesley@howe.ro.uk']
466 >>> LookupEmail('boys', alias)
467 ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
468 >>> LookupEmail('all', alias)
469 ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
470 >>> LookupEmail('odd', alias)
471 Traceback (most recent call last):
473 ValueError: Alias 'odd' not found
474 >>> LookupEmail('loop', alias)
475 Traceback (most recent call last):
477 OSError: Recursive email alias at 'other'
478 >>> LookupEmail('odd', alias, raise_on_error=False)
479 \033[1;31mAlias 'odd' not found\033[0m
481 >>> # In this case the loop part will effectively be ignored.
482 >>> LookupEmail('loop', alias, raise_on_error=False)
483 \033[1;31mRecursive email alias at 'other'\033[0m
484 \033[1;31mRecursive email alias at 'john'\033[0m
485 \033[1;31mRecursive email alias at 'mary'\033[0m
486 ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
489 alias = settings.alias
490 lookup_name = lookup_name.strip()
491 if '@' in lookup_name: # Perhaps a real email address
494 lookup_name = lookup_name.lower()
495 col = terminal.Color()
499 msg = "Recursive email alias at '%s'" % lookup_name
503 print col.Color(col.RED, msg)
507 if not lookup_name in alias:
508 msg = "Alias '%s' not found" % lookup_name
510 raise ValueError, msg
512 print col.Color(col.RED, msg)
514 for item in alias[lookup_name]:
515 todo = LookupEmail(item, alias, raise_on_error, level + 1)
516 for new_item in todo:
517 if not new_item in out_list:
518 out_list.append(new_item)
520 #print "No match for alias '%s'" % lookup_name
524 """Return name of top-level directory for this git repo.
527 Full path to git top-level directory
529 This test makes sure that we are running tests in the right subdir
531 >>> os.path.realpath(os.path.dirname(__file__)) == \
532 os.path.join(GetTopLevel(), 'tools', 'patman')
535 return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
538 """Gets the name of the git alias file.
541 Filename of git alias file, or None if none
543 fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
544 raise_on_error=False)
546 fname = os.path.join(GetTopLevel(), fname.strip())
549 def GetDefaultUserName():
550 """Gets the user.name from .gitconfig file.
553 User name found in .gitconfig file, or None if none
555 uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
558 def GetDefaultUserEmail():
559 """Gets the user.email from the global .gitconfig file.
562 User's email found in .gitconfig file, or None if none
564 uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
568 """Set up git utils, by reading the alias files."""
569 # Check for a git alias file also
570 alias_fname = GetAliasFile()
572 settings.ReadGitAliases(alias_fname)
573 cmd = LogCmd(None, count=0)
574 use_no_decorate = (command.RunPipe([cmd], raise_on_error=False)
578 """Get the hash of the current HEAD
583 return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
585 if __name__ == "__main__":