blob: 55d574b53ace40d22a87b8a6e9f9473dfe7fb0c9 [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:
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
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:
143 self.__status_info[cl.GetBranch()] = (cl.GetIssueURL(),
asanka97f39492016-07-18 18:16:40 -0700144 color_for_status(status),
145 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:
252 ahead_string = ''
253 behind_string = ''
254 front_separator = ''
255 center_separator = ''
256 back_separator = ''
257 if branch_info and not self.__is_invalid_parent(branch_info.upstream):
258 ahead = branch_info.ahead
259 behind = branch_info.behind
260
261 if ahead:
262 ahead_string = 'ahead %d' % ahead
263 if behind:
264 behind_string = 'behind %d' % behind
265
266 if ahead or behind:
267 front_separator = '['
268 back_separator = ']'
269
270 if ahead and behind:
271 center_separator = '|'
272
273 line.append(front_separator, separator=' ')
274 line.append(ahead_string, separator=' ', color=Fore.MAGENTA)
275 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()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000327 parser.add_argument('-v', action='count',
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)