blob: 8c5ea714e580cfce8653a30967d2db34a1797103 [file] [log] [blame]
Edward Lesmes98eda3f2019-08-12 21:09:53 +00001#!/usr/bin/env python
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
iannucci@chromium.org0703ea22016-04-01 01:02:42 +000031import os
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +000032import subprocess2
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000033import sys
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000034
calamity@chromium.org745ffa62014-09-08 01:03:19 +000035from git_common import current_branch, upstream, tags, get_branches_info
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +000036from git_common import get_git_version, MIN_UPSTREAM_TRACK_GIT_VERSION, hash_one
borenet@google.com09156ec2015-03-26 14:10:06 +000037from git_common import run
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000038
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +000039import setup_color
40
41from third_party.colorama import Fore, Style
42
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000043DEFAULT_SEPARATOR = ' ' * 4
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000044
45
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000046class OutputManager(object):
47 """Manages a number of OutputLines and formats them into aligned columns."""
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000048
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000049 def __init__(self):
50 self.lines = []
51 self.nocolor = False
52 self.max_column_lengths = []
53 self.num_columns = None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000054
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000055 def append(self, line):
56 # All lines must have the same number of columns.
57 if not self.num_columns:
58 self.num_columns = len(line.columns)
59 self.max_column_lengths = [0] * self.num_columns
60 assert self.num_columns == len(line.columns)
61
62 if self.nocolor:
63 line.colors = [''] * self.num_columns
64
65 self.lines.append(line)
66
67 # Update maximum column lengths.
68 for i, col in enumerate(line.columns):
69 self.max_column_lengths[i] = max(self.max_column_lengths[i], len(col))
70
71 def as_formatted_string(self):
72 return '\n'.join(
73 l.as_padded_string(self.max_column_lengths) for l in self.lines)
74
75
76class OutputLine(object):
77 """A single line of data.
78
79 This consists of an equal number of columns, colors and separators."""
80
81 def __init__(self):
82 self.columns = []
83 self.separators = []
84 self.colors = []
85
86 def append(self, data, separator=DEFAULT_SEPARATOR, color=Fore.WHITE):
87 self.columns.append(data)
88 self.separators.append(separator)
89 self.colors.append(color)
90
91 def as_padded_string(self, max_column_lengths):
92 """"Returns the data as a string with each column padded to
93 |max_column_lengths|."""
94 output_string = ''
95 for i, (color, data, separator) in enumerate(
96 zip(self.colors, self.columns, self.separators)):
97 if max_column_lengths[i] == 0:
98 continue
99
100 padding = (max_column_lengths[i] - len(data)) * ' '
101 output_string += color + data + padding + separator
102
103 return output_string.rstrip()
104
105
106class BranchMapper(object):
107 """A class which constructs output representing the tree's branch structure.
108
109 Attributes:
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000110 __branches_info: a map of branches to their BranchesInfo objects which
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000111 consist of the branch hash, upstream and ahead/behind status.
112 __gone_branches: a set of upstreams which are not fetchable by git"""
113
114 def __init__(self):
115 self.verbosity = 0
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000116 self.maxjobs = 0
borenet@google.com09156ec2015-03-26 14:10:06 +0000117 self.show_subject = False
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000118 self.output = OutputManager()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000119 self.__gone_branches = set()
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000120 self.__branches_info = None
121 self.__parent_map = collections.defaultdict(list)
122 self.__current_branch = None
123 self.__current_hash = None
124 self.__tag_set = None
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000125 self.__status_info = {}
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000126
127 def start(self):
128 self.__branches_info = get_branches_info(
129 include_tracking_status=self.verbosity >= 1)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000130 if (self.verbosity >= 2):
131 # Avoid heavy import unless necessary.
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000132 from git_cl import get_cl_statuses, color_for_status, Changelist
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000133
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000134 change_cls = [Changelist(branchref='refs/heads/'+b)
135 for b in self.__branches_info.keys() if b]
136 status_info = get_cl_statuses(change_cls,
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000137 fine_grained=self.verbosity > 2,
138 max_processes=self.maxjobs)
139
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000140 # This is a blocking get which waits for the remote CL status to be
141 # retrieved.
142 for cl, status in status_info:
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000143 self.__status_info[cl.GetBranch()] = (cl.GetIssueURL(short=True),
144 color_for_status(status), status)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000145
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000146 roots = set()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000147
148 # A map of parents to a list of their children.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000149 for branch, branch_info in self.__branches_info.items():
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000150 if not branch_info:
151 continue
152
153 parent = branch_info.upstream
Clemens Hammacher793183d2019-03-22 01:12:46 +0000154 if self.__check_cycle(branch):
155 continue
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000156 if not self.__branches_info[parent]:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000157 branch_upstream = upstream(branch)
158 # If git can't find the upstream, mark the upstream as gone.
159 if branch_upstream:
160 parent = branch_upstream
161 else:
162 self.__gone_branches.add(parent)
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000163 # A parent that isn't in the branches info is a root.
164 roots.add(parent)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000165
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000166 self.__parent_map[parent].append(branch)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000167
168 self.__current_branch = current_branch()
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000169 self.__current_hash = hash_one('HEAD', short=True)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000170 self.__tag_set = tags()
171
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000172 if roots:
173 for root in sorted(roots):
174 self.__append_branch(root)
175 else:
176 no_branches = OutputLine()
177 no_branches.append('No User Branches')
178 self.output.append(no_branches)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000179
Clemens Hammacher793183d2019-03-22 01:12:46 +0000180 def __check_cycle(self, branch):
181 # Maximum length of the cycle is `num_branches`. This limit avoids running
182 # into a cycle which does *not* contain `branch`.
183 num_branches = len(self.__branches_info)
184 cycle = [branch]
185 while len(cycle) < num_branches and self.__branches_info[cycle[-1]]:
186 parent = self.__branches_info[cycle[-1]].upstream
187 cycle.append(parent)
188 if parent == branch:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000189 print('Warning: Detected cycle in branches: {}'.format(
190 ' -> '.join(cycle)), file=sys.stderr)
Clemens Hammacher793183d2019-03-22 01:12:46 +0000191 return True
192 return False
193
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000194 def __is_invalid_parent(self, parent):
195 return not parent or parent in self.__gone_branches
196
197 def __color_for_branch(self, branch, branch_hash):
jsbell@google.com4f1fc352016-03-24 22:23:46 +0000198 if branch.startswith('origin/'):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000199 color = Fore.RED
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000200 elif branch.startswith('branch-heads'):
201 color = Fore.BLUE
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000202 elif self.__is_invalid_parent(branch) or branch in self.__tag_set:
203 color = Fore.MAGENTA
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000204 elif self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000205 color = Fore.CYAN
206 else:
207 color = Fore.GREEN
208
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000209 if branch_hash and self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000210 color += Style.BRIGHT
211 else:
212 color += Style.NORMAL
213
214 return color
215
216 def __append_branch(self, branch, depth=0):
217 """Recurses through the tree structure and appends an OutputLine to the
218 OutputManager for each branch."""
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000219 branch_info = self.__branches_info[branch]
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000220 if branch_info:
221 branch_hash = branch_info.hash
222 else:
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000223 try:
224 branch_hash = hash_one(branch, short=True)
225 except subprocess2.CalledProcessError:
226 branch_hash = None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000227
228 line = OutputLine()
229
230 # The branch name with appropriate indentation.
231 suffix = ''
232 if branch == self.__current_branch or (
233 self.__current_branch == 'HEAD' and branch == self.__current_hash):
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000234 suffix = ' *'
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000235 branch_string = branch
236 if branch in self.__gone_branches:
237 branch_string = '{%s:GONE}' % branch
238 if not branch:
239 branch_string = '{NO_UPSTREAM}'
240 main_string = ' ' * depth + branch_string + suffix
241 line.append(
242 main_string,
243 color=self.__color_for_branch(branch, branch_hash))
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000244
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000245 # The branch hash.
246 if self.verbosity >= 2:
247 line.append(branch_hash or '', separator=' ', color=Fore.RED)
248
249 # The branch tracking status.
250 if self.verbosity >= 1:
Gavin Mak8d7201b2020-09-17 19:21:38 +0000251 commits_string = ''
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000252 behind_string = ''
253 front_separator = ''
254 center_separator = ''
255 back_separator = ''
256 if branch_info and not self.__is_invalid_parent(branch_info.upstream):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000257 behind = branch_info.behind
Gavin Mak8d7201b2020-09-17 19:21:38 +0000258 commits = branch_info.commits
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000259
Gavin Mak8d7201b2020-09-17 19:21:38 +0000260 if commits:
261 commits_string = '%d commit' % commits
262 commits_string += 's' if commits > 1 else ' '
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000263 if behind:
264 behind_string = 'behind %d' % behind
265
Gavin Mak8d7201b2020-09-17 19:21:38 +0000266 if commits or behind:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000267 front_separator = '['
268 back_separator = ']'
269
Gavin Mak8d7201b2020-09-17 19:21:38 +0000270 if commits and behind:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000271 center_separator = '|'
272
273 line.append(front_separator, separator=' ')
Gavin Mak8d7201b2020-09-17 19:21:38 +0000274 line.append(commits_string, separator=' ', color=Fore.MAGENTA)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000275 line.append(center_separator, separator=' ')
276 line.append(behind_string, separator=' ', color=Fore.MAGENTA)
277 line.append(back_separator)
278
279 # The Rietveld issue associated with the branch.
280 if self.verbosity >= 2:
asanka97f39492016-07-18 18:16:40 -0700281 (url, color, status) = ('', '', '') if self.__is_invalid_parent(branch) \
282 else self.__status_info[branch]
283 if self.verbosity > 2:
284 line.append('{} ({})'.format(url, status) if url else '', color=color)
285 else:
286 line.append(url or '', color=color)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000287
borenet@google.com09156ec2015-03-26 14:10:06 +0000288 # The subject of the most recent commit on the branch.
289 if self.show_subject:
Aaron Gable6761b9d2017-08-28 12:23:40 -0700290 if branch:
291 line.append(run('log', '-n1', '--format=%s', branch, '--'))
292 else:
293 line.append('')
borenet@google.com09156ec2015-03-26 14:10:06 +0000294
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000295 self.output.append(line)
296
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000297 for child in sorted(self.__parent_map.pop(branch, ())):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000298 self.__append_branch(child, depth=depth + 1)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000299
300
anatoly techtonik222840f2017-04-15 16:25:57 +0300301def print_desc():
302 for line in __doc__.splitlines():
303 starpos = line.find('* ')
304 if starpos == -1 or '-' not in line:
305 print(line)
306 else:
307 _, color, rest = line.split(None, 2)
308 outline = line[:starpos+1]
309 outline += getattr(Fore, color.upper()) + " " + color + " " + Fore.RESET
310 outline += rest
311 print(outline)
312 print('')
313
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000314def main(argv):
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000315 setup_color.init()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000316 if get_git_version() < MIN_UPSTREAM_TRACK_GIT_VERSION:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000317 print(
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000318 'This tool will not show all tracking information for git version '
319 'earlier than ' +
320 '.'.join(str(x) for x in MIN_UPSTREAM_TRACK_GIT_VERSION) +
Raul Tambre80ee78e2019-05-06 22:41:05 +0000321 '. Please consider upgrading.', file=sys.stderr)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000322
anatoly techtonik222840f2017-04-15 16:25:57 +0300323 if '-h' in argv:
324 print_desc()
325
326 parser = argparse.ArgumentParser()
Edward Lemur2bac03e2020-03-04 21:54:26 +0000327 parser.add_argument('-v', action='count', default=0,
Clemens Hammacher03640c72018-12-13 08:08:19 +0000328 help=('Pass once to show tracking info, '
329 'twice for hash and review url, '
330 'thrice for review status'))
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000331 parser.add_argument('--no-color', action='store_true', dest='nocolor',
332 help='Turn off colors.')
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000333 parser.add_argument(
334 '-j', '--maxjobs', action='store', type=int,
335 help='The number of jobs to use when retrieving review status')
borenet@google.com09156ec2015-03-26 14:10:06 +0000336 parser.add_argument('--show-subject', action='store_true',
337 dest='show_subject', help='Show the commit subject.')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000338
sbc@chromium.org013731e2015-02-26 18:28:43 +0000339 opts = parser.parse_args(argv)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000340
341 mapper = BranchMapper()
342 mapper.verbosity = opts.v
343 mapper.output.nocolor = opts.nocolor
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000344 mapper.maxjobs = opts.maxjobs
borenet@google.com09156ec2015-03-26 14:10:06 +0000345 mapper.show_subject = opts.show_subject
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000346 mapper.start()
Raul Tambre80ee78e2019-05-06 22:41:05 +0000347 print(mapper.output.as_formatted_string())
sbc@chromium.org013731e2015-02-26 18:28:43 +0000348 return 0
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000349
350if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000351 try:
352 sys.exit(main(sys.argv[1:]))
353 except KeyboardInterrupt:
354 sys.stderr.write('interrupted\n')
355 sys.exit(1)