patman: cosmetic: Fix PEP 8 warnings for the gitutil module.
[platform/kernel/u-boot.git] / tools / patman / gitutil.py
1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2011 The Chromium OS Authors.
3 #
4
5 import os
6 import sys
7
8 from patman import command
9 from patman import settings
10 from patman import terminal
11
12 # True to use --no-decorate - we check this in setup()
13 use_no_decorate = True
14
15
16 def log_cmd(commit_range, git_dir=None, oneline=False, reverse=False,
17             count=None):
18     """Create a command to perform a 'git log'
19
20     Args:
21         commit_range: Range expression to use for log, None for none
22         git_dir: Path to git repository (None to use default)
23         oneline: True to use --oneline, else False
24         reverse: True to reverse the log (--reverse)
25         count: Number of commits to list, or None for no limit
26     Return:
27         List containing command and arguments to run
28     """
29     cmd = ['git']
30     if git_dir:
31         cmd += ['--git-dir', git_dir]
32     cmd += ['--no-pager', 'log', '--no-color']
33     if oneline:
34         cmd.append('--oneline')
35     if use_no_decorate:
36         cmd.append('--no-decorate')
37     if reverse:
38         cmd.append('--reverse')
39     if count is not None:
40         cmd.append('-n%d' % count)
41     if commit_range:
42         cmd.append(commit_range)
43
44     # Add this in case we have a branch with the same name as a directory.
45     # This avoids messages like this, for example:
46     #   fatal: ambiguous argument 'test': both revision and filename
47     cmd.append('--')
48     return cmd
49
50
51 def count_commits_to_branch(branch):
52     """Returns number of commits between HEAD and the tracking branch.
53
54     This looks back to the tracking branch and works out the number of commits
55     since then.
56
57     Args:
58         branch: Branch to count from (None for current branch)
59
60     Return:
61         Number of patches that exist on top of the branch
62     """
63     if branch:
64         us, msg = get_upstream('.git', branch)
65         rev_range = '%s..%s' % (us, branch)
66     else:
67         rev_range = '@{upstream}..'
68     pipe = [log_cmd(rev_range, oneline=True)]
69     result = command.run_pipe(pipe, capture=True, capture_stderr=True,
70                               oneline=True, raise_on_error=False)
71     if result.return_code:
72         raise ValueError('Failed to determine upstream: %s' %
73                          result.stderr.strip())
74     patch_count = len(result.stdout.splitlines())
75     return patch_count
76
77
78 def name_revision(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.run_pipe([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
94
95 def guess_upstream(git_dir, branch):
96     """Tries to guess the upstream for a branch
97
98     This lists out top commits on a branch and tries to find a suitable
99     upstream. It does this by looking for the first commit where
100     'git name-rev' returns a plain branch name, with no ! or ^ modifiers.
101
102     Args:
103         git_dir: Git directory containing repo
104         branch: Name of branch
105
106     Returns:
107         Tuple:
108             Name of upstream branch (e.g. 'upstream/master') or None if none
109             Warning/error message, or None if none
110     """
111     pipe = [log_cmd(branch, git_dir=git_dir, oneline=True, count=100)]
112     result = command.run_pipe(pipe, capture=True, capture_stderr=True,
113                               raise_on_error=False)
114     if result.return_code:
115         return None, "Branch '%s' not found" % branch
116     for line in result.stdout.splitlines()[1:]:
117         commit_hash = line.split(' ')[0]
118         name = name_revision(commit_hash)
119         if '~' not in name and '^' not in name:
120             if name.startswith('remotes/'):
121                 name = name[8:]
122             return name, "Guessing upstream as '%s'" % name
123     return None, "Cannot find a suitable upstream for branch '%s'" % branch
124
125
126 def get_upstream(git_dir, branch):
127     """Returns the name of the upstream for a branch
128
129     Args:
130         git_dir: Git directory containing repo
131         branch: Name of branch
132
133     Returns:
134         Tuple:
135             Name of upstream branch (e.g. 'upstream/master') or None if none
136             Warning/error message, or None if none
137     """
138     try:
139         remote = command.output_one_line('git', '--git-dir', git_dir, 'config',
140                                          'branch.%s.remote' % branch)
141         merge = command.output_one_line('git', '--git-dir', git_dir, 'config',
142                                         'branch.%s.merge' % branch)
143     except Exception:
144         upstream, msg = guess_upstream(git_dir, branch)
145         return upstream, msg
146
147     if remote == '.':
148         return merge, None
149     elif remote and merge:
150         leaf = merge.split('/')[-1]
151         return '%s/%s' % (remote, leaf), None
152     else:
153         raise ValueError("Cannot determine upstream branch for branch "
154                          "'%s' remote='%s', merge='%s'"
155                          % (branch, remote, merge))
156
157
158 def get_range_in_branch(git_dir, branch, include_upstream=False):
159     """Returns an expression for the commits in the given branch.
160
161     Args:
162         git_dir: Directory containing git repo
163         branch: Name of branch
164     Return:
165         Expression in the form 'upstream..branch' which can be used to
166         access the commits. If the branch does not exist, returns None.
167     """
168     upstream, msg = get_upstream(git_dir, branch)
169     if not upstream:
170         return None, msg
171     rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
172     return rstr, msg
173
174
175 def count_commits_in_range(git_dir, range_expr):
176     """Returns the number of commits in the given range.
177
178     Args:
179         git_dir: Directory containing git repo
180         range_expr: Range to check
181     Return:
182         Number of patches that exist in the supplied range or None if none
183         were found
184     """
185     pipe = [log_cmd(range_expr, git_dir=git_dir, oneline=True)]
186     result = command.run_pipe(pipe, capture=True, capture_stderr=True,
187                               raise_on_error=False)
188     if result.return_code:
189         return None, "Range '%s' not found or is invalid" % range_expr
190     patch_count = len(result.stdout.splitlines())
191     return patch_count, None
192
193
194 def count_commits_in_branch(git_dir, branch, include_upstream=False):
195     """Returns the number of commits in the given branch.
196
197     Args:
198         git_dir: Directory containing git repo
199         branch: Name of branch
200     Return:
201         Number of patches that exist on top of the branch, or None if the
202         branch does not exist.
203     """
204     range_expr, msg = get_range_in_branch(git_dir, branch, include_upstream)
205     if not range_expr:
206         return None, msg
207     return count_commits_in_range(git_dir, range_expr)
208
209
210 def count_commits(commit_range):
211     """Returns the number of commits in the given range.
212
213     Args:
214         commit_range: Range of commits to count (e.g. 'HEAD..base')
215     Return:
216         Number of patches that exist on top of the branch
217     """
218     pipe = [log_cmd(commit_range, oneline=True),
219             ['wc', '-l']]
220     stdout = command.run_pipe(pipe, capture=True, oneline=True).stdout
221     patch_count = int(stdout)
222     return patch_count
223
224
225 def checkout(commit_hash, git_dir=None, work_tree=None, force=False):
226     """Checkout the selected commit for this build
227
228     Args:
229         commit_hash: Commit hash to check out
230     """
231     pipe = ['git']
232     if git_dir:
233         pipe.extend(['--git-dir', git_dir])
234     if work_tree:
235         pipe.extend(['--work-tree', work_tree])
236     pipe.append('checkout')
237     if force:
238         pipe.append('-f')
239     pipe.append(commit_hash)
240     result = command.run_pipe([pipe], capture=True, raise_on_error=False,
241                               capture_stderr=True)
242     if result.return_code != 0:
243         raise OSError('git checkout (%s): %s' % (pipe, result.stderr))
244
245
246 def clone(git_dir, output_dir):
247     """Checkout the selected commit for this build
248
249     Args:
250         commit_hash: Commit hash to check out
251     """
252     pipe = ['git', 'clone', git_dir, '.']
253     result = command.run_pipe([pipe], capture=True, cwd=output_dir,
254                               capture_stderr=True)
255     if result.return_code != 0:
256         raise OSError('git clone: %s' % result.stderr)
257
258
259 def fetch(git_dir=None, work_tree=None):
260     """Fetch from the origin repo
261
262     Args:
263         commit_hash: Commit hash to check out
264     """
265     pipe = ['git']
266     if git_dir:
267         pipe.extend(['--git-dir', git_dir])
268     if work_tree:
269         pipe.extend(['--work-tree', work_tree])
270     pipe.append('fetch')
271     result = command.run_pipe([pipe], capture=True, capture_stderr=True)
272     if result.return_code != 0:
273         raise OSError('git fetch: %s' % result.stderr)
274
275
276 def check_worktree_is_available(git_dir):
277     """Check if git-worktree functionality is available
278
279     Args:
280         git_dir: The repository to test in
281
282     Returns:
283         True if git-worktree commands will work, False otherwise.
284     """
285     pipe = ['git', '--git-dir', git_dir, 'worktree', 'list']
286     result = command.run_pipe([pipe], capture=True, capture_stderr=True,
287                               raise_on_error=False)
288     return result.return_code == 0
289
290
291 def add_worktree(git_dir, output_dir, commit_hash=None):
292     """Create and checkout a new git worktree for this build
293
294     Args:
295         git_dir: The repository to checkout the worktree from
296         output_dir: Path for the new worktree
297         commit_hash: Commit hash to checkout
298     """
299     # We need to pass --detach to avoid creating a new branch
300     pipe = ['git', '--git-dir', git_dir, 'worktree', 'add', '.', '--detach']
301     if commit_hash:
302         pipe.append(commit_hash)
303     result = command.run_pipe([pipe], capture=True, cwd=output_dir,
304                               capture_stderr=True)
305     if result.return_code != 0:
306         raise OSError('git worktree add: %s' % result.stderr)
307
308
309 def prune_worktrees(git_dir):
310     """Remove administrative files for deleted worktrees
311
312     Args:
313         git_dir: The repository whose deleted worktrees should be pruned
314     """
315     pipe = ['git', '--git-dir', git_dir, 'worktree', 'prune']
316     result = command.run_pipe([pipe], capture=True, capture_stderr=True)
317     if result.return_code != 0:
318         raise OSError('git worktree prune: %s' % result.stderr)
319
320
321 def create_patches(branch, start, count, ignore_binary, series, signoff=True):
322     """Create a series of patches from the top of the current branch.
323
324     The patch files are written to the current directory using
325     git format-patch.
326
327     Args:
328         branch: Branch to create patches from (None for current branch)
329         start: Commit to start from: 0=HEAD, 1=next one, etc.
330         count: number of commits to include
331         ignore_binary: Don't generate patches for binary files
332         series: Series object for this series (set of patches)
333     Return:
334         Filename of cover letter (None if none)
335         List of filenames of patch files
336     """
337     cmd = ['git', 'format-patch', '-M']
338     if signoff:
339         cmd.append('--signoff')
340     if ignore_binary:
341         cmd.append('--no-binary')
342     if series.get('cover'):
343         cmd.append('--cover-letter')
344     prefix = series.GetPatchPrefix()
345     if prefix:
346         cmd += ['--subject-prefix=%s' % prefix]
347     brname = branch or 'HEAD'
348     cmd += ['%s~%d..%s~%d' % (brname, start + count, brname, start)]
349
350     stdout = command.run_list(cmd)
351     files = stdout.splitlines()
352
353     # We have an extra file if there is a cover letter
354     if series.get('cover'):
355         return files[0], files[1:]
356     else:
357         return None, files
358
359
360 def build_email_list(in_list, tag=None, alias=None, warn_on_error=True):
361     """Build a list of email addresses based on an input list.
362
363     Takes a list of email addresses and aliases, and turns this into a list
364     of only email address, by resolving any aliases that are present.
365
366     If the tag is given, then each email address is prepended with this
367     tag and a space. If the tag starts with a minus sign (indicating a
368     command line parameter) then the email address is quoted.
369
370     Args:
371         in_list:        List of aliases/email addresses
372         tag:            Text to put before each address
373         alias:          Alias dictionary
374         warn_on_error: True to raise an error when an alias fails to match,
375                 False to just print a message.
376
377     Returns:
378         List of email addresses
379
380     >>> alias = {}
381     >>> alias['fred'] = ['f.bloggs@napier.co.nz']
382     >>> alias['john'] = ['j.bloggs@napier.co.nz']
383     >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
384     >>> alias['boys'] = ['fred', ' john']
385     >>> alias['all'] = ['fred ', 'john', '   mary   ']
386     >>> build_email_list(['john', 'mary'], None, alias)
387     ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
388     >>> build_email_list(['john', 'mary'], '--to', alias)
389     ['--to "j.bloggs@napier.co.nz"', \
390 '--to "Mary Poppins <m.poppins@cloud.net>"']
391     >>> build_email_list(['john', 'mary'], 'Cc', alias)
392     ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
393     """
394     quote = '"' if tag and tag[0] == '-' else ''
395     raw = []
396     for item in in_list:
397         raw += lookup_email(item, alias, warn_on_error=warn_on_error)
398     result = []
399     for item in raw:
400         if item not in result:
401             result.append(item)
402     if tag:
403         return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
404     return result
405
406
407 def check_suppress_cc_config():
408     """Check if sendemail.suppresscc is configured correctly.
409
410     Returns:
411         True if the option is configured correctly, False otherwise.
412     """
413     suppresscc = command.output_one_line(
414         'git', 'config', 'sendemail.suppresscc', raise_on_error=False)
415
416     # Other settings should be fine.
417     if suppresscc == 'all' or suppresscc == 'cccmd':
418         col = terminal.Color()
419
420         print((col.build(col.RED, "error") +
421                ": git config sendemail.suppresscc set to %s\n"
422                % (suppresscc)) +
423               "  patman needs --cc-cmd to be run to set the cc list.\n" +
424               "  Please run:\n" +
425               "    git config --unset sendemail.suppresscc\n" +
426               "  Or read the man page:\n" +
427               "    git send-email --help\n" +
428               "  and set an option that runs --cc-cmd\n")
429         return False
430
431     return True
432
433
434 def email_patches(series, cover_fname, args, dry_run, warn_on_error, cc_fname,
435                   self_only=False, alias=None, in_reply_to=None, thread=False,
436                   smtp_server=None):
437     """Email a patch series.
438
439     Args:
440         series: Series object containing destination info
441         cover_fname: filename of cover letter
442         args: list of filenames of patch files
443         dry_run: Just return the command that would be run
444         warn_on_error: True to print a warning when an alias fails to match,
445                 False to ignore it.
446         cc_fname: Filename of Cc file for per-commit Cc
447         self_only: True to just email to yourself as a test
448         in_reply_to: If set we'll pass this to git as --in-reply-to.
449             Should be a message ID that this is in reply to.
450         thread: True to add --thread to git send-email (make
451             all patches reply to cover-letter or first patch in series)
452         smtp_server: SMTP server to use to send patches
453
454     Returns:
455         Git command that was/would be run
456
457     # For the duration of this doctest pretend that we ran patman with ./patman
458     >>> _old_argv0 = sys.argv[0]
459     >>> sys.argv[0] = './patman'
460
461     >>> alias = {}
462     >>> alias['fred'] = ['f.bloggs@napier.co.nz']
463     >>> alias['john'] = ['j.bloggs@napier.co.nz']
464     >>> alias['mary'] = ['m.poppins@cloud.net']
465     >>> alias['boys'] = ['fred', ' john']
466     >>> alias['all'] = ['fred ', 'john', '   mary   ']
467     >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
468     >>> series = {}
469     >>> series['to'] = ['fred']
470     >>> series['cc'] = ['mary']
471     >>> email_patches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
472             False, alias)
473     'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
474 "m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" cover p1 p2'
475     >>> email_patches(series, None, ['p1'], True, True, 'cc-fname', False, \
476             alias)
477     'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
478 "m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" p1'
479     >>> series['cc'] = ['all']
480     >>> email_patches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
481             True, alias)
482     'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
483 send --cc-cmd cc-fname" cover p1 p2'
484     >>> email_patches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
485             False, alias)
486     'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
487 "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
488 "m.poppins@cloud.net" --cc-cmd "./patman send --cc-cmd cc-fname" cover p1 p2'
489
490     # Restore argv[0] since we clobbered it.
491     >>> sys.argv[0] = _old_argv0
492     """
493     to = build_email_list(series.get('to'), '--to', alias, warn_on_error)
494     if not to:
495         git_config_to = command.output('git', 'config', 'sendemail.to',
496                                        raise_on_error=False)
497         if not git_config_to:
498             print("No recipient.\n"
499                   "Please add something like this to a commit\n"
500                   "Series-to: Fred Bloggs <f.blogs@napier.co.nz>\n"
501                   "Or do something like this\n"
502                   "git config sendemail.to u-boot@lists.denx.de")
503             return
504     cc = build_email_list(list(set(series.get('cc')) - set(series.get('to'))),
505                           '--cc', alias, warn_on_error)
506     if self_only:
507         to = build_email_list([os.getenv('USER')], '--to',
508                               alias, warn_on_error)
509         cc = []
510     cmd = ['git', 'send-email', '--annotate']
511     if smtp_server:
512         cmd.append('--smtp-server=%s' % smtp_server)
513     if in_reply_to:
514         cmd.append('--in-reply-to="%s"' % in_reply_to)
515     if thread:
516         cmd.append('--thread')
517
518     cmd += to
519     cmd += cc
520     cmd += ['--cc-cmd', '"%s send --cc-cmd %s"' % (sys.argv[0], cc_fname)]
521     if cover_fname:
522         cmd.append(cover_fname)
523     cmd += args
524     cmdstr = ' '.join(cmd)
525     if not dry_run:
526         os.system(cmdstr)
527     return cmdstr
528
529
530 def lookup_email(lookup_name, alias=None, warn_on_error=True, level=0):
531     """If an email address is an alias, look it up and return the full name
532
533     TODO: Why not just use git's own alias feature?
534
535     Args:
536         lookup_name: Alias or email address to look up
537         alias: Dictionary containing aliases (None to use settings default)
538         warn_on_error: True to print a warning when an alias fails to match,
539                 False to ignore it.
540
541     Returns:
542         tuple:
543             list containing a list of email addresses
544
545     Raises:
546         OSError if a recursive alias reference was found
547         ValueError if an alias was not found
548
549     >>> alias = {}
550     >>> alias['fred'] = ['f.bloggs@napier.co.nz']
551     >>> alias['john'] = ['j.bloggs@napier.co.nz']
552     >>> alias['mary'] = ['m.poppins@cloud.net']
553     >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
554     >>> alias['all'] = ['fred ', 'john', '   mary   ']
555     >>> alias['loop'] = ['other', 'john', '   mary   ']
556     >>> alias['other'] = ['loop', 'john', '   mary   ']
557     >>> lookup_email('mary', alias)
558     ['m.poppins@cloud.net']
559     >>> lookup_email('arthur.wellesley@howe.ro.uk', alias)
560     ['arthur.wellesley@howe.ro.uk']
561     >>> lookup_email('boys', alias)
562     ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
563     >>> lookup_email('all', alias)
564     ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
565     >>> lookup_email('odd', alias)
566     Alias 'odd' not found
567     []
568     >>> lookup_email('loop', alias)
569     Traceback (most recent call last):
570     ...
571     OSError: Recursive email alias at 'other'
572     >>> lookup_email('odd', alias, warn_on_error=False)
573     []
574     >>> # In this case the loop part will effectively be ignored.
575     >>> lookup_email('loop', alias, warn_on_error=False)
576     Recursive email alias at 'other'
577     Recursive email alias at 'john'
578     Recursive email alias at 'mary'
579     ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
580     """
581     if not alias:
582         alias = settings.alias
583     lookup_name = lookup_name.strip()
584     if '@' in lookup_name:      # Perhaps a real email address
585         return [lookup_name]
586
587     lookup_name = lookup_name.lower()
588     col = terminal.Color()
589
590     out_list = []
591     if level > 10:
592         msg = "Recursive email alias at '%s'" % lookup_name
593         if warn_on_error:
594             raise OSError(msg)
595         else:
596             print(col.build(col.RED, msg))
597             return out_list
598
599     if lookup_name:
600         if lookup_name not in alias:
601             msg = "Alias '%s' not found" % lookup_name
602             if warn_on_error:
603                 print(col.build(col.RED, msg))
604             return out_list
605         for item in alias[lookup_name]:
606             todo = lookup_email(item, alias, warn_on_error, level + 1)
607             for new_item in todo:
608                 if new_item not in out_list:
609                     out_list.append(new_item)
610
611     return out_list
612
613
614 def get_top_level():
615     """Return name of top-level directory for this git repo.
616
617     Returns:
618         Full path to git top-level directory
619
620     This test makes sure that we are running tests in the right subdir
621
622     >>> os.path.realpath(os.path.dirname(__file__)) == \
623             os.path.join(get_top_level(), 'tools', 'patman')
624     True
625     """
626     return command.output_one_line('git', 'rev-parse', '--show-toplevel')
627
628
629 def get_alias_file():
630     """Gets the name of the git alias file.
631
632     Returns:
633         Filename of git alias file, or None if none
634     """
635     fname = command.output_one_line('git', 'config', 'sendemail.aliasesfile',
636                                     raise_on_error=False)
637     if not fname:
638         return None
639
640     fname = os.path.expanduser(fname.strip())
641     if os.path.isabs(fname):
642         return fname
643
644     return os.path.join(get_top_level(), fname)
645
646
647 def get_default_user_name():
648     """Gets the user.name from .gitconfig file.
649
650     Returns:
651         User name found in .gitconfig file, or None if none
652     """
653     uname = command.output_one_line('git', 'config', '--global', 'user.name')
654     return uname
655
656
657 def get_default_user_email():
658     """Gets the user.email from the global .gitconfig file.
659
660     Returns:
661         User's email found in .gitconfig file, or None if none
662     """
663     uemail = command.output_one_line('git', 'config', '--global', 'user.email')
664     return uemail
665
666
667 def get_default_subject_prefix():
668     """Gets the format.subjectprefix from local .git/config file.
669
670     Returns:
671         Subject prefix found in local .git/config file, or None if none
672     """
673     sub_prefix = command.output_one_line(
674         'git', 'config', 'format.subjectprefix', raise_on_error=False)
675
676     return sub_prefix
677
678
679 def setup():
680     """Set up git utils, by reading the alias files."""
681     # Check for a git alias file also
682     global use_no_decorate
683
684     alias_fname = get_alias_file()
685     if alias_fname:
686         settings.ReadGitAliases(alias_fname)
687     cmd = log_cmd(None, count=0)
688     use_no_decorate = (command.run_pipe([cmd], raise_on_error=False)
689                        .return_code == 0)
690
691
692 def get_head():
693     """Get the hash of the current HEAD
694
695     Returns:
696         Hash of HEAD
697     """
698     return command.output_one_line('git', 'show', '-s', '--pretty=format:%H')
699
700
701 if __name__ == "__main__":
702     import doctest
703
704     doctest.testmod()