1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2011 The Chromium OS Authors.
10 from patman import command
11 from patman import settings
12 from patman import terminal
13 from patman import tools
15 # True to use --no-decorate - we check this in Setup()
16 use_no_decorate = True
18 def LogCmd(commit_range, git_dir=None, oneline=False, reverse=False,
20 """Create a command to perform a 'git log'
23 commit_range: Range expression to use for log, None for none
24 git_dir: Path to git repository (None to use default)
25 oneline: True to use --oneline, else False
26 reverse: True to reverse the log (--reverse)
27 count: Number of commits to list, or None for no limit
29 List containing command and arguments to run
33 cmd += ['--git-dir', git_dir]
34 cmd += ['--no-pager', 'log', '--no-color']
36 cmd.append('--oneline')
38 cmd.append('--no-decorate')
40 cmd.append('--reverse')
42 cmd.append('-n%d' % count)
44 cmd.append(commit_range)
46 # Add this in case we have a branch with the same name as a directory.
47 # This avoids messages like this, for example:
48 # fatal: ambiguous argument 'test': both revision and filename
52 def CountCommitsToBranch():
53 """Returns number of commits between HEAD and the tracking branch.
55 This looks back to the tracking branch and works out the number of commits
59 Number of patches that exist on top of the branch
61 pipe = [LogCmd('@{upstream}..', oneline=True),
63 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
64 patch_count = int(stdout)
67 def NameRevision(commit_hash):
68 """Gets the revision name for a commit
71 commit_hash: Commit hash to look up
74 Name of revision, if any, else None
76 pipe = ['git', 'name-rev', commit_hash]
77 stdout = command.RunPipe([pipe], capture=True, oneline=True).stdout
79 # We expect a commit, a space, then a revision name
80 name = stdout.split(' ')[1].strip()
83 def GuessUpstream(git_dir, branch):
84 """Tries to guess the upstream for a branch
86 This lists out top commits on a branch and tries to find a suitable
87 upstream. It does this by looking for the first commit where
88 'git name-rev' returns a plain branch name, with no ! or ^ modifiers.
91 git_dir: Git directory containing repo
92 branch: Name of branch
96 Name of upstream branch (e.g. 'upstream/master') or None if none
97 Warning/error message, or None if none
99 pipe = [LogCmd(branch, git_dir=git_dir, oneline=True, count=100)]
100 result = command.RunPipe(pipe, capture=True, capture_stderr=True,
101 raise_on_error=False)
102 if result.return_code:
103 return None, "Branch '%s' not found" % branch
104 for line in result.stdout.splitlines()[1:]:
105 commit_hash = line.split(' ')[0]
106 name = NameRevision(commit_hash)
107 if '~' not in name and '^' not in name:
108 if name.startswith('remotes/'):
110 return name, "Guessing upstream as '%s'" % name
111 return None, "Cannot find a suitable upstream for branch '%s'" % branch
113 def GetUpstream(git_dir, branch):
114 """Returns the name of the upstream for a branch
117 git_dir: Git directory containing repo
118 branch: Name of branch
122 Name of upstream branch (e.g. 'upstream/master') or None if none
123 Warning/error message, or None if none
126 remote = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
127 'branch.%s.remote' % branch)
128 merge = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
129 'branch.%s.merge' % branch)
131 upstream, msg = GuessUpstream(git_dir, branch)
136 elif remote and merge:
137 leaf = merge.split('/')[-1]
138 return '%s/%s' % (remote, leaf), None
140 raise ValueError("Cannot determine upstream branch for branch "
141 "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
144 def GetRangeInBranch(git_dir, branch, include_upstream=False):
145 """Returns an expression for the commits in the given branch.
148 git_dir: Directory containing git repo
149 branch: Name of branch
151 Expression in the form 'upstream..branch' which can be used to
152 access the commits. If the branch does not exist, returns None.
154 upstream, msg = GetUpstream(git_dir, branch)
157 rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
160 def CountCommitsInRange(git_dir, range_expr):
161 """Returns the number of commits in the given range.
164 git_dir: Directory containing git repo
165 range_expr: Range to check
167 Number of patches that exist in the supplied range or None if none
170 pipe = [LogCmd(range_expr, git_dir=git_dir, oneline=True)]
171 result = command.RunPipe(pipe, capture=True, capture_stderr=True,
172 raise_on_error=False)
173 if result.return_code:
174 return None, "Range '%s' not found or is invalid" % range_expr
175 patch_count = len(result.stdout.splitlines())
176 return patch_count, None
178 def CountCommitsInBranch(git_dir, branch, include_upstream=False):
179 """Returns the number of commits in the given branch.
182 git_dir: Directory containing git repo
183 branch: Name of branch
185 Number of patches that exist on top of the branch, or None if the
186 branch does not exist.
188 range_expr, msg = GetRangeInBranch(git_dir, branch, include_upstream)
191 return CountCommitsInRange(git_dir, range_expr)
193 def CountCommits(commit_range):
194 """Returns the number of commits in the given range.
197 commit_range: Range of commits to count (e.g. 'HEAD..base')
199 Number of patches that exist on top of the branch
201 pipe = [LogCmd(commit_range, oneline=True),
203 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
204 patch_count = int(stdout)
207 def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
208 """Checkout the selected commit for this build
211 commit_hash: Commit hash to check out
215 pipe.extend(['--git-dir', git_dir])
217 pipe.extend(['--work-tree', work_tree])
218 pipe.append('checkout')
221 pipe.append(commit_hash)
222 result = command.RunPipe([pipe], capture=True, raise_on_error=False,
224 if result.return_code != 0:
225 raise OSError('git checkout (%s): %s' % (pipe, result.stderr))
227 def Clone(git_dir, output_dir):
228 """Checkout the selected commit for this build
231 commit_hash: Commit hash to check out
233 pipe = ['git', 'clone', git_dir, '.']
234 result = command.RunPipe([pipe], capture=True, cwd=output_dir,
236 if result.return_code != 0:
237 raise OSError('git clone: %s' % result.stderr)
239 def Fetch(git_dir=None, work_tree=None):
240 """Fetch from the origin repo
243 commit_hash: Commit hash to check out
247 pipe.extend(['--git-dir', git_dir])
249 pipe.extend(['--work-tree', work_tree])
251 result = command.RunPipe([pipe], capture=True, capture_stderr=True)
252 if result.return_code != 0:
253 raise OSError('git fetch: %s' % result.stderr)
255 def CreatePatches(start, count, ignore_binary, series):
256 """Create a series of patches from the top of the current branch.
258 The patch files are written to the current directory using
262 start: Commit to start from: 0=HEAD, 1=next one, etc.
263 count: number of commits to include
264 ignore_binary: Don't generate patches for binary files
265 series: Series object for this series (set of patches)
267 Filename of cover letter (None if none)
268 List of filenames of patch files
270 if series.get('version'):
271 version = '%s ' % series['version']
272 cmd = ['git', 'format-patch', '-M', '--signoff']
274 cmd.append('--no-binary')
275 if series.get('cover'):
276 cmd.append('--cover-letter')
277 prefix = series.GetPatchPrefix()
279 cmd += ['--subject-prefix=%s' % prefix]
280 cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
282 stdout = command.RunList(cmd)
283 files = stdout.splitlines()
285 # We have an extra file if there is a cover letter
286 if series.get('cover'):
287 return files[0], files[1:]
291 def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
292 """Build a list of email addresses based on an input list.
294 Takes a list of email addresses and aliases, and turns this into a list
295 of only email address, by resolving any aliases that are present.
297 If the tag is given, then each email address is prepended with this
298 tag and a space. If the tag starts with a minus sign (indicating a
299 command line parameter) then the email address is quoted.
302 in_list: List of aliases/email addresses
303 tag: Text to put before each address
304 alias: Alias dictionary
305 raise_on_error: True to raise an error when an alias fails to match,
306 False to just print a message.
309 List of email addresses
312 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
313 >>> alias['john'] = ['j.bloggs@napier.co.nz']
314 >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
315 >>> alias['boys'] = ['fred', ' john']
316 >>> alias['all'] = ['fred ', 'john', ' mary ']
317 >>> BuildEmailList(['john', 'mary'], None, alias)
318 ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
319 >>> BuildEmailList(['john', 'mary'], '--to', alias)
320 ['--to "j.bloggs@napier.co.nz"', \
321 '--to "Mary Poppins <m.poppins@cloud.net>"']
322 >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
323 ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
325 quote = '"' if tag and tag[0] == '-' else ''
328 raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
331 item = tools.FromUnicode(item)
332 if not item in result:
335 return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
338 def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
339 self_only=False, alias=None, in_reply_to=None, thread=False,
341 """Email a patch series.
344 series: Series object containing destination info
345 cover_fname: filename of cover letter
346 args: list of filenames of patch files
347 dry_run: Just return the command that would be run
348 raise_on_error: True to raise an error when an alias fails to match,
349 False to just print a message.
350 cc_fname: Filename of Cc file for per-commit Cc
351 self_only: True to just email to yourself as a test
352 in_reply_to: If set we'll pass this to git as --in-reply-to.
353 Should be a message ID that this is in reply to.
354 thread: True to add --thread to git send-email (make
355 all patches reply to cover-letter or first patch in series)
356 smtp_server: SMTP server to use to send patches
359 Git command that was/would be run
361 # For the duration of this doctest pretend that we ran patman with ./patman
362 >>> _old_argv0 = sys.argv[0]
363 >>> sys.argv[0] = './patman'
366 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
367 >>> alias['john'] = ['j.bloggs@napier.co.nz']
368 >>> alias['mary'] = ['m.poppins@cloud.net']
369 >>> alias['boys'] = ['fred', ' john']
370 >>> alias['all'] = ['fred ', 'john', ' mary ']
371 >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
373 >>> series['to'] = ['fred']
374 >>> series['cc'] = ['mary']
375 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
377 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
378 "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
379 >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
381 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
382 "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
383 >>> series['cc'] = ['all']
384 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
386 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
387 --cc-cmd cc-fname" cover p1 p2'
388 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
390 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
391 "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
392 "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
394 # Restore argv[0] since we clobbered it.
395 >>> sys.argv[0] = _old_argv0
397 to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
399 git_config_to = command.Output('git', 'config', 'sendemail.to',
400 raise_on_error=False)
401 if not git_config_to:
402 print("No recipient.\n"
403 "Please add something like this to a commit\n"
404 "Series-to: Fred Bloggs <f.blogs@napier.co.nz>\n"
405 "Or do something like this\n"
406 "git config sendemail.to u-boot@lists.denx.de")
408 cc = BuildEmailList(list(set(series.get('cc')) - set(series.get('to'))),
409 '--cc', alias, raise_on_error)
411 to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
413 cmd = ['git', 'send-email', '--annotate']
415 cmd.append('--smtp-server=%s' % smtp_server)
417 cmd.append('--in-reply-to="%s"' % tools.FromUnicode(in_reply_to))
419 cmd.append('--thread')
423 cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
425 cmd.append(cover_fname)
427 cmdstr = ' '.join(cmd)
433 def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
434 """If an email address is an alias, look it up and return the full name
436 TODO: Why not just use git's own alias feature?
439 lookup_name: Alias or email address to look up
440 alias: Dictionary containing aliases (None to use settings default)
441 raise_on_error: True to raise an error when an alias fails to match,
442 False to just print a message.
446 list containing a list of email addresses
449 OSError if a recursive alias reference was found
450 ValueError if an alias was not found
453 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
454 >>> alias['john'] = ['j.bloggs@napier.co.nz']
455 >>> alias['mary'] = ['m.poppins@cloud.net']
456 >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
457 >>> alias['all'] = ['fred ', 'john', ' mary ']
458 >>> alias['loop'] = ['other', 'john', ' mary ']
459 >>> alias['other'] = ['loop', 'john', ' mary ']
460 >>> LookupEmail('mary', alias)
461 ['m.poppins@cloud.net']
462 >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
463 ['arthur.wellesley@howe.ro.uk']
464 >>> LookupEmail('boys', alias)
465 ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
466 >>> LookupEmail('all', alias)
467 ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
468 >>> LookupEmail('odd', alias)
469 Traceback (most recent call last):
471 ValueError: Alias 'odd' not found
472 >>> LookupEmail('loop', alias)
473 Traceback (most recent call last):
475 OSError: Recursive email alias at 'other'
476 >>> LookupEmail('odd', alias, raise_on_error=False)
477 Alias 'odd' not found
479 >>> # In this case the loop part will effectively be ignored.
480 >>> LookupEmail('loop', alias, raise_on_error=False)
481 Recursive email alias at 'other'
482 Recursive email alias at 'john'
483 Recursive email alias at 'mary'
484 ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
487 alias = settings.alias
488 lookup_name = lookup_name.strip()
489 if '@' in lookup_name: # Perhaps a real email address
492 lookup_name = lookup_name.lower()
493 col = terminal.Color()
497 msg = "Recursive email alias at '%s'" % lookup_name
501 print(col.Color(col.RED, msg))
505 if not lookup_name in alias:
506 msg = "Alias '%s' not found" % lookup_name
508 raise ValueError(msg)
510 print(col.Color(col.RED, msg))
512 for item in alias[lookup_name]:
513 todo = LookupEmail(item, alias, raise_on_error, level + 1)
514 for new_item in todo:
515 if not new_item in out_list:
516 out_list.append(new_item)
518 #print("No match for alias '%s'" % lookup_name)
522 """Return name of top-level directory for this git repo.
525 Full path to git top-level directory
527 This test makes sure that we are running tests in the right subdir
529 >>> os.path.realpath(os.path.dirname(__file__)) == \
530 os.path.join(GetTopLevel(), 'tools', 'patman')
533 return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
536 """Gets the name of the git alias file.
539 Filename of git alias file, or None if none
541 fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
542 raise_on_error=False)
544 fname = os.path.join(GetTopLevel(), fname.strip())
547 def GetDefaultUserName():
548 """Gets the user.name from .gitconfig file.
551 User name found in .gitconfig file, or None if none
553 uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
556 def GetDefaultUserEmail():
557 """Gets the user.email from the global .gitconfig file.
560 User's email found in .gitconfig file, or None if none
562 uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
565 def GetDefaultSubjectPrefix():
566 """Gets the format.subjectprefix from local .git/config file.
569 Subject prefix found in local .git/config file, or None if none
571 sub_prefix = command.OutputOneLine('git', 'config', 'format.subjectprefix',
572 raise_on_error=False)
577 """Set up git utils, by reading the alias files."""
578 # Check for a git alias file also
579 global use_no_decorate
581 alias_fname = GetAliasFile()
583 settings.ReadGitAliases(alias_fname)
584 cmd = LogCmd(None, count=0)
585 use_no_decorate = (command.RunPipe([cmd], raise_on_error=False)
589 """Get the hash of the current HEAD
594 return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
596 if __name__ == "__main__":