blob: 6c4d2417a04d0083ff4426219d6414b868af2a1e [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass0d24de92012-01-14 15:12:45 +00002# Copyright (c) 2011 The Chromium OS Authors.
3#
Simon Glass0d24de92012-01-14 15:12:45 +00004
Simon Glass0d24de92012-01-14 15:12:45 +00005import re
6import os
Simon Glass0d24de92012-01-14 15:12:45 +00007import subprocess
8import sys
Simon Glass0d24de92012-01-14 15:12:45 +00009
Simon Glassbf776672020-04-17 18:09:04 -060010from patman import command
Simon Glassbf776672020-04-17 18:09:04 -060011from patman import settings
12from patman import terminal
13from patman import tools
Simon Glass5f6a1c42012-12-15 10:42:07 +000014
Simon Glasse49f14a2014-08-09 15:33:11 -060015# True to use --no-decorate - we check this in Setup()
16use_no_decorate = True
17
Simon Glasscda2a612014-08-09 15:33:10 -060018def LogCmd(commit_range, git_dir=None, oneline=False, reverse=False,
19 count=None):
20 """Create a command to perform a 'git log'
21
22 Args:
23 commit_range: Range expression to use for log, None for none
Anatolij Gustschinab4a6ab2019-10-27 17:55:04 +010024 git_dir: Path to git repository (None to use default)
Simon Glasscda2a612014-08-09 15:33:10 -060025 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
28 Return:
29 List containing command and arguments to run
30 """
31 cmd = ['git']
32 if git_dir:
33 cmd += ['--git-dir', git_dir]
Simon Glass9447a6b2014-08-28 09:43:37 -060034 cmd += ['--no-pager', 'log', '--no-color']
Simon Glasscda2a612014-08-09 15:33:10 -060035 if oneline:
36 cmd.append('--oneline')
Simon Glasse49f14a2014-08-09 15:33:11 -060037 if use_no_decorate:
38 cmd.append('--no-decorate')
Simon Glass042a7322014-08-14 21:59:11 -060039 if reverse:
40 cmd.append('--reverse')
Simon Glasscda2a612014-08-09 15:33:10 -060041 if count is not None:
42 cmd.append('-n%d' % count)
43 if commit_range:
44 cmd.append(commit_range)
Simon Glassd4c85722016-03-12 18:50:31 -070045
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
49 cmd.append('--')
Simon Glasscda2a612014-08-09 15:33:10 -060050 return cmd
Simon Glass0d24de92012-01-14 15:12:45 +000051
Simon Glass262130f2020-07-05 21:41:51 -060052def CountCommitsToBranch(branch):
Simon Glass0d24de92012-01-14 15:12:45 +000053 """Returns number of commits between HEAD and the tracking branch.
54
55 This looks back to the tracking branch and works out the number of commits
56 since then.
57
Simon Glass262130f2020-07-05 21:41:51 -060058 Args:
59 branch: Branch to count from (None for current branch)
60
Simon Glass0d24de92012-01-14 15:12:45 +000061 Return:
62 Number of patches that exist on top of the branch
63 """
Simon Glass262130f2020-07-05 21:41:51 -060064 if branch:
65 us, msg = GetUpstream('.git', branch)
66 rev_range = '%s..%s' % (us, branch)
67 else:
68 rev_range = '@{upstream}..'
Simon Glassbe051c02020-10-29 21:46:34 -060069 pipe = [LogCmd(rev_range, oneline=True)]
70 result = command.RunPipe(pipe, capture=True, capture_stderr=True,
71 oneline=True, raise_on_error=False)
72 if result.return_code:
73 raise ValueError('Failed to determine upstream: %s' %
74 result.stderr.strip())
75 patch_count = len(result.stdout.splitlines())
Simon Glass0d24de92012-01-14 15:12:45 +000076 return patch_count
77
Simon Glass2a9e2c62014-12-01 17:33:54 -070078def NameRevision(commit_hash):
79 """Gets the revision name for a commit
80
81 Args:
82 commit_hash: Commit hash to look up
83
84 Return:
85 Name of revision, if any, else None
86 """
87 pipe = ['git', 'name-rev', commit_hash]
88 stdout = command.RunPipe([pipe], capture=True, oneline=True).stdout
89
90 # We expect a commit, a space, then a revision name
91 name = stdout.split(' ')[1].strip()
92 return name
93
94def GuessUpstream(git_dir, branch):
95 """Tries to guess the upstream for a branch
96
97 This lists out top commits on a branch and tries to find a suitable
98 upstream. It does this by looking for the first commit where
99 'git name-rev' returns a plain branch name, with no ! or ^ modifiers.
100
101 Args:
102 git_dir: Git directory containing repo
103 branch: Name of branch
104
105 Returns:
106 Tuple:
107 Name of upstream branch (e.g. 'upstream/master') or None if none
108 Warning/error message, or None if none
109 """
110 pipe = [LogCmd(branch, git_dir=git_dir, oneline=True, count=100)]
111 result = command.RunPipe(pipe, capture=True, capture_stderr=True,
112 raise_on_error=False)
113 if result.return_code:
114 return None, "Branch '%s' not found" % branch
115 for line in result.stdout.splitlines()[1:]:
116 commit_hash = line.split(' ')[0]
117 name = NameRevision(commit_hash)
118 if '~' not in name and '^' not in name:
119 if name.startswith('remotes/'):
120 name = name[8:]
121 return name, "Guessing upstream as '%s'" % name
122 return None, "Cannot find a suitable upstream for branch '%s'" % branch
123
Simon Glass5f6a1c42012-12-15 10:42:07 +0000124def GetUpstream(git_dir, branch):
125 """Returns the name of the upstream for a branch
126
127 Args:
128 git_dir: Git directory containing repo
129 branch: Name of branch
130
131 Returns:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700132 Tuple:
133 Name of upstream branch (e.g. 'upstream/master') or None if none
134 Warning/error message, or None if none
Simon Glass5f6a1c42012-12-15 10:42:07 +0000135 """
Simon Glasscce717a2013-05-08 08:06:08 +0000136 try:
137 remote = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
138 'branch.%s.remote' % branch)
139 merge = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
140 'branch.%s.merge' % branch)
141 except:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700142 upstream, msg = GuessUpstream(git_dir, branch)
143 return upstream, msg
Simon Glasscce717a2013-05-08 08:06:08 +0000144
Simon Glass5f6a1c42012-12-15 10:42:07 +0000145 if remote == '.':
Simon Glass71edbe52015-01-29 11:35:16 -0700146 return merge, None
Simon Glass5f6a1c42012-12-15 10:42:07 +0000147 elif remote and merge:
148 leaf = merge.split('/')[-1]
Simon Glass2a9e2c62014-12-01 17:33:54 -0700149 return '%s/%s' % (remote, leaf), None
Simon Glass5f6a1c42012-12-15 10:42:07 +0000150 else:
Paul Burtonac3fde92016-09-27 16:03:51 +0100151 raise ValueError("Cannot determine upstream branch for branch "
Simon Glass5f6a1c42012-12-15 10:42:07 +0000152 "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
153
154
155def GetRangeInBranch(git_dir, branch, include_upstream=False):
156 """Returns an expression for the commits in the given branch.
157
158 Args:
159 git_dir: Directory containing git repo
160 branch: Name of branch
161 Return:
162 Expression in the form 'upstream..branch' which can be used to
Simon Glasscce717a2013-05-08 08:06:08 +0000163 access the commits. If the branch does not exist, returns None.
Simon Glass5f6a1c42012-12-15 10:42:07 +0000164 """
Simon Glass2a9e2c62014-12-01 17:33:54 -0700165 upstream, msg = GetUpstream(git_dir, branch)
Simon Glasscce717a2013-05-08 08:06:08 +0000166 if not upstream:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700167 return None, msg
168 rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
169 return rstr, msg
Simon Glass5f6a1c42012-12-15 10:42:07 +0000170
Simon Glass5abab202014-12-01 17:33:57 -0700171def CountCommitsInRange(git_dir, range_expr):
172 """Returns the number of commits in the given range.
173
174 Args:
175 git_dir: Directory containing git repo
176 range_expr: Range to check
177 Return:
Anatolij Gustschinab4a6ab2019-10-27 17:55:04 +0100178 Number of patches that exist in the supplied range or None if none
Simon Glass5abab202014-12-01 17:33:57 -0700179 were found
180 """
181 pipe = [LogCmd(range_expr, git_dir=git_dir, oneline=True)]
182 result = command.RunPipe(pipe, capture=True, capture_stderr=True,
183 raise_on_error=False)
184 if result.return_code:
185 return None, "Range '%s' not found or is invalid" % range_expr
186 patch_count = len(result.stdout.splitlines())
187 return patch_count, None
188
Simon Glass5f6a1c42012-12-15 10:42:07 +0000189def CountCommitsInBranch(git_dir, branch, include_upstream=False):
190 """Returns the number of commits in the given branch.
191
192 Args:
193 git_dir: Directory containing git repo
194 branch: Name of branch
195 Return:
Simon Glasscce717a2013-05-08 08:06:08 +0000196 Number of patches that exist on top of the branch, or None if the
197 branch does not exist.
Simon Glass5f6a1c42012-12-15 10:42:07 +0000198 """
Simon Glass2a9e2c62014-12-01 17:33:54 -0700199 range_expr, msg = GetRangeInBranch(git_dir, branch, include_upstream)
Simon Glasscce717a2013-05-08 08:06:08 +0000200 if not range_expr:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700201 return None, msg
Simon Glass5abab202014-12-01 17:33:57 -0700202 return CountCommitsInRange(git_dir, range_expr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000203
204def CountCommits(commit_range):
205 """Returns the number of commits in the given range.
206
207 Args:
208 commit_range: Range of commits to count (e.g. 'HEAD..base')
209 Return:
210 Number of patches that exist on top of the branch
211 """
Simon Glasscda2a612014-08-09 15:33:10 -0600212 pipe = [LogCmd(commit_range, oneline=True),
Simon Glass5f6a1c42012-12-15 10:42:07 +0000213 ['wc', '-l']]
214 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
215 patch_count = int(stdout)
216 return patch_count
217
218def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
219 """Checkout the selected commit for this build
220
221 Args:
222 commit_hash: Commit hash to check out
223 """
224 pipe = ['git']
225 if git_dir:
226 pipe.extend(['--git-dir', git_dir])
227 if work_tree:
228 pipe.extend(['--work-tree', work_tree])
229 pipe.append('checkout')
230 if force:
231 pipe.append('-f')
232 pipe.append(commit_hash)
Simon Glassddaf5c82014-09-05 19:00:09 -0600233 result = command.RunPipe([pipe], capture=True, raise_on_error=False,
234 capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000235 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100236 raise OSError('git checkout (%s): %s' % (pipe, result.stderr))
Simon Glass5f6a1c42012-12-15 10:42:07 +0000237
238def Clone(git_dir, output_dir):
239 """Checkout the selected commit for this build
240
241 Args:
242 commit_hash: Commit hash to check out
243 """
244 pipe = ['git', 'clone', git_dir, '.']
Simon Glassddaf5c82014-09-05 19:00:09 -0600245 result = command.RunPipe([pipe], capture=True, cwd=output_dir,
246 capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000247 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100248 raise OSError('git clone: %s' % result.stderr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000249
250def Fetch(git_dir=None, work_tree=None):
251 """Fetch from the origin repo
252
253 Args:
254 commit_hash: Commit hash to check out
255 """
256 pipe = ['git']
257 if git_dir:
258 pipe.extend(['--git-dir', git_dir])
259 if work_tree:
260 pipe.extend(['--work-tree', work_tree])
261 pipe.append('fetch')
Simon Glassddaf5c82014-09-05 19:00:09 -0600262 result = command.RunPipe([pipe], capture=True, capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000263 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100264 raise OSError('git fetch: %s' % result.stderr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000265
Alper Nebi Yasak76de29f2020-09-03 15:51:03 +0300266def CheckWorktreeIsAvailable(git_dir):
267 """Check if git-worktree functionality is available
268
269 Args:
270 git_dir: The repository to test in
271
272 Returns:
273 True if git-worktree commands will work, False otherwise.
274 """
275 pipe = ['git', '--git-dir', git_dir, 'worktree', 'list']
276 result = command.RunPipe([pipe], capture=True, capture_stderr=True,
277 raise_on_error=False)
278 return result.return_code == 0
279
280def AddWorktree(git_dir, output_dir, commit_hash=None):
281 """Create and checkout a new git worktree for this build
282
283 Args:
284 git_dir: The repository to checkout the worktree from
285 output_dir: Path for the new worktree
286 commit_hash: Commit hash to checkout
287 """
288 # We need to pass --detach to avoid creating a new branch
289 pipe = ['git', '--git-dir', git_dir, 'worktree', 'add', '.', '--detach']
290 if commit_hash:
291 pipe.append(commit_hash)
292 result = command.RunPipe([pipe], capture=True, cwd=output_dir,
293 capture_stderr=True)
294 if result.return_code != 0:
295 raise OSError('git worktree add: %s' % result.stderr)
296
297def PruneWorktrees(git_dir):
298 """Remove administrative files for deleted worktrees
299
300 Args:
301 git_dir: The repository whose deleted worktrees should be pruned
302 """
303 pipe = ['git', '--git-dir', git_dir, 'worktree', 'prune']
304 result = command.RunPipe([pipe], capture=True, capture_stderr=True)
305 if result.return_code != 0:
306 raise OSError('git worktree prune: %s' % result.stderr)
307
Simon Glass262130f2020-07-05 21:41:51 -0600308def CreatePatches(branch, start, count, ignore_binary, series):
Simon Glass0d24de92012-01-14 15:12:45 +0000309 """Create a series of patches from the top of the current branch.
310
311 The patch files are written to the current directory using
312 git format-patch.
313
314 Args:
Simon Glass262130f2020-07-05 21:41:51 -0600315 branch: Branch to create patches from (None for current branch)
Simon Glass0d24de92012-01-14 15:12:45 +0000316 start: Commit to start from: 0=HEAD, 1=next one, etc.
317 count: number of commits to include
Simon Glass7d5b04e2020-07-05 21:41:49 -0600318 ignore_binary: Don't generate patches for binary files
319 series: Series object for this series (set of patches)
Simon Glass0d24de92012-01-14 15:12:45 +0000320 Return:
Simon Glass7d5b04e2020-07-05 21:41:49 -0600321 Filename of cover letter (None if none)
Simon Glass0d24de92012-01-14 15:12:45 +0000322 List of filenames of patch files
323 """
324 if series.get('version'):
325 version = '%s ' % series['version']
Masahiro Yamada8d3595a2015-08-31 01:23:32 +0900326 cmd = ['git', 'format-patch', '-M', '--signoff']
Bin Meng14aa35a2020-05-04 00:52:44 -0700327 if ignore_binary:
328 cmd.append('--no-binary')
Simon Glass0d24de92012-01-14 15:12:45 +0000329 if series.get('cover'):
330 cmd.append('--cover-letter')
331 prefix = series.GetPatchPrefix()
332 if prefix:
333 cmd += ['--subject-prefix=%s' % prefix]
Simon Glass262130f2020-07-05 21:41:51 -0600334 brname = branch or 'HEAD'
335 cmd += ['%s~%d..%s~%d' % (brname, start + count, brname, start)]
Simon Glass0d24de92012-01-14 15:12:45 +0000336
337 stdout = command.RunList(cmd)
338 files = stdout.splitlines()
339
340 # We have an extra file if there is a cover letter
341 if series.get('cover'):
342 return files[0], files[1:]
343 else:
344 return None, files
345
Simon Glassa1318f72013-03-26 13:09:42 +0000346def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
Simon Glass0d24de92012-01-14 15:12:45 +0000347 """Build a list of email addresses based on an input list.
348
349 Takes a list of email addresses and aliases, and turns this into a list
350 of only email address, by resolving any aliases that are present.
351
352 If the tag is given, then each email address is prepended with this
353 tag and a space. If the tag starts with a minus sign (indicating a
354 command line parameter) then the email address is quoted.
355
356 Args:
357 in_list: List of aliases/email addresses
358 tag: Text to put before each address
Simon Glassa1318f72013-03-26 13:09:42 +0000359 alias: Alias dictionary
360 raise_on_error: True to raise an error when an alias fails to match,
361 False to just print a message.
Simon Glass0d24de92012-01-14 15:12:45 +0000362
363 Returns:
364 List of email addresses
365
366 >>> alias = {}
367 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
368 >>> alias['john'] = ['j.bloggs@napier.co.nz']
369 >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
370 >>> alias['boys'] = ['fred', ' john']
371 >>> alias['all'] = ['fred ', 'john', ' mary ']
372 >>> BuildEmailList(['john', 'mary'], None, alias)
373 ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
374 >>> BuildEmailList(['john', 'mary'], '--to', alias)
375 ['--to "j.bloggs@napier.co.nz"', \
376'--to "Mary Poppins <m.poppins@cloud.net>"']
377 >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
378 ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
379 """
380 quote = '"' if tag and tag[0] == '-' else ''
381 raw = []
382 for item in in_list:
Simon Glassa1318f72013-03-26 13:09:42 +0000383 raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000384 result = []
385 for item in raw:
386 if not item in result:
387 result.append(item)
388 if tag:
389 return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
390 return result
391
Nicolas Boichat94977562020-07-13 10:50:00 +0800392def CheckSuppressCCConfig():
393 """Check if sendemail.suppresscc is configured correctly.
394
395 Returns:
396 True if the option is configured correctly, False otherwise.
397 """
398 suppresscc = command.OutputOneLine('git', 'config', 'sendemail.suppresscc',
399 raise_on_error=False)
400
401 # Other settings should be fine.
402 if suppresscc == 'all' or suppresscc == 'cccmd':
403 col = terminal.Color()
404
405 print((col.Color(col.RED, "error") +
406 ": git config sendemail.suppresscc set to %s\n" % (suppresscc)) +
407 " patman needs --cc-cmd to be run to set the cc list.\n" +
408 " Please run:\n" +
409 " git config --unset sendemail.suppresscc\n" +
410 " Or read the man page:\n" +
411 " git send-email --help\n" +
412 " and set an option that runs --cc-cmd\n")
413 return False
414
415 return True
416
Simon Glassa1318f72013-03-26 13:09:42 +0000417def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
Simon Glassa60aedf2018-06-19 09:56:07 -0600418 self_only=False, alias=None, in_reply_to=None, thread=False,
419 smtp_server=None):
Simon Glass0d24de92012-01-14 15:12:45 +0000420 """Email a patch series.
421
422 Args:
423 series: Series object containing destination info
424 cover_fname: filename of cover letter
425 args: list of filenames of patch files
426 dry_run: Just return the command that would be run
Simon Glassa1318f72013-03-26 13:09:42 +0000427 raise_on_error: True to raise an error when an alias fails to match,
428 False to just print a message.
Simon Glass0d24de92012-01-14 15:12:45 +0000429 cc_fname: Filename of Cc file for per-commit Cc
430 self_only: True to just email to yourself as a test
Doug Anderson6d819922013-03-17 10:31:04 +0000431 in_reply_to: If set we'll pass this to git as --in-reply-to.
432 Should be a message ID that this is in reply to.
Mateusz Kulikowski27067a42016-01-14 20:37:41 +0100433 thread: True to add --thread to git send-email (make
434 all patches reply to cover-letter or first patch in series)
Simon Glassa60aedf2018-06-19 09:56:07 -0600435 smtp_server: SMTP server to use to send patches
Simon Glass0d24de92012-01-14 15:12:45 +0000436
437 Returns:
438 Git command that was/would be run
439
Doug Andersona9700482012-11-26 15:21:40 +0000440 # For the duration of this doctest pretend that we ran patman with ./patman
441 >>> _old_argv0 = sys.argv[0]
442 >>> sys.argv[0] = './patman'
443
Simon Glass0d24de92012-01-14 15:12:45 +0000444 >>> alias = {}
445 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
446 >>> alias['john'] = ['j.bloggs@napier.co.nz']
447 >>> alias['mary'] = ['m.poppins@cloud.net']
448 >>> alias['boys'] = ['fred', ' john']
449 >>> alias['all'] = ['fred ', 'john', ' mary ']
450 >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
Simon Glass38a9d3b2020-06-07 06:45:47 -0600451 >>> series = {}
452 >>> series['to'] = ['fred']
453 >>> series['cc'] = ['mary']
Simon Glassa1318f72013-03-26 13:09:42 +0000454 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
455 False, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000456 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
Simon Glass46007672020-11-03 13:54:10 -0700457"m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" cover p1 p2'
Simon Glassa1318f72013-03-26 13:09:42 +0000458 >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
459 alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000460 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
Simon Glass46007672020-11-03 13:54:10 -0700461"m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" p1'
Simon Glass38a9d3b2020-06-07 06:45:47 -0600462 >>> series['cc'] = ['all']
Simon Glassa1318f72013-03-26 13:09:42 +0000463 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
464 True, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000465 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
Simon Glass46007672020-11-03 13:54:10 -0700466send --cc-cmd cc-fname" cover p1 p2'
Simon Glassa1318f72013-03-26 13:09:42 +0000467 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
468 False, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000469 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
470"f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
Simon Glass46007672020-11-03 13:54:10 -0700471"m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" cover p1 p2'
Doug Andersona9700482012-11-26 15:21:40 +0000472
473 # Restore argv[0] since we clobbered it.
474 >>> sys.argv[0] = _old_argv0
Simon Glass0d24de92012-01-14 15:12:45 +0000475 """
Simon Glassa1318f72013-03-26 13:09:42 +0000476 to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000477 if not to:
Simon Glass785f1542016-07-25 18:59:00 -0600478 git_config_to = command.Output('git', 'config', 'sendemail.to',
479 raise_on_error=False)
Masahiro Yamadaee860c62014-07-18 14:23:20 +0900480 if not git_config_to:
Simon Glass5a1af1d2019-05-14 15:53:36 -0600481 print("No recipient.\n"
482 "Please add something like this to a commit\n"
483 "Series-to: Fred Bloggs <f.blogs@napier.co.nz>\n"
484 "Or do something like this\n"
485 "git config sendemail.to u-boot@lists.denx.de")
Masahiro Yamadaee860c62014-07-18 14:23:20 +0900486 return
Peter Tyser21818302015-01-26 11:42:21 -0600487 cc = BuildEmailList(list(set(series.get('cc')) - set(series.get('to'))),
488 '--cc', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000489 if self_only:
Simon Glassa1318f72013-03-26 13:09:42 +0000490 to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000491 cc = []
492 cmd = ['git', 'send-email', '--annotate']
Simon Glassa60aedf2018-06-19 09:56:07 -0600493 if smtp_server:
494 cmd.append('--smtp-server=%s' % smtp_server)
Doug Anderson6d819922013-03-17 10:31:04 +0000495 if in_reply_to:
Simon Glassfc0056e2020-11-08 20:36:18 -0700496 cmd.append('--in-reply-to="%s"' % in_reply_to)
Mateusz Kulikowski27067a42016-01-14 20:37:41 +0100497 if thread:
498 cmd.append('--thread')
Doug Anderson6d819922013-03-17 10:31:04 +0000499
Simon Glass0d24de92012-01-14 15:12:45 +0000500 cmd += to
501 cmd += cc
Simon Glass46007672020-11-03 13:54:10 -0700502 cmd += ['--cc-cmd', '"%s send --cc-cmd %s"' % (sys.argv[0], cc_fname)]
Simon Glass0d24de92012-01-14 15:12:45 +0000503 if cover_fname:
504 cmd.append(cover_fname)
505 cmd += args
Simon Glass2df3a012017-05-29 15:31:25 -0600506 cmdstr = ' '.join(cmd)
Simon Glass0d24de92012-01-14 15:12:45 +0000507 if not dry_run:
Simon Glass2df3a012017-05-29 15:31:25 -0600508 os.system(cmdstr)
509 return cmdstr
Simon Glass0d24de92012-01-14 15:12:45 +0000510
511
Simon Glassa1318f72013-03-26 13:09:42 +0000512def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
Simon Glass0d24de92012-01-14 15:12:45 +0000513 """If an email address is an alias, look it up and return the full name
514
515 TODO: Why not just use git's own alias feature?
516
517 Args:
518 lookup_name: Alias or email address to look up
Simon Glassa1318f72013-03-26 13:09:42 +0000519 alias: Dictionary containing aliases (None to use settings default)
520 raise_on_error: True to raise an error when an alias fails to match,
521 False to just print a message.
Simon Glass0d24de92012-01-14 15:12:45 +0000522
523 Returns:
524 tuple:
525 list containing a list of email addresses
526
527 Raises:
528 OSError if a recursive alias reference was found
529 ValueError if an alias was not found
530
531 >>> alias = {}
532 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
533 >>> alias['john'] = ['j.bloggs@napier.co.nz']
534 >>> alias['mary'] = ['m.poppins@cloud.net']
535 >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
536 >>> alias['all'] = ['fred ', 'john', ' mary ']
537 >>> alias['loop'] = ['other', 'john', ' mary ']
538 >>> alias['other'] = ['loop', 'john', ' mary ']
539 >>> LookupEmail('mary', alias)
540 ['m.poppins@cloud.net']
541 >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
542 ['arthur.wellesley@howe.ro.uk']
543 >>> LookupEmail('boys', alias)
544 ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
545 >>> LookupEmail('all', alias)
546 ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
547 >>> LookupEmail('odd', alias)
548 Traceback (most recent call last):
549 ...
550 ValueError: Alias 'odd' not found
551 >>> LookupEmail('loop', alias)
552 Traceback (most recent call last):
553 ...
554 OSError: Recursive email alias at 'other'
Simon Glassa1318f72013-03-26 13:09:42 +0000555 >>> LookupEmail('odd', alias, raise_on_error=False)
Simon Glasse752edc2014-08-28 09:43:35 -0600556 Alias 'odd' not found
Simon Glassa1318f72013-03-26 13:09:42 +0000557 []
558 >>> # In this case the loop part will effectively be ignored.
559 >>> LookupEmail('loop', alias, raise_on_error=False)
Simon Glasse752edc2014-08-28 09:43:35 -0600560 Recursive email alias at 'other'
561 Recursive email alias at 'john'
562 Recursive email alias at 'mary'
Simon Glassa1318f72013-03-26 13:09:42 +0000563 ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
Simon Glass0d24de92012-01-14 15:12:45 +0000564 """
565 if not alias:
566 alias = settings.alias
567 lookup_name = lookup_name.strip()
568 if '@' in lookup_name: # Perhaps a real email address
569 return [lookup_name]
570
571 lookup_name = lookup_name.lower()
Simon Glassa1318f72013-03-26 13:09:42 +0000572 col = terminal.Color()
Simon Glass0d24de92012-01-14 15:12:45 +0000573
574 out_list = []
Simon Glassa1318f72013-03-26 13:09:42 +0000575 if level > 10:
576 msg = "Recursive email alias at '%s'" % lookup_name
577 if raise_on_error:
Paul Burtonac3fde92016-09-27 16:03:51 +0100578 raise OSError(msg)
Simon Glassa1318f72013-03-26 13:09:42 +0000579 else:
Paul Burtona920a172016-09-27 16:03:50 +0100580 print(col.Color(col.RED, msg))
Simon Glassa1318f72013-03-26 13:09:42 +0000581 return out_list
582
Simon Glass0d24de92012-01-14 15:12:45 +0000583 if lookup_name:
584 if not lookup_name in alias:
Simon Glassa1318f72013-03-26 13:09:42 +0000585 msg = "Alias '%s' not found" % lookup_name
586 if raise_on_error:
Paul Burtonac3fde92016-09-27 16:03:51 +0100587 raise ValueError(msg)
Simon Glassa1318f72013-03-26 13:09:42 +0000588 else:
Paul Burtona920a172016-09-27 16:03:50 +0100589 print(col.Color(col.RED, msg))
Simon Glassa1318f72013-03-26 13:09:42 +0000590 return out_list
Simon Glass0d24de92012-01-14 15:12:45 +0000591 for item in alias[lookup_name]:
Simon Glassa1318f72013-03-26 13:09:42 +0000592 todo = LookupEmail(item, alias, raise_on_error, level + 1)
Simon Glass0d24de92012-01-14 15:12:45 +0000593 for new_item in todo:
594 if not new_item in out_list:
595 out_list.append(new_item)
596
Paul Burtona920a172016-09-27 16:03:50 +0100597 #print("No match for alias '%s'" % lookup_name)
Simon Glass0d24de92012-01-14 15:12:45 +0000598 return out_list
599
600def GetTopLevel():
601 """Return name of top-level directory for this git repo.
602
603 Returns:
604 Full path to git top-level directory
605
606 This test makes sure that we are running tests in the right subdir
607
Doug Andersona9700482012-11-26 15:21:40 +0000608 >>> os.path.realpath(os.path.dirname(__file__)) == \
609 os.path.join(GetTopLevel(), 'tools', 'patman')
Simon Glass0d24de92012-01-14 15:12:45 +0000610 True
611 """
612 return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
613
614def GetAliasFile():
615 """Gets the name of the git alias file.
616
617 Returns:
618 Filename of git alias file, or None if none
619 """
Simon Glassdc191502012-12-15 10:42:05 +0000620 fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
621 raise_on_error=False)
Simon Glass0d24de92012-01-14 15:12:45 +0000622 if fname:
623 fname = os.path.join(GetTopLevel(), fname.strip())
624 return fname
625
Vikram Narayanan87d65552012-05-23 09:01:06 +0000626def GetDefaultUserName():
627 """Gets the user.name from .gitconfig file.
628
629 Returns:
630 User name found in .gitconfig file, or None if none
631 """
632 uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
633 return uname
634
635def GetDefaultUserEmail():
636 """Gets the user.email from the global .gitconfig file.
637
638 Returns:
639 User's email found in .gitconfig file, or None if none
640 """
641 uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
642 return uemail
643
Wu, Josh3871cd82015-04-15 10:25:18 +0800644def GetDefaultSubjectPrefix():
645 """Gets the format.subjectprefix from local .git/config file.
646
647 Returns:
648 Subject prefix found in local .git/config file, or None if none
649 """
650 sub_prefix = command.OutputOneLine('git', 'config', 'format.subjectprefix',
651 raise_on_error=False)
652
653 return sub_prefix
654
Simon Glass0d24de92012-01-14 15:12:45 +0000655def Setup():
656 """Set up git utils, by reading the alias files."""
Simon Glass0d24de92012-01-14 15:12:45 +0000657 # Check for a git alias file also
Simon Glass0b703db2014-08-28 09:43:45 -0600658 global use_no_decorate
659
Simon Glass0d24de92012-01-14 15:12:45 +0000660 alias_fname = GetAliasFile()
661 if alias_fname:
662 settings.ReadGitAliases(alias_fname)
Simon Glasse49f14a2014-08-09 15:33:11 -0600663 cmd = LogCmd(None, count=0)
664 use_no_decorate = (command.RunPipe([cmd], raise_on_error=False)
665 .return_code == 0)
Simon Glass0d24de92012-01-14 15:12:45 +0000666
Simon Glass5f6a1c42012-12-15 10:42:07 +0000667def GetHead():
668 """Get the hash of the current HEAD
669
670 Returns:
671 Hash of HEAD
672 """
673 return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
674
Simon Glass0d24de92012-01-14 15:12:45 +0000675if __name__ == "__main__":
676 import doctest
677
678 doctest.testmod()