blob: 290f90f52c90dc3876efc2dc72085881f9fff5bf [file] [log] [blame]
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +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:
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00009origin/master
10 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
iannucci@chromium.org0703ea22016-04-01 01:02:42 +000029import os
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
69 def as_formatted_string(self):
70 return '\n'.join(
71 l.as_padded_string(self.max_column_lengths) for l in self.lines)
72
73
74class OutputLine(object):
75 """A single line of data.
76
77 This consists of an equal number of columns, colors and separators."""
78
79 def __init__(self):
80 self.columns = []
81 self.separators = []
82 self.colors = []
83
84 def append(self, data, separator=DEFAULT_SEPARATOR, color=Fore.WHITE):
85 self.columns.append(data)
86 self.separators.append(separator)
87 self.colors.append(color)
88
89 def as_padded_string(self, max_column_lengths):
90 """"Returns the data as a string with each column padded to
91 |max_column_lengths|."""
92 output_string = ''
93 for i, (color, data, separator) in enumerate(
94 zip(self.colors, self.columns, self.separators)):
95 if max_column_lengths[i] == 0:
96 continue
97
98 padding = (max_column_lengths[i] - len(data)) * ' '
99 output_string += color + data + padding + separator
100
101 return output_string.rstrip()
102
103
104class BranchMapper(object):
105 """A class which constructs output representing the tree's branch structure.
106
107 Attributes:
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000108 __branches_info: a map of branches to their BranchesInfo objects which
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000109 consist of the branch hash, upstream and ahead/behind status.
110 __gone_branches: a set of upstreams which are not fetchable by git"""
111
112 def __init__(self):
113 self.verbosity = 0
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000114 self.maxjobs = 0
borenet@google.com09156ec2015-03-26 14:10:06 +0000115 self.show_subject = False
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000116 self.output = OutputManager()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000117 self.__gone_branches = set()
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000118 self.__branches_info = None
119 self.__parent_map = collections.defaultdict(list)
120 self.__current_branch = None
121 self.__current_hash = None
122 self.__tag_set = None
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000123 self.__status_info = {}
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000124
125 def start(self):
126 self.__branches_info = get_branches_info(
127 include_tracking_status=self.verbosity >= 1)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000128 if (self.verbosity >= 2):
129 # Avoid heavy import unless necessary.
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000130 from git_cl import get_cl_statuses, color_for_status, Changelist
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000131
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000132 change_cls = [Changelist(branchref='refs/heads/'+b)
133 for b in self.__branches_info.keys() if b]
134 status_info = get_cl_statuses(change_cls,
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000135 fine_grained=self.verbosity > 2,
136 max_processes=self.maxjobs)
137
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000138 # This is a blocking get which waits for the remote CL status to be
139 # retrieved.
140 for cl, status in status_info:
141 self.__status_info[cl.GetBranch()] = (cl.GetIssueURL(),
asanka97f39492016-07-18 18:16:40 -0700142 color_for_status(status),
143 status)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000144
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000145 roots = set()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000146
147 # A map of parents to a list of their children.
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000148 for branch, branch_info in self.__branches_info.iteritems():
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000149 if not branch_info:
150 continue
151
152 parent = branch_info.upstream
Clemens Hammacher793183d2019-03-22 01:12:46 +0000153 if self.__check_cycle(branch):
154 continue
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000155 if not self.__branches_info[parent]:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000156 branch_upstream = upstream(branch)
157 # If git can't find the upstream, mark the upstream as gone.
158 if branch_upstream:
159 parent = branch_upstream
160 else:
161 self.__gone_branches.add(parent)
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000162 # A parent that isn't in the branches info is a root.
163 roots.add(parent)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000164
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000165 self.__parent_map[parent].append(branch)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000166
167 self.__current_branch = current_branch()
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000168 self.__current_hash = hash_one('HEAD', short=True)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000169 self.__tag_set = tags()
170
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000171 if roots:
172 for root in sorted(roots):
173 self.__append_branch(root)
174 else:
175 no_branches = OutputLine()
176 no_branches.append('No User Branches')
177 self.output.append(no_branches)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000178
Clemens Hammacher793183d2019-03-22 01:12:46 +0000179 def __check_cycle(self, branch):
180 # Maximum length of the cycle is `num_branches`. This limit avoids running
181 # into a cycle which does *not* contain `branch`.
182 num_branches = len(self.__branches_info)
183 cycle = [branch]
184 while len(cycle) < num_branches and self.__branches_info[cycle[-1]]:
185 parent = self.__branches_info[cycle[-1]].upstream
186 cycle.append(parent)
187 if parent == branch:
188 print >> sys.stderr, 'Warning: Detected cycle in branches: {}'.format(
189 ' -> '.join(cycle))
190 return True
191 return False
192
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000193 def __is_invalid_parent(self, parent):
194 return not parent or parent in self.__gone_branches
195
196 def __color_for_branch(self, branch, branch_hash):
jsbell@google.com4f1fc352016-03-24 22:23:46 +0000197 if branch.startswith('origin/'):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000198 color = Fore.RED
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000199 elif branch.startswith('branch-heads'):
200 color = Fore.BLUE
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000201 elif self.__is_invalid_parent(branch) or branch in self.__tag_set:
202 color = Fore.MAGENTA
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000203 elif self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000204 color = Fore.CYAN
205 else:
206 color = Fore.GREEN
207
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000208 if branch_hash and self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000209 color += Style.BRIGHT
210 else:
211 color += Style.NORMAL
212
213 return color
214
215 def __append_branch(self, branch, depth=0):
216 """Recurses through the tree structure and appends an OutputLine to the
217 OutputManager for each branch."""
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000218 branch_info = self.__branches_info[branch]
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000219 if branch_info:
220 branch_hash = branch_info.hash
221 else:
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000222 try:
223 branch_hash = hash_one(branch, short=True)
224 except subprocess2.CalledProcessError:
225 branch_hash = None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000226
227 line = OutputLine()
228
229 # The branch name with appropriate indentation.
230 suffix = ''
231 if branch == self.__current_branch or (
232 self.__current_branch == 'HEAD' and branch == self.__current_hash):
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000233 suffix = ' *'
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000234 branch_string = branch
235 if branch in self.__gone_branches:
236 branch_string = '{%s:GONE}' % branch
237 if not branch:
238 branch_string = '{NO_UPSTREAM}'
239 main_string = ' ' * depth + branch_string + suffix
240 line.append(
241 main_string,
242 color=self.__color_for_branch(branch, branch_hash))
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000243
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000244 # The branch hash.
245 if self.verbosity >= 2:
246 line.append(branch_hash or '', separator=' ', color=Fore.RED)
247
248 # The branch tracking status.
249 if self.verbosity >= 1:
250 ahead_string = ''
251 behind_string = ''
252 front_separator = ''
253 center_separator = ''
254 back_separator = ''
255 if branch_info and not self.__is_invalid_parent(branch_info.upstream):
256 ahead = branch_info.ahead
257 behind = branch_info.behind
258
259 if ahead:
260 ahead_string = 'ahead %d' % ahead
261 if behind:
262 behind_string = 'behind %d' % behind
263
264 if ahead or behind:
265 front_separator = '['
266 back_separator = ']'
267
268 if ahead and behind:
269 center_separator = '|'
270
271 line.append(front_separator, separator=' ')
272 line.append(ahead_string, separator=' ', color=Fore.MAGENTA)
273 line.append(center_separator, separator=' ')
274 line.append(behind_string, separator=' ', color=Fore.MAGENTA)
275 line.append(back_separator)
276
277 # The Rietveld issue associated with the branch.
278 if self.verbosity >= 2:
asanka97f39492016-07-18 18:16:40 -0700279 (url, color, status) = ('', '', '') if self.__is_invalid_parent(branch) \
280 else self.__status_info[branch]
281 if self.verbosity > 2:
282 line.append('{} ({})'.format(url, status) if url else '', color=color)
283 else:
284 line.append(url or '', color=color)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000285
borenet@google.com09156ec2015-03-26 14:10:06 +0000286 # The subject of the most recent commit on the branch.
287 if self.show_subject:
Aaron Gable6761b9d2017-08-28 12:23:40 -0700288 if branch:
289 line.append(run('log', '-n1', '--format=%s', branch, '--'))
290 else:
291 line.append('')
borenet@google.com09156ec2015-03-26 14:10:06 +0000292
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000293 self.output.append(line)
294
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000295 for child in sorted(self.__parent_map.pop(branch, ())):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000296 self.__append_branch(child, depth=depth + 1)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000297
298
anatoly techtonik222840f2017-04-15 16:25:57 +0300299def print_desc():
300 for line in __doc__.splitlines():
301 starpos = line.find('* ')
302 if starpos == -1 or '-' not in line:
303 print(line)
304 else:
305 _, color, rest = line.split(None, 2)
306 outline = line[:starpos+1]
307 outline += getattr(Fore, color.upper()) + " " + color + " " + Fore.RESET
308 outline += rest
309 print(outline)
310 print('')
311
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000312def main(argv):
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +0000313 setup_color.init()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000314 if get_git_version() < MIN_UPSTREAM_TRACK_GIT_VERSION:
315 print >> sys.stderr, (
316 'This tool will not show all tracking information for git version '
317 'earlier than ' +
318 '.'.join(str(x) for x in MIN_UPSTREAM_TRACK_GIT_VERSION) +
319 '. Please consider upgrading.')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000320
anatoly techtonik222840f2017-04-15 16:25:57 +0300321 if '-h' in argv:
322 print_desc()
323
324 parser = argparse.ArgumentParser()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000325 parser.add_argument('-v', action='count',
Clemens Hammacher03640c72018-12-13 08:08:19 +0000326 help=('Pass once to show tracking info, '
327 'twice for hash and review url, '
328 'thrice for review status'))
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000329 parser.add_argument('--no-color', action='store_true', dest='nocolor',
330 help='Turn off colors.')
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000331 parser.add_argument(
332 '-j', '--maxjobs', action='store', type=int,
333 help='The number of jobs to use when retrieving review status')
borenet@google.com09156ec2015-03-26 14:10:06 +0000334 parser.add_argument('--show-subject', action='store_true',
335 dest='show_subject', help='Show the commit subject.')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000336
sbc@chromium.org013731e2015-02-26 18:28:43 +0000337 opts = parser.parse_args(argv)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000338
339 mapper = BranchMapper()
340 mapper.verbosity = opts.v
341 mapper.output.nocolor = opts.nocolor
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000342 mapper.maxjobs = opts.maxjobs
borenet@google.com09156ec2015-03-26 14:10:06 +0000343 mapper.show_subject = opts.show_subject
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000344 mapper.start()
345 print mapper.output.as_formatted_string()
sbc@chromium.org013731e2015-02-26 18:28:43 +0000346 return 0
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000347
348if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000349 try:
350 sys.exit(main(sys.argv[1:]))
351 except KeyboardInterrupt:
352 sys.stderr.write('interrupted\n')
353 sys.exit(1)