blob: 2fb89a66c318a4a0e1789bfb7b47debe239344d6 [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
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000027import argparse
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000028import collections
Josip Sokcevic306b03b2022-02-23 03:25:23 +000029import metrics
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +000030import subprocess2
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000031import sys
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000032
calamity@chromium.org745ffa62014-09-08 01:03:19 +000033from git_common import current_branch, upstream, tags, get_branches_info
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +000034from git_common import get_git_version, MIN_UPSTREAM_TRACK_GIT_VERSION, hash_one
borenet@google.com09156ec2015-03-26 14:10:06 +000035from git_common import run
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000036
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000037import setup_color
38
39from third_party.colorama import Fore, Style
40
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000041DEFAULT_SEPARATOR = ' ' * 4
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000042
43
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000044class OutputManager(object):
45 """Manages a number of OutputLines and formats them into aligned columns."""
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000046
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000047 def __init__(self):
48 self.lines = []
49 self.nocolor = False
50 self.max_column_lengths = []
51 self.num_columns = None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000052
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000053 def append(self, line):
54 # All lines must have the same number of columns.
55 if not self.num_columns:
56 self.num_columns = len(line.columns)
57 self.max_column_lengths = [0] * self.num_columns
58 assert self.num_columns == len(line.columns)
59
60 if self.nocolor:
61 line.colors = [''] * self.num_columns
62
63 self.lines.append(line)
64
65 # Update maximum column lengths.
66 for i, col in enumerate(line.columns):
67 self.max_column_lengths[i] = max(self.max_column_lengths[i], len(col))
68
Orr Bernsteinb7e16d22023-07-14 11:00:55 +000069 def merge(self, other):
70 for line in other.lines:
71 self.append(line)
72
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000073 def as_formatted_string(self):
74 return '\n'.join(
75 l.as_padded_string(self.max_column_lengths) for l in self.lines)
76
77
78class OutputLine(object):
79 """A single line of data.
80
81 This consists of an equal number of columns, colors and separators."""
82
83 def __init__(self):
84 self.columns = []
85 self.separators = []
86 self.colors = []
87
88 def append(self, data, separator=DEFAULT_SEPARATOR, color=Fore.WHITE):
89 self.columns.append(data)
90 self.separators.append(separator)
91 self.colors.append(color)
92
93 def as_padded_string(self, max_column_lengths):
94 """"Returns the data as a string with each column padded to
95 |max_column_lengths|."""
96 output_string = ''
97 for i, (color, data, separator) in enumerate(
98 zip(self.colors, self.columns, self.separators)):
99 if max_column_lengths[i] == 0:
100 continue
101
102 padding = (max_column_lengths[i] - len(data)) * ' '
103 output_string += color + data + padding + separator
104
105 return output_string.rstrip()
106
107
108class BranchMapper(object):
109 """A class which constructs output representing the tree's branch structure.
110
111 Attributes:
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000112 __branches_info: a map of branches to their BranchesInfo objects which
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000113 consist of the branch hash, upstream and ahead/behind status.
114 __gone_branches: a set of upstreams which are not fetchable by git"""
115
116 def __init__(self):
117 self.verbosity = 0
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000118 self.maxjobs = 0
borenet@google.com09156ec2015-03-26 14:10:06 +0000119 self.show_subject = False
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000120 self.hide_dormant = False
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000121 self.output = OutputManager()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000122 self.__gone_branches = set()
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000123 self.__branches_info = None
124 self.__parent_map = collections.defaultdict(list)
125 self.__current_branch = None
126 self.__current_hash = None
127 self.__tag_set = None
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000128 self.__status_info = {}
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000129
130 def start(self):
131 self.__branches_info = get_branches_info(
132 include_tracking_status=self.verbosity >= 1)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000133 if (self.verbosity >= 2):
134 # Avoid heavy import unless necessary.
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000135 from git_cl import get_cl_statuses, color_for_status, Changelist
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000136
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000137 change_cls = [Changelist(branchref='refs/heads/'+b)
138 for b in self.__branches_info.keys() if b]
139 status_info = get_cl_statuses(change_cls,
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000140 fine_grained=self.verbosity > 2,
141 max_processes=self.maxjobs)
142
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000143 # This is a blocking get which waits for the remote CL status to be
144 # retrieved.
145 for cl, status in status_info:
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000146 self.__status_info[cl.GetBranch()] = (cl.GetIssueURL(short=True),
147 color_for_status(status), status)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000148
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000149 roots = set()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000150
151 # A map of parents to a list of their children.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000152 for branch, branch_info in self.__branches_info.items():
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000153 if not branch_info:
154 continue
155
156 parent = branch_info.upstream
Clemens Hammacher793183d2019-03-22 01:12:46 +0000157 if self.__check_cycle(branch):
158 continue
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000159 if not self.__branches_info[parent]:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000160 branch_upstream = upstream(branch)
161 # If git can't find the upstream, mark the upstream as gone.
162 if branch_upstream:
163 parent = branch_upstream
164 else:
165 self.__gone_branches.add(parent)
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000166 # A parent that isn't in the branches info is a root.
167 roots.add(parent)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000168
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000169 self.__parent_map[parent].append(branch)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000170
171 self.__current_branch = current_branch()
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000172 self.__current_hash = hash_one('HEAD', short=True)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000173 self.__tag_set = tags()
174
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000175 if roots:
176 for root in sorted(roots):
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000177 self.__append_branch(root, self.output)
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000178 else:
179 no_branches = OutputLine()
180 no_branches.append('No User Branches')
181 self.output.append(no_branches)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000182
Clemens Hammacher793183d2019-03-22 01:12:46 +0000183 def __check_cycle(self, branch):
184 # Maximum length of the cycle is `num_branches`. This limit avoids running
185 # into a cycle which does *not* contain `branch`.
186 num_branches = len(self.__branches_info)
187 cycle = [branch]
188 while len(cycle) < num_branches and self.__branches_info[cycle[-1]]:
189 parent = self.__branches_info[cycle[-1]].upstream
190 cycle.append(parent)
191 if parent == branch:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000192 print('Warning: Detected cycle in branches: {}'.format(
193 ' -> '.join(cycle)), file=sys.stderr)
Clemens Hammacher793183d2019-03-22 01:12:46 +0000194 return True
195 return False
196
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000197 def __is_invalid_parent(self, parent):
198 return not parent or parent in self.__gone_branches
199
200 def __color_for_branch(self, branch, branch_hash):
jsbell@google.com4f1fc352016-03-24 22:23:46 +0000201 if branch.startswith('origin/'):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000202 color = Fore.RED
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000203 elif branch.startswith('branch-heads'):
204 color = Fore.BLUE
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000205 elif self.__is_invalid_parent(branch) or branch in self.__tag_set:
206 color = Fore.MAGENTA
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000207 elif self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000208 color = Fore.CYAN
209 else:
210 color = Fore.GREEN
211
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000212 if branch_hash and self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000213 color += Style.BRIGHT
214 else:
215 color += Style.NORMAL
216
217 return color
218
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000219 def __is_dormant_branch(self, branch):
220 if '/' in branch:
221 return False
222
223 is_dormant = run('config',
224 '--get',
225 'branch.{}.dormant'.format(branch),
226 accepted_retcodes=[0, 1])
227 return is_dormant == 'true'
228
229 def __append_branch(self, branch, output, depth=0):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000230 """Recurses through the tree structure and appends an OutputLine to the
231 OutputManager for each branch."""
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000232 child_output = OutputManager()
233 for child in sorted(self.__parent_map.pop(branch, ())):
234 self.__append_branch(child, child_output, depth=depth + 1)
235
236 is_dormant_branch = self.__is_dormant_branch(branch)
237 if self.hide_dormant and is_dormant_branch and not child_output.lines:
238 return
239
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000240 branch_info = self.__branches_info[branch]
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000241 if branch_info:
242 branch_hash = branch_info.hash
243 else:
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000244 try:
245 branch_hash = hash_one(branch, short=True)
246 except subprocess2.CalledProcessError:
247 branch_hash = None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000248
249 line = OutputLine()
250
251 # The branch name with appropriate indentation.
252 suffix = ''
253 if branch == self.__current_branch or (
254 self.__current_branch == 'HEAD' and branch == self.__current_hash):
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000255 suffix = ' *'
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000256 branch_string = branch
257 if branch in self.__gone_branches:
258 branch_string = '{%s:GONE}' % branch
259 if not branch:
260 branch_string = '{NO_UPSTREAM}'
261 main_string = ' ' * depth + branch_string + suffix
262 line.append(
263 main_string,
264 color=self.__color_for_branch(branch, branch_hash))
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000265
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000266 # The branch hash.
267 if self.verbosity >= 2:
268 line.append(branch_hash or '', separator=' ', color=Fore.RED)
269
270 # The branch tracking status.
271 if self.verbosity >= 1:
Gavin Mak8d7201b2020-09-17 19:21:38 +0000272 commits_string = ''
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000273 behind_string = ''
274 front_separator = ''
275 center_separator = ''
276 back_separator = ''
277 if branch_info and not self.__is_invalid_parent(branch_info.upstream):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000278 behind = branch_info.behind
Gavin Mak8d7201b2020-09-17 19:21:38 +0000279 commits = branch_info.commits
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000280
Gavin Mak8d7201b2020-09-17 19:21:38 +0000281 if commits:
282 commits_string = '%d commit' % commits
283 commits_string += 's' if commits > 1 else ' '
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000284 if behind:
285 behind_string = 'behind %d' % behind
286
Gavin Mak8d7201b2020-09-17 19:21:38 +0000287 if commits or behind:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000288 front_separator = '['
289 back_separator = ']'
290
Gavin Mak8d7201b2020-09-17 19:21:38 +0000291 if commits and behind:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000292 center_separator = '|'
293
294 line.append(front_separator, separator=' ')
Gavin Mak8d7201b2020-09-17 19:21:38 +0000295 line.append(commits_string, separator=' ', color=Fore.MAGENTA)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000296 line.append(center_separator, separator=' ')
297 line.append(behind_string, separator=' ', color=Fore.MAGENTA)
298 line.append(back_separator)
299
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000300 if self.verbosity >= 4:
301 line.append(' (dormant)' if is_dormant_branch else ' ',
302 separator=' ',
303 color=Fore.RED)
304
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000305 # The Rietveld issue associated with the branch.
306 if self.verbosity >= 2:
asanka97f39492016-07-18 18:16:40 -0700307 (url, color, status) = ('', '', '') if self.__is_invalid_parent(branch) \
308 else self.__status_info[branch]
309 if self.verbosity > 2:
310 line.append('{} ({})'.format(url, status) if url else '', color=color)
311 else:
312 line.append(url or '', color=color)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000313
borenet@google.com09156ec2015-03-26 14:10:06 +0000314 # The subject of the most recent commit on the branch.
315 if self.show_subject:
Christian Flacha2658212022-12-07 09:00:42 +0000316 if not self.__is_invalid_parent(branch):
Aaron Gable6761b9d2017-08-28 12:23:40 -0700317 line.append(run('log', '-n1', '--format=%s', branch, '--'))
318 else:
319 line.append('')
borenet@google.com09156ec2015-03-26 14:10:06 +0000320
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000321 output.append(line)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000322
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000323 output.merge(child_output)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000324
325
anatoly techtonik222840f2017-04-15 16:25:57 +0300326def print_desc():
327 for line in __doc__.splitlines():
328 starpos = line.find('* ')
329 if starpos == -1 or '-' not in line:
330 print(line)
331 else:
332 _, color, rest = line.split(None, 2)
333 outline = line[:starpos+1]
334 outline += getattr(Fore, color.upper()) + " " + color + " " + Fore.RESET
335 outline += rest
336 print(outline)
337 print('')
338
Josip Sokcevic306b03b2022-02-23 03:25:23 +0000339@metrics.collector.collect_metrics('git map-branches')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000340def main(argv):
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000341 setup_color.init()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000342 if get_git_version() < MIN_UPSTREAM_TRACK_GIT_VERSION:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000343 print(
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000344 'This tool will not show all tracking information for git version '
345 'earlier than ' +
346 '.'.join(str(x) for x in MIN_UPSTREAM_TRACK_GIT_VERSION) +
Raul Tambre80ee78e2019-05-06 22:41:05 +0000347 '. Please consider upgrading.', file=sys.stderr)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000348
anatoly techtonik222840f2017-04-15 16:25:57 +0300349 if '-h' in argv:
350 print_desc()
351
352 parser = argparse.ArgumentParser()
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000353 parser.add_argument('-v',
354 action='count',
355 default=0,
Clemens Hammacher03640c72018-12-13 08:08:19 +0000356 help=('Pass once to show tracking info, '
357 'twice for hash and review url, '
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000358 'thrice for review status, '
359 'four times to mark dormant branches'))
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000360 parser.add_argument('--no-color', action='store_true', dest='nocolor',
361 help='Turn off colors.')
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000362 parser.add_argument(
363 '-j', '--maxjobs', action='store', type=int,
364 help='The number of jobs to use when retrieving review status')
borenet@google.com09156ec2015-03-26 14:10:06 +0000365 parser.add_argument('--show-subject', action='store_true',
366 dest='show_subject', help='Show the commit subject.')
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000367 parser.add_argument('--hide-dormant',
368 action='store_true',
369 dest='hide_dormant',
370 help='Hides dormant branches.')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000371
sbc@chromium.org013731e2015-02-26 18:28:43 +0000372 opts = parser.parse_args(argv)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000373
374 mapper = BranchMapper()
375 mapper.verbosity = opts.v
376 mapper.output.nocolor = opts.nocolor
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000377 mapper.maxjobs = opts.maxjobs
borenet@google.com09156ec2015-03-26 14:10:06 +0000378 mapper.show_subject = opts.show_subject
Orr Bernsteinb7e16d22023-07-14 11:00:55 +0000379 mapper.hide_dormant = opts.hide_dormant
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000380 mapper.start()
Raul Tambre80ee78e2019-05-06 22:41:05 +0000381 print(mapper.output.as_formatted_string())
sbc@chromium.org013731e2015-02-26 18:28:43 +0000382 return 0
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000383
384if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000385 try:
Josip Sokcevic306b03b2022-02-23 03:25:23 +0000386 with metrics.collector.print_notice_and_exit():
387 sys.exit(main(sys.argv[1:]))
sbc@chromium.org013731e2015-02-26 18:28:43 +0000388 except KeyboardInterrupt:
389 sys.stderr.write('interrupted\n')
390 sys.exit(1)