blob: c9ceb28a050437b0790d6efa7a07ed1a6255d4db [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
11from patman import series
12from patman import settings
13from patman import terminal
14from patman import tools
Simon Glass5f6a1c42012-12-15 10:42:07 +000015
Simon Glasse49f14a2014-08-09 15:33:11 -060016# True to use --no-decorate - we check this in Setup()
17use_no_decorate = True
18
Simon Glasscda2a612014-08-09 15:33:10 -060019def LogCmd(commit_range, git_dir=None, oneline=False, reverse=False,
20 count=None):
21 """Create a command to perform a 'git log'
22
23 Args:
24 commit_range: Range expression to use for log, None for none
Anatolij Gustschinab4a6ab2019-10-27 17:55:04 +010025 git_dir: Path to git repository (None to use default)
Simon Glasscda2a612014-08-09 15:33:10 -060026 oneline: True to use --oneline, else False
27 reverse: True to reverse the log (--reverse)
28 count: Number of commits to list, or None for no limit
29 Return:
30 List containing command and arguments to run
31 """
32 cmd = ['git']
33 if git_dir:
34 cmd += ['--git-dir', git_dir]
Simon Glass9447a6b2014-08-28 09:43:37 -060035 cmd += ['--no-pager', 'log', '--no-color']
Simon Glasscda2a612014-08-09 15:33:10 -060036 if oneline:
37 cmd.append('--oneline')
Simon Glasse49f14a2014-08-09 15:33:11 -060038 if use_no_decorate:
39 cmd.append('--no-decorate')
Simon Glass042a7322014-08-14 21:59:11 -060040 if reverse:
41 cmd.append('--reverse')
Simon Glasscda2a612014-08-09 15:33:10 -060042 if count is not None:
43 cmd.append('-n%d' % count)
44 if commit_range:
45 cmd.append(commit_range)
Simon Glassd4c85722016-03-12 18:50:31 -070046
47 # Add this in case we have a branch with the same name as a directory.
48 # This avoids messages like this, for example:
49 # fatal: ambiguous argument 'test': both revision and filename
50 cmd.append('--')
Simon Glasscda2a612014-08-09 15:33:10 -060051 return cmd
Simon Glass0d24de92012-01-14 15:12:45 +000052
53def CountCommitsToBranch():
54 """Returns number of commits between HEAD and the tracking branch.
55
56 This looks back to the tracking branch and works out the number of commits
57 since then.
58
59 Return:
60 Number of patches that exist on top of the branch
61 """
Simon Glasscda2a612014-08-09 15:33:10 -060062 pipe = [LogCmd('@{upstream}..', oneline=True),
Simon Glass0d24de92012-01-14 15:12:45 +000063 ['wc', '-l']]
Simon Glassa10fd932012-12-15 10:42:04 +000064 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
Simon Glass0d24de92012-01-14 15:12:45 +000065 patch_count = int(stdout)
66 return patch_count
67
Simon Glass2a9e2c62014-12-01 17:33:54 -070068def NameRevision(commit_hash):
69 """Gets the revision name for a commit
70
71 Args:
72 commit_hash: Commit hash to look up
73
74 Return:
75 Name of revision, if any, else None
76 """
77 pipe = ['git', 'name-rev', commit_hash]
78 stdout = command.RunPipe([pipe], capture=True, oneline=True).stdout
79
80 # We expect a commit, a space, then a revision name
81 name = stdout.split(' ')[1].strip()
82 return name
83
84def GuessUpstream(git_dir, branch):
85 """Tries to guess the upstream for a branch
86
87 This lists out top commits on a branch and tries to find a suitable
88 upstream. It does this by looking for the first commit where
89 'git name-rev' returns a plain branch name, with no ! or ^ modifiers.
90
91 Args:
92 git_dir: Git directory containing repo
93 branch: Name of branch
94
95 Returns:
96 Tuple:
97 Name of upstream branch (e.g. 'upstream/master') or None if none
98 Warning/error message, or None if none
99 """
100 pipe = [LogCmd(branch, git_dir=git_dir, oneline=True, count=100)]
101 result = command.RunPipe(pipe, capture=True, capture_stderr=True,
102 raise_on_error=False)
103 if result.return_code:
104 return None, "Branch '%s' not found" % branch
105 for line in result.stdout.splitlines()[1:]:
106 commit_hash = line.split(' ')[0]
107 name = NameRevision(commit_hash)
108 if '~' not in name and '^' not in name:
109 if name.startswith('remotes/'):
110 name = name[8:]
111 return name, "Guessing upstream as '%s'" % name
112 return None, "Cannot find a suitable upstream for branch '%s'" % branch
113
Simon Glass5f6a1c42012-12-15 10:42:07 +0000114def GetUpstream(git_dir, branch):
115 """Returns the name of the upstream for a branch
116
117 Args:
118 git_dir: Git directory containing repo
119 branch: Name of branch
120
121 Returns:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700122 Tuple:
123 Name of upstream branch (e.g. 'upstream/master') or None if none
124 Warning/error message, or None if none
Simon Glass5f6a1c42012-12-15 10:42:07 +0000125 """
Simon Glasscce717a2013-05-08 08:06:08 +0000126 try:
127 remote = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
128 'branch.%s.remote' % branch)
129 merge = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
130 'branch.%s.merge' % branch)
131 except:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700132 upstream, msg = GuessUpstream(git_dir, branch)
133 return upstream, msg
Simon Glasscce717a2013-05-08 08:06:08 +0000134
Simon Glass5f6a1c42012-12-15 10:42:07 +0000135 if remote == '.':
Simon Glass71edbe52015-01-29 11:35:16 -0700136 return merge, None
Simon Glass5f6a1c42012-12-15 10:42:07 +0000137 elif remote and merge:
138 leaf = merge.split('/')[-1]
Simon Glass2a9e2c62014-12-01 17:33:54 -0700139 return '%s/%s' % (remote, leaf), None
Simon Glass5f6a1c42012-12-15 10:42:07 +0000140 else:
Paul Burtonac3fde92016-09-27 16:03:51 +0100141 raise ValueError("Cannot determine upstream branch for branch "
Simon Glass5f6a1c42012-12-15 10:42:07 +0000142 "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
143
144
145def GetRangeInBranch(git_dir, branch, include_upstream=False):
146 """Returns an expression for the commits in the given branch.
147
148 Args:
149 git_dir: Directory containing git repo
150 branch: Name of branch
151 Return:
152 Expression in the form 'upstream..branch' which can be used to
Simon Glasscce717a2013-05-08 08:06:08 +0000153 access the commits. If the branch does not exist, returns None.
Simon Glass5f6a1c42012-12-15 10:42:07 +0000154 """
Simon Glass2a9e2c62014-12-01 17:33:54 -0700155 upstream, msg = GetUpstream(git_dir, branch)
Simon Glasscce717a2013-05-08 08:06:08 +0000156 if not upstream:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700157 return None, msg
158 rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
159 return rstr, msg
Simon Glass5f6a1c42012-12-15 10:42:07 +0000160
Simon Glass5abab202014-12-01 17:33:57 -0700161def CountCommitsInRange(git_dir, range_expr):
162 """Returns the number of commits in the given range.
163
164 Args:
165 git_dir: Directory containing git repo
166 range_expr: Range to check
167 Return:
Anatolij Gustschinab4a6ab2019-10-27 17:55:04 +0100168 Number of patches that exist in the supplied range or None if none
Simon Glass5abab202014-12-01 17:33:57 -0700169 were found
170 """
171 pipe = [LogCmd(range_expr, git_dir=git_dir, oneline=True)]
172 result = command.RunPipe(pipe, capture=True, capture_stderr=True,
173 raise_on_error=False)
174 if result.return_code:
175 return None, "Range '%s' not found or is invalid" % range_expr
176 patch_count = len(result.stdout.splitlines())
177 return patch_count, None
178
Simon Glass5f6a1c42012-12-15 10:42:07 +0000179def CountCommitsInBranch(git_dir, branch, include_upstream=False):
180 """Returns the number of commits in the given branch.
181
182 Args:
183 git_dir: Directory containing git repo
184 branch: Name of branch
185 Return:
Simon Glasscce717a2013-05-08 08:06:08 +0000186 Number of patches that exist on top of the branch, or None if the
187 branch does not exist.
Simon Glass5f6a1c42012-12-15 10:42:07 +0000188 """
Simon Glass2a9e2c62014-12-01 17:33:54 -0700189 range_expr, msg = GetRangeInBranch(git_dir, branch, include_upstream)
Simon Glasscce717a2013-05-08 08:06:08 +0000190 if not range_expr:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700191 return None, msg
Simon Glass5abab202014-12-01 17:33:57 -0700192 return CountCommitsInRange(git_dir, range_expr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000193
194def CountCommits(commit_range):
195 """Returns the number of commits in the given range.
196
197 Args:
198 commit_range: Range of commits to count (e.g. 'HEAD..base')
199 Return:
200 Number of patches that exist on top of the branch
201 """
Simon Glasscda2a612014-08-09 15:33:10 -0600202 pipe = [LogCmd(commit_range, oneline=True),
Simon Glass5f6a1c42012-12-15 10:42:07 +0000203 ['wc', '-l']]
204 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
205 patch_count = int(stdout)
206 return patch_count
207
208def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
209 """Checkout the selected commit for this build
210
211 Args:
212 commit_hash: Commit hash to check out
213 """
214 pipe = ['git']
215 if git_dir:
216 pipe.extend(['--git-dir', git_dir])
217 if work_tree:
218 pipe.extend(['--work-tree', work_tree])
219 pipe.append('checkout')
220 if force:
221 pipe.append('-f')
222 pipe.append(commit_hash)
Simon Glassddaf5c82014-09-05 19:00:09 -0600223 result = command.RunPipe([pipe], capture=True, raise_on_error=False,
224 capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000225 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100226 raise OSError('git checkout (%s): %s' % (pipe, result.stderr))
Simon Glass5f6a1c42012-12-15 10:42:07 +0000227
228def Clone(git_dir, output_dir):
229 """Checkout the selected commit for this build
230
231 Args:
232 commit_hash: Commit hash to check out
233 """
234 pipe = ['git', 'clone', git_dir, '.']
Simon Glassddaf5c82014-09-05 19:00:09 -0600235 result = command.RunPipe([pipe], capture=True, cwd=output_dir,
236 capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000237 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100238 raise OSError('git clone: %s' % result.stderr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000239
240def Fetch(git_dir=None, work_tree=None):
241 """Fetch from the origin repo
242
243 Args:
244 commit_hash: Commit hash to check out
245 """
246 pipe = ['git']
247 if git_dir:
248 pipe.extend(['--git-dir', git_dir])
249 if work_tree:
250 pipe.extend(['--work-tree', work_tree])
251 pipe.append('fetch')
Simon Glassddaf5c82014-09-05 19:00:09 -0600252 result = command.RunPipe([pipe], capture=True, capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000253 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100254 raise OSError('git fetch: %s' % result.stderr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000255
Bin Meng14aa35a2020-05-04 00:52:44 -0700256def CreatePatches(start, count, ignore_binary, series):
Simon Glass0d24de92012-01-14 15:12:45 +0000257 """Create a series of patches from the top of the current branch.
258
259 The patch files are written to the current directory using
260 git format-patch.
261
262 Args:
263 start: Commit to start from: 0=HEAD, 1=next one, etc.
264 count: number of commits to include
265 Return:
266 Filename of cover letter
267 List of filenames of patch files
268 """
269 if series.get('version'):
270 version = '%s ' % series['version']
Masahiro Yamada8d3595a2015-08-31 01:23:32 +0900271 cmd = ['git', 'format-patch', '-M', '--signoff']
Bin Meng14aa35a2020-05-04 00:52:44 -0700272 if ignore_binary:
273 cmd.append('--no-binary')
Simon Glass0d24de92012-01-14 15:12:45 +0000274 if series.get('cover'):
275 cmd.append('--cover-letter')
276 prefix = series.GetPatchPrefix()
277 if prefix:
278 cmd += ['--subject-prefix=%s' % prefix]
279 cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
280
281 stdout = command.RunList(cmd)
282 files = stdout.splitlines()
283
284 # We have an extra file if there is a cover letter
285 if series.get('cover'):
286 return files[0], files[1:]
287 else:
288 return None, files
289
Simon Glassa1318f72013-03-26 13:09:42 +0000290def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
Simon Glass0d24de92012-01-14 15:12:45 +0000291 """Build a list of email addresses based on an input list.
292
293 Takes a list of email addresses and aliases, and turns this into a list
294 of only email address, by resolving any aliases that are present.
295
296 If the tag is given, then each email address is prepended with this
297 tag and a space. If the tag starts with a minus sign (indicating a
298 command line parameter) then the email address is quoted.
299
300 Args:
301 in_list: List of aliases/email addresses
302 tag: Text to put before each address
Simon Glassa1318f72013-03-26 13:09:42 +0000303 alias: Alias dictionary
304 raise_on_error: True to raise an error when an alias fails to match,
305 False to just print a message.
Simon Glass0d24de92012-01-14 15:12:45 +0000306
307 Returns:
308 List of email addresses
309
310 >>> alias = {}
311 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
312 >>> alias['john'] = ['j.bloggs@napier.co.nz']
313 >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
314 >>> alias['boys'] = ['fred', ' john']
315 >>> alias['all'] = ['fred ', 'john', ' mary ']
316 >>> BuildEmailList(['john', 'mary'], None, alias)
317 ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
318 >>> BuildEmailList(['john', 'mary'], '--to', alias)
319 ['--to "j.bloggs@napier.co.nz"', \
320'--to "Mary Poppins <m.poppins@cloud.net>"']
321 >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
322 ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
323 """
324 quote = '"' if tag and tag[0] == '-' else ''
325 raw = []
326 for item in in_list:
Simon Glassa1318f72013-03-26 13:09:42 +0000327 raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000328 result = []
329 for item in raw:
Simon Glass513eace2019-05-14 15:53:50 -0600330 item = tools.FromUnicode(item)
Simon Glass0d24de92012-01-14 15:12:45 +0000331 if not item in result:
332 result.append(item)
333 if tag:
334 return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
335 return result
336
Simon Glassa1318f72013-03-26 13:09:42 +0000337def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
Simon Glassa60aedf2018-06-19 09:56:07 -0600338 self_only=False, alias=None, in_reply_to=None, thread=False,
339 smtp_server=None):
Simon Glass0d24de92012-01-14 15:12:45 +0000340 """Email a patch series.
341
342 Args:
343 series: Series object containing destination info
344 cover_fname: filename of cover letter
345 args: list of filenames of patch files
346 dry_run: Just return the command that would be run
Simon Glassa1318f72013-03-26 13:09:42 +0000347 raise_on_error: True to raise an error when an alias fails to match,
348 False to just print a message.
Simon Glass0d24de92012-01-14 15:12:45 +0000349 cc_fname: Filename of Cc file for per-commit Cc
350 self_only: True to just email to yourself as a test
Doug Anderson6d819922013-03-17 10:31:04 +0000351 in_reply_to: If set we'll pass this to git as --in-reply-to.
352 Should be a message ID that this is in reply to.
Mateusz Kulikowski27067a42016-01-14 20:37:41 +0100353 thread: True to add --thread to git send-email (make
354 all patches reply to cover-letter or first patch in series)
Simon Glassa60aedf2018-06-19 09:56:07 -0600355 smtp_server: SMTP server to use to send patches
Simon Glass0d24de92012-01-14 15:12:45 +0000356
357 Returns:
358 Git command that was/would be run
359
Doug Andersona9700482012-11-26 15:21:40 +0000360 # For the duration of this doctest pretend that we ran patman with ./patman
361 >>> _old_argv0 = sys.argv[0]
362 >>> sys.argv[0] = './patman'
363
Simon Glass0d24de92012-01-14 15:12:45 +0000364 >>> alias = {}
365 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
366 >>> alias['john'] = ['j.bloggs@napier.co.nz']
367 >>> alias['mary'] = ['m.poppins@cloud.net']
368 >>> alias['boys'] = ['fred', ' john']
369 >>> alias['all'] = ['fred ', 'john', ' mary ']
370 >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
371 >>> series = series.Series()
372 >>> series.to = ['fred']
373 >>> series.cc = ['mary']
Simon Glassa1318f72013-03-26 13:09:42 +0000374 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
375 False, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000376 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
377"m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
Simon Glassa1318f72013-03-26 13:09:42 +0000378 >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
379 alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000380 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
381"m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
382 >>> series.cc = ['all']
Simon Glassa1318f72013-03-26 13:09:42 +0000383 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
384 True, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000385 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
386--cc-cmd cc-fname" cover p1 p2'
Simon Glassa1318f72013-03-26 13:09:42 +0000387 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
388 False, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000389 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
390"f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
391"m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
Doug Andersona9700482012-11-26 15:21:40 +0000392
393 # Restore argv[0] since we clobbered it.
394 >>> sys.argv[0] = _old_argv0
Simon Glass0d24de92012-01-14 15:12:45 +0000395 """
Simon Glassa1318f72013-03-26 13:09:42 +0000396 to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000397 if not to:
Simon Glass785f1542016-07-25 18:59:00 -0600398 git_config_to = command.Output('git', 'config', 'sendemail.to',
399 raise_on_error=False)
Masahiro Yamadaee860c62014-07-18 14:23:20 +0900400 if not git_config_to:
Simon Glass5a1af1d2019-05-14 15:53:36 -0600401 print("No recipient.\n"
402 "Please add something like this to a commit\n"
403 "Series-to: Fred Bloggs <f.blogs@napier.co.nz>\n"
404 "Or do something like this\n"
405 "git config sendemail.to u-boot@lists.denx.de")
Masahiro Yamadaee860c62014-07-18 14:23:20 +0900406 return
Peter Tyser21818302015-01-26 11:42:21 -0600407 cc = BuildEmailList(list(set(series.get('cc')) - set(series.get('to'))),
408 '--cc', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000409 if self_only:
Simon Glassa1318f72013-03-26 13:09:42 +0000410 to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000411 cc = []
412 cmd = ['git', 'send-email', '--annotate']
Simon Glassa60aedf2018-06-19 09:56:07 -0600413 if smtp_server:
414 cmd.append('--smtp-server=%s' % smtp_server)
Doug Anderson6d819922013-03-17 10:31:04 +0000415 if in_reply_to:
Simon Glassf6a6aaf2019-05-14 15:53:54 -0600416 cmd.append('--in-reply-to="%s"' % tools.FromUnicode(in_reply_to))
Mateusz Kulikowski27067a42016-01-14 20:37:41 +0100417 if thread:
418 cmd.append('--thread')
Doug Anderson6d819922013-03-17 10:31:04 +0000419
Simon Glass0d24de92012-01-14 15:12:45 +0000420 cmd += to
421 cmd += cc
422 cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
423 if cover_fname:
424 cmd.append(cover_fname)
425 cmd += args
Simon Glass2df3a012017-05-29 15:31:25 -0600426 cmdstr = ' '.join(cmd)
Simon Glass0d24de92012-01-14 15:12:45 +0000427 if not dry_run:
Simon Glass2df3a012017-05-29 15:31:25 -0600428 os.system(cmdstr)
429 return cmdstr
Simon Glass0d24de92012-01-14 15:12:45 +0000430
431
Simon Glassa1318f72013-03-26 13:09:42 +0000432def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
Simon Glass0d24de92012-01-14 15:12:45 +0000433 """If an email address is an alias, look it up and return the full name
434
435 TODO: Why not just use git's own alias feature?
436
437 Args:
438 lookup_name: Alias or email address to look up
Simon Glassa1318f72013-03-26 13:09:42 +0000439 alias: Dictionary containing aliases (None to use settings default)
440 raise_on_error: True to raise an error when an alias fails to match,
441 False to just print a message.
Simon Glass0d24de92012-01-14 15:12:45 +0000442
443 Returns:
444 tuple:
445 list containing a list of email addresses
446
447 Raises:
448 OSError if a recursive alias reference was found
449 ValueError if an alias was not found
450
451 >>> alias = {}
452 >>> alias['fred'] = ['f.bloggs@napier.co.nz']
453 >>> alias['john'] = ['j.bloggs@napier.co.nz']
454 >>> alias['mary'] = ['m.poppins@cloud.net']
455 >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
456 >>> alias['all'] = ['fred ', 'john', ' mary ']
457 >>> alias['loop'] = ['other', 'john', ' mary ']
458 >>> alias['other'] = ['loop', 'john', ' mary ']
459 >>> LookupEmail('mary', alias)
460 ['m.poppins@cloud.net']
461 >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
462 ['arthur.wellesley@howe.ro.uk']
463 >>> LookupEmail('boys', alias)
464 ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
465 >>> LookupEmail('all', alias)
466 ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
467 >>> LookupEmail('odd', alias)
468 Traceback (most recent call last):
469 ...
470 ValueError: Alias 'odd' not found
471 >>> LookupEmail('loop', alias)
472 Traceback (most recent call last):
473 ...
474 OSError: Recursive email alias at 'other'
Simon Glassa1318f72013-03-26 13:09:42 +0000475 >>> LookupEmail('odd', alias, raise_on_error=False)
Simon Glasse752edc2014-08-28 09:43:35 -0600476 Alias 'odd' not found
Simon Glassa1318f72013-03-26 13:09:42 +0000477 []
478 >>> # In this case the loop part will effectively be ignored.
479 >>> LookupEmail('loop', alias, raise_on_error=False)
Simon Glasse752edc2014-08-28 09:43:35 -0600480 Recursive email alias at 'other'
481 Recursive email alias at 'john'
482 Recursive email alias at 'mary'
Simon Glassa1318f72013-03-26 13:09:42 +0000483 ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
Simon Glass0d24de92012-01-14 15:12:45 +0000484 """
485 if not alias:
486 alias = settings.alias
487 lookup_name = lookup_name.strip()
488 if '@' in lookup_name: # Perhaps a real email address
489 return [lookup_name]
490
491 lookup_name = lookup_name.lower()
Simon Glassa1318f72013-03-26 13:09:42 +0000492 col = terminal.Color()
Simon Glass0d24de92012-01-14 15:12:45 +0000493
494 out_list = []
Simon Glassa1318f72013-03-26 13:09:42 +0000495 if level > 10:
496 msg = "Recursive email alias at '%s'" % lookup_name
497 if raise_on_error:
Paul Burtonac3fde92016-09-27 16:03:51 +0100498 raise OSError(msg)
Simon Glassa1318f72013-03-26 13:09:42 +0000499 else:
Paul Burtona920a172016-09-27 16:03:50 +0100500 print(col.Color(col.RED, msg))
Simon Glassa1318f72013-03-26 13:09:42 +0000501 return out_list
502
Simon Glass0d24de92012-01-14 15:12:45 +0000503 if lookup_name:
504 if not lookup_name in alias:
Simon Glassa1318f72013-03-26 13:09:42 +0000505 msg = "Alias '%s' not found" % lookup_name
506 if raise_on_error:
Paul Burtonac3fde92016-09-27 16:03:51 +0100507 raise ValueError(msg)
Simon Glassa1318f72013-03-26 13:09:42 +0000508 else:
Paul Burtona920a172016-09-27 16:03:50 +0100509 print(col.Color(col.RED, msg))
Simon Glassa1318f72013-03-26 13:09:42 +0000510 return out_list
Simon Glass0d24de92012-01-14 15:12:45 +0000511 for item in alias[lookup_name]:
Simon Glassa1318f72013-03-26 13:09:42 +0000512 todo = LookupEmail(item, alias, raise_on_error, level + 1)
Simon Glass0d24de92012-01-14 15:12:45 +0000513 for new_item in todo:
514 if not new_item in out_list:
515 out_list.append(new_item)
516
Paul Burtona920a172016-09-27 16:03:50 +0100517 #print("No match for alias '%s'" % lookup_name)
Simon Glass0d24de92012-01-14 15:12:45 +0000518 return out_list
519
520def GetTopLevel():
521 """Return name of top-level directory for this git repo.
522
523 Returns:
524 Full path to git top-level directory
525
526 This test makes sure that we are running tests in the right subdir
527
Doug Andersona9700482012-11-26 15:21:40 +0000528 >>> os.path.realpath(os.path.dirname(__file__)) == \
529 os.path.join(GetTopLevel(), 'tools', 'patman')
Simon Glass0d24de92012-01-14 15:12:45 +0000530 True
531 """
532 return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
533
534def GetAliasFile():
535 """Gets the name of the git alias file.
536
537 Returns:
538 Filename of git alias file, or None if none
539 """
Simon Glassdc191502012-12-15 10:42:05 +0000540 fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
541 raise_on_error=False)
Simon Glass0d24de92012-01-14 15:12:45 +0000542 if fname:
543 fname = os.path.join(GetTopLevel(), fname.strip())
544 return fname
545
Vikram Narayanan87d65552012-05-23 09:01:06 +0000546def GetDefaultUserName():
547 """Gets the user.name from .gitconfig file.
548
549 Returns:
550 User name found in .gitconfig file, or None if none
551 """
552 uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
553 return uname
554
555def GetDefaultUserEmail():
556 """Gets the user.email from the global .gitconfig file.
557
558 Returns:
559 User's email found in .gitconfig file, or None if none
560 """
561 uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
562 return uemail
563
Wu, Josh3871cd82015-04-15 10:25:18 +0800564def GetDefaultSubjectPrefix():
565 """Gets the format.subjectprefix from local .git/config file.
566
567 Returns:
568 Subject prefix found in local .git/config file, or None if none
569 """
570 sub_prefix = command.OutputOneLine('git', 'config', 'format.subjectprefix',
571 raise_on_error=False)
572
573 return sub_prefix
574
Simon Glass0d24de92012-01-14 15:12:45 +0000575def Setup():
576 """Set up git utils, by reading the alias files."""
Simon Glass0d24de92012-01-14 15:12:45 +0000577 # Check for a git alias file also
Simon Glass0b703db2014-08-28 09:43:45 -0600578 global use_no_decorate
579
Simon Glass0d24de92012-01-14 15:12:45 +0000580 alias_fname = GetAliasFile()
581 if alias_fname:
582 settings.ReadGitAliases(alias_fname)
Simon Glasse49f14a2014-08-09 15:33:11 -0600583 cmd = LogCmd(None, count=0)
584 use_no_decorate = (command.RunPipe([cmd], raise_on_error=False)
585 .return_code == 0)
Simon Glass0d24de92012-01-14 15:12:45 +0000586
Simon Glass5f6a1c42012-12-15 10:42:07 +0000587def GetHead():
588 """Get the hash of the current HEAD
589
590 Returns:
591 Hash of HEAD
592 """
593 return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
594
Simon Glass0d24de92012-01-14 15:12:45 +0000595if __name__ == "__main__":
596 import doctest
597
598 doctest.testmod()