blob: da63d7af7272efa4fc1f75ab43648bd017ebc860 [file] [log] [blame]
Josip Sokcevic4de5dea2022-03-23 21:15:14 +00001#!/usr/bin/env python3
iannucci@chromium.orga112f032014-03-13 07:47:50 +00002# Copyright 2014 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
anatoly techtonik222840f2017-04-15 16:25:57 +03006"""Print dependency tree of branches in local repo.
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00007
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00008Example:
Josip Sokcevic9c0dc302020-11-20 18:41:25 +00009origin/main
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000010 cool_feature
11 dependent_feature
12 other_dependent_feature
13 other_feature
14
15Branches are colorized as follows:
16 * Red - a remote branch (usually the root of all local branches)
17 * Cyan - a local branch which is the same as HEAD
18 * Note that multiple branches may be Cyan, if they are all on the same
19 commit, and you have that commit checked out.
20 * Green - a local branch
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +000021 * Blue - a 'branch-heads' branch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000022 * Magenta - a tag
23 * Magenta '{NO UPSTREAM}' - If you have local branches which do not track any
24 upstream, then you will see this.
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000025"""
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000026
Raul Tambre80ee78e2019-05-06 22:41:05 +000027from __future__ import print_function
28
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000029import argparse
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000030import collections
Josip Sokcevic306b03b2022-02-23 03:25:23 +000031import metrics
iannucci@chromium.org0703ea22016-04-01 01:02:42 +000032import os
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +000033import subprocess2
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000034import sys
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000035
calamity@chromium.org745ffa62014-09-08 01:03:19 +000036from git_common import current_branch, upstream, tags, get_branches_info
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +000037from git_common import get_git_version, MIN_UPSTREAM_TRACK_GIT_VERSION, hash_one
borenet@google.com09156ec2015-03-26 14:10:06 +000038from git_common import run
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000039
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000040import setup_color
41
42from third_party.colorama import Fore, Style
43
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000044DEFAULT_SEPARATOR = ' ' * 4
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000045
46
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000047class OutputManager(object):
48 """Manages a number of OutputLines and formats them into aligned columns."""
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000049
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000050 def __init__(self):
51 self.lines = []
52 self.nocolor = False
53 self.max_column_lengths = []
54 self.num_columns = None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000055
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000056 def append(self, line):
57 # All lines must have the same number of columns.
58 if not self.num_columns:
59 self.num_columns = len(line.columns)
60 self.max_column_lengths = [0] * self.num_columns
61 assert self.num_columns == len(line.columns)
62
63 if self.nocolor:
64 line.colors = [''] * self.num_columns
65
66 self.lines.append(line)
67
68 # Update maximum column lengths.
69 for i, col in enumerate(line.columns):
70 self.max_column_lengths[i] = max(self.max_column_lengths[i], len(col))
71
72 def as_formatted_string(self):
73 return '\n'.join(
74 l.as_padded_string(self.max_column_lengths) for l in self.lines)
75
76
77class OutputLine(object):
78 """A single line of data.
79
80 This consists of an equal number of columns, colors and separators."""
81
82 def __init__(self):
83 self.columns = []
84 self.separators = []
85 self.colors = []
86
87 def append(self, data, separator=DEFAULT_SEPARATOR, color=Fore.WHITE):
88 self.columns.append(data)
89 self.separators.append(separator)
90 self.colors.append(color)
91
92 def as_padded_string(self, max_column_lengths):
93 """"Returns the data as a string with each column padded to
94 |max_column_lengths|."""
95 output_string = ''
96 for i, (color, data, separator) in enumerate(
97 zip(self.colors, self.columns, self.separators)):
98 if max_column_lengths[i] == 0:
99 continue
100
101 padding = (max_column_lengths[i] - len(data)) * ' '
102 output_string += color + data + padding + separator
103
104 return output_string.rstrip()
105
106
107class BranchMapper(object):
108 """A class which constructs output representing the tree's branch structure.
109
110 Attributes:
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000111 __branches_info: a map of branches to their BranchesInfo objects which
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000112 consist of the branch hash, upstream and ahead/behind status.
113 __gone_branches: a set of upstreams which are not fetchable by git"""
114
115 def __init__(self):
116 self.verbosity = 0
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000117 self.maxjobs = 0
borenet@google.com09156ec2015-03-26 14:10:06 +0000118 self.show_subject = False
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000119 self.output = OutputManager()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000120 self.__gone_branches = set()
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000121 self.__branches_info = None
122 self.__parent_map = collections.defaultdict(list)
123 self.__current_branch = None
124 self.__current_hash = None
125 self.__tag_set = None
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000126 self.__status_info = {}
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000127
128 def start(self):
129 self.__branches_info = get_branches_info(
130 include_tracking_status=self.verbosity >= 1)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000131 if (self.verbosity >= 2):
132 # Avoid heavy import unless necessary.
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000133 from git_cl import get_cl_statuses, color_for_status, Changelist
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000134
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000135 change_cls = [Changelist(branchref='refs/heads/'+b)
136 for b in self.__branches_info.keys() if b]
137 status_info = get_cl_statuses(change_cls,
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000138 fine_grained=self.verbosity > 2,
139 max_processes=self.maxjobs)
140
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000141 # This is a blocking get which waits for the remote CL status to be
142 # retrieved.
143 for cl, status in status_info:
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000144 self.__status_info[cl.GetBranch()] = (cl.GetIssueURL(short=True),
145 color_for_status(status), status)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000146
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000147 roots = set()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000148
149 # A map of parents to a list of their children.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000150 for branch, branch_info in self.__branches_info.items():
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000151 if not branch_info:
152 continue
153
154 parent = branch_info.upstream
Clemens Hammacher793183d2019-03-22 01:12:46 +0000155 if self.__check_cycle(branch):
156 continue
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000157 if not self.__branches_info[parent]:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000158 branch_upstream = upstream(branch)
159 # If git can't find the upstream, mark the upstream as gone.
160 if branch_upstream:
161 parent = branch_upstream
162 else:
163 self.__gone_branches.add(parent)
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000164 # A parent that isn't in the branches info is a root.
165 roots.add(parent)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000166
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000167 self.__parent_map[parent].append(branch)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000168
169 self.__current_branch = current_branch()
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000170 self.__current_hash = hash_one('HEAD', short=True)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000171 self.__tag_set = tags()
172
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000173 if roots:
174 for root in sorted(roots):
175 self.__append_branch(root)
176 else:
177 no_branches = OutputLine()
178 no_branches.append('No User Branches')
179 self.output.append(no_branches)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000180
Clemens Hammacher793183d2019-03-22 01:12:46 +0000181 def __check_cycle(self, branch):
182 # Maximum length of the cycle is `num_branches`. This limit avoids running
183 # into a cycle which does *not* contain `branch`.
184 num_branches = len(self.__branches_info)
185 cycle = [branch]
186 while len(cycle) < num_branches and self.__branches_info[cycle[-1]]:
187 parent = self.__branches_info[cycle[-1]].upstream
188 cycle.append(parent)
189 if parent == branch:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000190 print('Warning: Detected cycle in branches: {}'.format(
191 ' -> '.join(cycle)), file=sys.stderr)
Clemens Hammacher793183d2019-03-22 01:12:46 +0000192 return True
193 return False
194
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000195 def __is_invalid_parent(self, parent):
196 return not parent or parent in self.__gone_branches
197
198 def __color_for_branch(self, branch, branch_hash):
jsbell@google.com4f1fc352016-03-24 22:23:46 +0000199 if branch.startswith('origin/'):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000200 color = Fore.RED
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000201 elif branch.startswith('branch-heads'):
202 color = Fore.BLUE
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000203 elif self.__is_invalid_parent(branch) or branch in self.__tag_set:
204 color = Fore.MAGENTA
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000205 elif self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000206 color = Fore.CYAN
207 else:
208 color = Fore.GREEN
209
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000210 if branch_hash and self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000211 color += Style.BRIGHT
212 else:
213 color += Style.NORMAL
214
215 return color
216
217 def __append_branch(self, branch, depth=0):
218 """Recurses through the tree structure and appends an OutputLine to the
219 OutputManager for each branch."""
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000220 branch_info = self.__branches_info[branch]
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000221 if branch_info:
222 branch_hash = branch_info.hash
223 else:
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000224 try:
225 branch_hash = hash_one(branch, short=True)
226 except subprocess2.CalledProcessError:
227 branch_hash = None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000228
229 line = OutputLine()
230
231 # The branch name with appropriate indentation.
232 suffix = ''
233 if branch == self.__current_branch or (
234 self.__current_branch == 'HEAD' and branch == self.__current_hash):
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000235 suffix = ' *'
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000236 branch_string = branch
237 if branch in self.__gone_branches:
238 branch_string = '{%s:GONE}' % branch
239 if not branch:
240 branch_string = '{NO_UPSTREAM}'
241 main_string = ' ' * depth + branch_string + suffix
242 line.append(
243 main_string,
244 color=self.__color_for_branch(branch, branch_hash))
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000245
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000246 # The branch hash.
247 if self.verbosity >= 2:
248 line.append(branch_hash or '', separator=' ', color=Fore.RED)
249
250 # The branch tracking status.
251 if self.verbosity >= 1:
Gavin Mak8d7201b2020-09-17 19:21:38 +0000252 commits_string = ''
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000253 behind_string = ''
254 front_separator = ''
255 center_separator = ''
256 back_separator = ''
257 if branch_info and not self.__is_invalid_parent(branch_info.upstream):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000258 behind = branch_info.behind
Gavin Mak8d7201b2020-09-17 19:21:38 +0000259 commits = branch_info.commits
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000260
Gavin Mak8d7201b2020-09-17 19:21:38 +0000261 if commits:
262 commits_string = '%d commit' % commits
263 commits_string += 's' if commits > 1 else ' '
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000264 if behind:
265 behind_string = 'behind %d' % behind
266
Gavin Mak8d7201b2020-09-17 19:21:38 +0000267 if commits or behind:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000268 front_separator = '['
269 back_separator = ']'
270
Gavin Mak8d7201b2020-09-17 19:21:38 +0000271 if commits and behind:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000272 center_separator = '|'
273
274 line.append(front_separator, separator=' ')
Gavin Mak8d7201b2020-09-17 19:21:38 +0000275 line.append(commits_string, separator=' ', color=Fore.MAGENTA)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000276 line.append(center_separator, separator=' ')
277 line.append(behind_string, separator=' ', color=Fore.MAGENTA)
278 line.append(back_separator)
279
280 # The Rietveld issue associated with the branch.
281 if self.verbosity >= 2:
asanka97f39492016-07-18 18:16:40 -0700282 (url, color, status) = ('', '', '') if self.__is_invalid_parent(branch) \
283 else self.__status_info[branch]
284 if self.verbosity > 2:
285 line.append('{} ({})'.format(url, status) if url else '', color=color)
286 else:
287 line.append(url or '', color=color)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000288
borenet@google.com09156ec2015-03-26 14:10:06 +0000289 # The subject of the most recent commit on the branch.
290 if self.show_subject:
Aaron Gable6761b9d2017-08-28 12:23:40 -0700291 if branch:
292 line.append(run('log', '-n1', '--format=%s', branch, '--'))
293 else:
294 line.append('')
borenet@google.com09156ec2015-03-26 14:10:06 +0000295
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000296 self.output.append(line)
297
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000298 for child in sorted(self.__parent_map.pop(branch, ())):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000299 self.__append_branch(child, depth=depth + 1)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000300
301
anatoly techtonik222840f2017-04-15 16:25:57 +0300302def print_desc():
303 for line in __doc__.splitlines():
304 starpos = line.find('* ')
305 if starpos == -1 or '-' not in line:
306 print(line)
307 else:
308 _, color, rest = line.split(None, 2)
309 outline = line[:starpos+1]
310 outline += getattr(Fore, color.upper()) + " " + color + " " + Fore.RESET
311 outline += rest
312 print(outline)
313 print('')
314
Josip Sokcevic306b03b2022-02-23 03:25:23 +0000315@metrics.collector.collect_metrics('git map-branches')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000316def main(argv):
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000317 setup_color.init()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000318 if get_git_version() < MIN_UPSTREAM_TRACK_GIT_VERSION:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000319 print(
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000320 'This tool will not show all tracking information for git version '
321 'earlier than ' +
322 '.'.join(str(x) for x in MIN_UPSTREAM_TRACK_GIT_VERSION) +
Raul Tambre80ee78e2019-05-06 22:41:05 +0000323 '. Please consider upgrading.', file=sys.stderr)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000324
anatoly techtonik222840f2017-04-15 16:25:57 +0300325 if '-h' in argv:
326 print_desc()
327
328 parser = argparse.ArgumentParser()
Edward Lemur2bac03e2020-03-04 21:54:26 +0000329 parser.add_argument('-v', action='count', default=0,
Clemens Hammacher03640c72018-12-13 08:08:19 +0000330 help=('Pass once to show tracking info, '
331 'twice for hash and review url, '
332 'thrice for review status'))
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000333 parser.add_argument('--no-color', action='store_true', dest='nocolor',
334 help='Turn off colors.')
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000335 parser.add_argument(
336 '-j', '--maxjobs', action='store', type=int,
337 help='The number of jobs to use when retrieving review status')
borenet@google.com09156ec2015-03-26 14:10:06 +0000338 parser.add_argument('--show-subject', action='store_true',
339 dest='show_subject', help='Show the commit subject.')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000340
sbc@chromium.org013731e2015-02-26 18:28:43 +0000341 opts = parser.parse_args(argv)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000342
343 mapper = BranchMapper()
344 mapper.verbosity = opts.v
345 mapper.output.nocolor = opts.nocolor
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000346 mapper.maxjobs = opts.maxjobs
borenet@google.com09156ec2015-03-26 14:10:06 +0000347 mapper.show_subject = opts.show_subject
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000348 mapper.start()
Raul Tambre80ee78e2019-05-06 22:41:05 +0000349 print(mapper.output.as_formatted_string())
sbc@chromium.org013731e2015-02-26 18:28:43 +0000350 return 0
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000351
352if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000353 try:
Josip Sokcevic306b03b2022-02-23 03:25:23 +0000354 with metrics.collector.print_notice_and_exit():
355 sys.exit(main(sys.argv[1:]))
sbc@chromium.org013731e2015-02-26 18:28:43 +0000356 except KeyboardInterrupt:
357 sys.stderr.write('interrupted\n')
358 sys.exit(1)