blob: 29444bf8e929bb79193dff79e907e9efe105263b [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
Tom Rini72083962020-07-24 08:42:06 -040052def CountCommitsToBranch():
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
58 Return:
59 Number of patches that exist on top of the branch
60 """
Tom Rini72083962020-07-24 08:42:06 -040061 pipe = [LogCmd('@{upstream}..', oneline=True),
62 ['wc', '-l']]
Simon Glassa10fd932012-12-15 10:42:04 +000063 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
Simon Glass0d24de92012-01-14 15:12:45 +000064 patch_count = int(stdout)
65 return patch_count
66
Simon Glass2a9e2c62014-12-01 17:33:54 -070067def NameRevision(commit_hash):
68 """Gets the revision name for a commit
69
70 Args:
71 commit_hash: Commit hash to look up
72
73 Return:
74 Name of revision, if any, else None
75 """
76 pipe = ['git', 'name-rev', commit_hash]
77 stdout = command.RunPipe([pipe], capture=True, oneline=True).stdout
78
79 # We expect a commit, a space, then a revision name
80 name = stdout.split(' ')[1].strip()
81 return name
82
83def GuessUpstream(git_dir, branch):
84 """Tries to guess the upstream for a branch
85
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.
89
90 Args:
91 git_dir: Git directory containing repo
92 branch: Name of branch
93
94 Returns:
95 Tuple:
96 Name of upstream branch (e.g. 'upstream/master') or None if none
97 Warning/error message, or None if none
98 """
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/'):
109 name = name[8:]
110 return name, "Guessing upstream as '%s'" % name
111 return None, "Cannot find a suitable upstream for branch '%s'" % branch
112
Simon Glass5f6a1c42012-12-15 10:42:07 +0000113def GetUpstream(git_dir, branch):
114 """Returns the name of the upstream for a branch
115
116 Args:
117 git_dir: Git directory containing repo
118 branch: Name of branch
119
120 Returns:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700121 Tuple:
122 Name of upstream branch (e.g. 'upstream/master') or None if none
123 Warning/error message, or None if none
Simon Glass5f6a1c42012-12-15 10:42:07 +0000124 """
Simon Glasscce717a2013-05-08 08:06:08 +0000125 try:
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)
130 except:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700131 upstream, msg = GuessUpstream(git_dir, branch)
132 return upstream, msg
Simon Glasscce717a2013-05-08 08:06:08 +0000133
Simon Glass5f6a1c42012-12-15 10:42:07 +0000134 if remote == '.':
Simon Glass71edbe52015-01-29 11:35:16 -0700135 return merge, None
Simon Glass5f6a1c42012-12-15 10:42:07 +0000136 elif remote and merge:
137 leaf = merge.split('/')[-1]
Simon Glass2a9e2c62014-12-01 17:33:54 -0700138 return '%s/%s' % (remote, leaf), None
Simon Glass5f6a1c42012-12-15 10:42:07 +0000139 else:
Paul Burtonac3fde92016-09-27 16:03:51 +0100140 raise ValueError("Cannot determine upstream branch for branch "
Simon Glass5f6a1c42012-12-15 10:42:07 +0000141 "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
142
143
144def GetRangeInBranch(git_dir, branch, include_upstream=False):
145 """Returns an expression for the commits in the given branch.
146
147 Args:
148 git_dir: Directory containing git repo
149 branch: Name of branch
150 Return:
151 Expression in the form 'upstream..branch' which can be used to
Simon Glasscce717a2013-05-08 08:06:08 +0000152 access the commits. If the branch does not exist, returns None.
Simon Glass5f6a1c42012-12-15 10:42:07 +0000153 """
Simon Glass2a9e2c62014-12-01 17:33:54 -0700154 upstream, msg = GetUpstream(git_dir, branch)
Simon Glasscce717a2013-05-08 08:06:08 +0000155 if not upstream:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700156 return None, msg
157 rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
158 return rstr, msg
Simon Glass5f6a1c42012-12-15 10:42:07 +0000159
Simon Glass5abab202014-12-01 17:33:57 -0700160def CountCommitsInRange(git_dir, range_expr):
161 """Returns the number of commits in the given range.
162
163 Args:
164 git_dir: Directory containing git repo
165 range_expr: Range to check
166 Return:
Anatolij Gustschinab4a6ab2019-10-27 17:55:04 +0100167 Number of patches that exist in the supplied range or None if none
Simon Glass5abab202014-12-01 17:33:57 -0700168 were found
169 """
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
177
Simon Glass5f6a1c42012-12-15 10:42:07 +0000178def CountCommitsInBranch(git_dir, branch, include_upstream=False):
179 """Returns the number of commits in the given branch.
180
181 Args:
182 git_dir: Directory containing git repo
183 branch: Name of branch
184 Return:
Simon Glasscce717a2013-05-08 08:06:08 +0000185 Number of patches that exist on top of the branch, or None if the
186 branch does not exist.
Simon Glass5f6a1c42012-12-15 10:42:07 +0000187 """
Simon Glass2a9e2c62014-12-01 17:33:54 -0700188 range_expr, msg = GetRangeInBranch(git_dir, branch, include_upstream)
Simon Glasscce717a2013-05-08 08:06:08 +0000189 if not range_expr:
Simon Glass2a9e2c62014-12-01 17:33:54 -0700190 return None, msg
Simon Glass5abab202014-12-01 17:33:57 -0700191 return CountCommitsInRange(git_dir, range_expr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000192
193def CountCommits(commit_range):
194 """Returns the number of commits in the given range.
195
196 Args:
197 commit_range: Range of commits to count (e.g. 'HEAD..base')
198 Return:
199 Number of patches that exist on top of the branch
200 """
Simon Glasscda2a612014-08-09 15:33:10 -0600201 pipe = [LogCmd(commit_range, oneline=True),
Simon Glass5f6a1c42012-12-15 10:42:07 +0000202 ['wc', '-l']]
203 stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
204 patch_count = int(stdout)
205 return patch_count
206
207def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
208 """Checkout the selected commit for this build
209
210 Args:
211 commit_hash: Commit hash to check out
212 """
213 pipe = ['git']
214 if git_dir:
215 pipe.extend(['--git-dir', git_dir])
216 if work_tree:
217 pipe.extend(['--work-tree', work_tree])
218 pipe.append('checkout')
219 if force:
220 pipe.append('-f')
221 pipe.append(commit_hash)
Simon Glassddaf5c82014-09-05 19:00:09 -0600222 result = command.RunPipe([pipe], capture=True, raise_on_error=False,
223 capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000224 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100225 raise OSError('git checkout (%s): %s' % (pipe, result.stderr))
Simon Glass5f6a1c42012-12-15 10:42:07 +0000226
227def Clone(git_dir, output_dir):
228 """Checkout the selected commit for this build
229
230 Args:
231 commit_hash: Commit hash to check out
232 """
233 pipe = ['git', 'clone', git_dir, '.']
Simon Glassddaf5c82014-09-05 19:00:09 -0600234 result = command.RunPipe([pipe], capture=True, cwd=output_dir,
235 capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000236 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100237 raise OSError('git clone: %s' % result.stderr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000238
239def Fetch(git_dir=None, work_tree=None):
240 """Fetch from the origin repo
241
242 Args:
243 commit_hash: Commit hash to check out
244 """
245 pipe = ['git']
246 if git_dir:
247 pipe.extend(['--git-dir', git_dir])
248 if work_tree:
249 pipe.extend(['--work-tree', work_tree])
250 pipe.append('fetch')
Simon Glassddaf5c82014-09-05 19:00:09 -0600251 result = command.RunPipe([pipe], capture=True, capture_stderr=True)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000252 if result.return_code != 0:
Paul Burtonac3fde92016-09-27 16:03:51 +0100253 raise OSError('git fetch: %s' % result.stderr)
Simon Glass5f6a1c42012-12-15 10:42:07 +0000254
Tom Rini72083962020-07-24 08:42:06 -0400255def CreatePatches(start, count, ignore_binary, series):
Simon Glass0d24de92012-01-14 15:12:45 +0000256 """Create a series of patches from the top of the current branch.
257
258 The patch files are written to the current directory using
259 git format-patch.
260
261 Args:
262 start: Commit to start from: 0=HEAD, 1=next one, etc.
263 count: number of commits to include
Simon Glass7d5b04e2020-07-05 21:41:49 -0600264 ignore_binary: Don't generate patches for binary files
265 series: Series object for this series (set of patches)
Simon Glass0d24de92012-01-14 15:12:45 +0000266 Return:
Simon Glass7d5b04e2020-07-05 21:41:49 -0600267 Filename of cover letter (None if none)
Simon Glass0d24de92012-01-14 15:12:45 +0000268 List of filenames of patch files
269 """
270 if series.get('version'):
271 version = '%s ' % series['version']
Masahiro Yamada8d3595a2015-08-31 01:23:32 +0900272 cmd = ['git', 'format-patch', '-M', '--signoff']
Bin Meng14aa35a2020-05-04 00:52:44 -0700273 if ignore_binary:
274 cmd.append('--no-binary')
Simon Glass0d24de92012-01-14 15:12:45 +0000275 if series.get('cover'):
276 cmd.append('--cover-letter')
277 prefix = series.GetPatchPrefix()
278 if prefix:
279 cmd += ['--subject-prefix=%s' % prefix]
Tom Rini72083962020-07-24 08:42:06 -0400280 cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
Simon Glass0d24de92012-01-14 15:12:45 +0000281
282 stdout = command.RunList(cmd)
283 files = stdout.splitlines()
284
285 # We have an extra file if there is a cover letter
286 if series.get('cover'):
287 return files[0], files[1:]
288 else:
289 return None, files
290
Simon Glassa1318f72013-03-26 13:09:42 +0000291def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
Simon Glass0d24de92012-01-14 15:12:45 +0000292 """Build a list of email addresses based on an input list.
293
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.
296
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.
300
301 Args:
302 in_list: List of aliases/email addresses
303 tag: Text to put before each address
Simon Glassa1318f72013-03-26 13:09:42 +0000304 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.
Simon Glass0d24de92012-01-14 15:12:45 +0000307
308 Returns:
309 List of email addresses
310
311 >>> alias = {}
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>']
324 """
325 quote = '"' if tag and tag[0] == '-' else ''
326 raw = []
327 for item in in_list:
Simon Glassa1318f72013-03-26 13:09:42 +0000328 raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000329 result = []
330 for item in raw:
Simon Glass513eace2019-05-14 15:53:50 -0600331 item = tools.FromUnicode(item)
Simon Glass0d24de92012-01-14 15:12:45 +0000332 if not item in result:
333 result.append(item)
334 if tag:
335 return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
336 return result
337
Simon Glassa1318f72013-03-26 13:09:42 +0000338def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
Simon Glassa60aedf2018-06-19 09:56:07 -0600339 self_only=False, alias=None, in_reply_to=None, thread=False,
340 smtp_server=None):
Simon Glass0d24de92012-01-14 15:12:45 +0000341 """Email a patch series.
342
343 Args:
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
Simon Glassa1318f72013-03-26 13:09:42 +0000348 raise_on_error: True to raise an error when an alias fails to match,
349 False to just print a message.
Simon Glass0d24de92012-01-14 15:12:45 +0000350 cc_fname: Filename of Cc file for per-commit Cc
351 self_only: True to just email to yourself as a test
Doug Anderson6d819922013-03-17 10:31:04 +0000352 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.
Mateusz Kulikowski27067a42016-01-14 20:37:41 +0100354 thread: True to add --thread to git send-email (make
355 all patches reply to cover-letter or first patch in series)
Simon Glassa60aedf2018-06-19 09:56:07 -0600356 smtp_server: SMTP server to use to send patches
Simon Glass0d24de92012-01-14 15:12:45 +0000357
358 Returns:
359 Git command that was/would be run
360
Doug Andersona9700482012-11-26 15:21:40 +0000361 # For the duration of this doctest pretend that we ran patman with ./patman
362 >>> _old_argv0 = sys.argv[0]
363 >>> sys.argv[0] = './patman'
364
Simon Glass0d24de92012-01-14 15:12:45 +0000365 >>> alias = {}
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']
Simon Glass38a9d3b2020-06-07 06:45:47 -0600372 >>> series = {}
373 >>> series['to'] = ['fred']
374 >>> series['cc'] = ['mary']
Simon Glassa1318f72013-03-26 13:09:42 +0000375 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
376 False, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000377 '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'
Simon Glassa1318f72013-03-26 13:09:42 +0000379 >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
380 alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000381 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
382"m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
Simon Glass38a9d3b2020-06-07 06:45:47 -0600383 >>> series['cc'] = ['all']
Simon Glassa1318f72013-03-26 13:09:42 +0000384 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
385 True, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000386 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
387--cc-cmd cc-fname" cover p1 p2'
Simon Glassa1318f72013-03-26 13:09:42 +0000388 >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
389 False, alias)
Simon Glass0d24de92012-01-14 15:12:45 +0000390 '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'
Doug Andersona9700482012-11-26 15:21:40 +0000393
394 # Restore argv[0] since we clobbered it.
395 >>> sys.argv[0] = _old_argv0
Simon Glass0d24de92012-01-14 15:12:45 +0000396 """
Simon Glassa1318f72013-03-26 13:09:42 +0000397 to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000398 if not to:
Simon Glass785f1542016-07-25 18:59:00 -0600399 git_config_to = command.Output('git', 'config', 'sendemail.to',
400 raise_on_error=False)
Masahiro Yamadaee860c62014-07-18 14:23:20 +0900401 if not git_config_to:
Simon Glass5a1af1d2019-05-14 15:53:36 -0600402 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")
Masahiro Yamadaee860c62014-07-18 14:23:20 +0900407 return
Peter Tyser21818302015-01-26 11:42:21 -0600408 cc = BuildEmailList(list(set(series.get('cc')) - set(series.get('to'))),
409 '--cc', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000410 if self_only:
Simon Glassa1318f72013-03-26 13:09:42 +0000411 to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
Simon Glass0d24de92012-01-14 15:12:45 +0000412 cc = []
413 cmd = ['git', 'send-email', '--annotate']
Simon Glassa60aedf2018-06-19 09:56:07 -0600414 if smtp_server:
415 cmd.append('--smtp-server=%s' % smtp_server)
Doug Anderson6d819922013-03-17 10:31:04 +0000416 if in_reply_to:
Simon Glassf6a6aaf2019-05-14 15:53:54 -0600417 cmd.append('--in-reply-to="%s"' % tools.FromUnicode(in_reply_to))
Mateusz Kulikowski27067a42016-01-14 20:37:41 +0100418 if thread:
419 cmd.append('--thread')
Doug Anderson6d819922013-03-17 10:31:04 +0000420
Simon Glass0d24de92012-01-14 15:12:45 +0000421 cmd += to
422 cmd += cc
423 cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
424 if cover_fname:
425 cmd.append(cover_fname)
426 cmd += args
Simon Glass2df3a012017-05-29 15:31:25 -0600427 cmdstr = ' '.join(cmd)
Simon Glass0d24de92012-01-14 15:12:45 +0000428 if not dry_run:
Simon Glass2df3a012017-05-29 15:31:25 -0600429 os.system(cmdstr)
430 return cmdstr
Simon Glass0d24de92012-01-14 15:12:45 +0000431
432
Simon Glassa1318f72013-03-26 13:09:42 +0000433def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
Simon Glass0d24de92012-01-14 15:12:45 +0000434 """If an email address is an alias, look it up and return the full name
435
436 TODO: Why not just use git's own alias feature?
437
438 Args:
439 lookup_name: Alias or email address to look up
Simon Glassa1318f72013-03-26 13:09:42 +0000440 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.
Simon Glass0d24de92012-01-14 15:12:45 +0000443
444 Returns:
445 tuple:
446 list containing a list of email addresses
447
448 Raises:
449 OSError if a recursive alias reference was found
450 ValueError if an alias was not found
451
452 >>> alias = {}
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):
470 ...
471 ValueError: Alias 'odd' not found
472 >>> LookupEmail('loop', alias)
473 Traceback (most recent call last):
474 ...
475 OSError: Recursive email alias at 'other'
Simon Glassa1318f72013-03-26 13:09:42 +0000476 >>> LookupEmail('odd', alias, raise_on_error=False)
Simon Glasse752edc2014-08-28 09:43:35 -0600477 Alias 'odd' not found
Simon Glassa1318f72013-03-26 13:09:42 +0000478 []
479 >>> # In this case the loop part will effectively be ignored.
480 >>> LookupEmail('loop', alias, raise_on_error=False)
Simon Glasse752edc2014-08-28 09:43:35 -0600481 Recursive email alias at 'other'
482 Recursive email alias at 'john'
483 Recursive email alias at 'mary'
Simon Glassa1318f72013-03-26 13:09:42 +0000484 ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
Simon Glass0d24de92012-01-14 15:12:45 +0000485 """
486 if not alias:
487 alias = settings.alias
488 lookup_name = lookup_name.strip()
489 if '@' in lookup_name: # Perhaps a real email address
490 return [lookup_name]
491
492 lookup_name = lookup_name.lower()
Simon Glassa1318f72013-03-26 13:09:42 +0000493 col = terminal.Color()
Simon Glass0d24de92012-01-14 15:12:45 +0000494
495 out_list = []
Simon Glassa1318f72013-03-26 13:09:42 +0000496 if level > 10:
497 msg = "Recursive email alias at '%s'" % lookup_name
498 if raise_on_error:
Paul Burtonac3fde92016-09-27 16:03:51 +0100499 raise OSError(msg)
Simon Glassa1318f72013-03-26 13:09:42 +0000500 else:
Paul Burtona920a172016-09-27 16:03:50 +0100501 print(col.Color(col.RED, msg))
Simon Glassa1318f72013-03-26 13:09:42 +0000502 return out_list
503
Simon Glass0d24de92012-01-14 15:12:45 +0000504 if lookup_name:
505 if not lookup_name in alias:
Simon Glassa1318f72013-03-26 13:09:42 +0000506 msg = "Alias '%s' not found" % lookup_name
507 if raise_on_error:
Paul Burtonac3fde92016-09-27 16:03:51 +0100508 raise ValueError(msg)
Simon Glassa1318f72013-03-26 13:09:42 +0000509 else:
Paul Burtona920a172016-09-27 16:03:50 +0100510 print(col.Color(col.RED, msg))
Simon Glassa1318f72013-03-26 13:09:42 +0000511 return out_list
Simon Glass0d24de92012-01-14 15:12:45 +0000512 for item in alias[lookup_name]:
Simon Glassa1318f72013-03-26 13:09:42 +0000513 todo = LookupEmail(item, alias, raise_on_error, level + 1)
Simon Glass0d24de92012-01-14 15:12:45 +0000514 for new_item in todo:
515 if not new_item in out_list:
516 out_list.append(new_item)
517
Paul Burtona920a172016-09-27 16:03:50 +0100518 #print("No match for alias '%s'" % lookup_name)
Simon Glass0d24de92012-01-14 15:12:45 +0000519 return out_list
520
521def GetTopLevel():
522 """Return name of top-level directory for this git repo.
523
524 Returns:
525 Full path to git top-level directory
526
527 This test makes sure that we are running tests in the right subdir
528
Doug Andersona9700482012-11-26 15:21:40 +0000529 >>> os.path.realpath(os.path.dirname(__file__)) == \
530 os.path.join(GetTopLevel(), 'tools', 'patman')
Simon Glass0d24de92012-01-14 15:12:45 +0000531 True
532 """
533 return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
534
535def GetAliasFile():
536 """Gets the name of the git alias file.
537
538 Returns:
539 Filename of git alias file, or None if none
540 """
Simon Glassdc191502012-12-15 10:42:05 +0000541 fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
542 raise_on_error=False)
Simon Glass0d24de92012-01-14 15:12:45 +0000543 if fname:
544 fname = os.path.join(GetTopLevel(), fname.strip())
545 return fname
546
Vikram Narayanan87d65552012-05-23 09:01:06 +0000547def GetDefaultUserName():
548 """Gets the user.name from .gitconfig file.
549
550 Returns:
551 User name found in .gitconfig file, or None if none
552 """
553 uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
554 return uname
555
556def GetDefaultUserEmail():
557 """Gets the user.email from the global .gitconfig file.
558
559 Returns:
560 User's email found in .gitconfig file, or None if none
561 """
562 uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
563 return uemail
564
Wu, Josh3871cd82015-04-15 10:25:18 +0800565def GetDefaultSubjectPrefix():
566 """Gets the format.subjectprefix from local .git/config file.
567
568 Returns:
569 Subject prefix found in local .git/config file, or None if none
570 """
571 sub_prefix = command.OutputOneLine('git', 'config', 'format.subjectprefix',
572 raise_on_error=False)
573
574 return sub_prefix
575
Simon Glass0d24de92012-01-14 15:12:45 +0000576def Setup():
577 """Set up git utils, by reading the alias files."""
Simon Glass0d24de92012-01-14 15:12:45 +0000578 # Check for a git alias file also
Simon Glass0b703db2014-08-28 09:43:45 -0600579 global use_no_decorate
580
Simon Glass0d24de92012-01-14 15:12:45 +0000581 alias_fname = GetAliasFile()
582 if alias_fname:
583 settings.ReadGitAliases(alias_fname)
Simon Glasse49f14a2014-08-09 15:33:11 -0600584 cmd = LogCmd(None, count=0)
585 use_no_decorate = (command.RunPipe([cmd], raise_on_error=False)
586 .return_code == 0)
Simon Glass0d24de92012-01-14 15:12:45 +0000587
Simon Glass5f6a1c42012-12-15 10:42:07 +0000588def GetHead():
589 """Get the hash of the current HEAD
590
591 Returns:
592 Hash of HEAD
593 """
594 return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
595
Simon Glass0d24de92012-01-14 15:12:45 +0000596if __name__ == "__main__":
597 import doctest
598
599 doctest.testmod()