blob: 613abc797d0af2fa2556ba982add2a9de86eee35 [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
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00006"""Provides a short mapping of all the branches in your local repo, organized
7by their upstream ('tracking branch') layout.
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +00008
calamity@chromium.org9d2c8802014-09-03 02:04:46 +00009Example:
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000010origin/master
11 cool_feature
12 dependent_feature
13 other_dependent_feature
14 other_feature
15
16Branches are colorized as follows:
17 * Red - a remote branch (usually the root of all local branches)
18 * Cyan - a local branch which is the same as HEAD
19 * Note that multiple branches may be Cyan, if they are all on the same
20 commit, and you have that commit checked out.
21 * Green - a local branch
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +000022 * Blue - a 'branch-heads' branch
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000023 * Magenta - a tag
24 * Magenta '{NO UPSTREAM}' - If you have local branches which do not track any
25 upstream, then you will see this.
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000026"""
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000027
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000028import argparse
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000029import collections
30import sys
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +000031import subprocess2
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000032
33from third_party import colorama
34from third_party.colorama import Fore, Style
35
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
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000038
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000039DEFAULT_SEPARATOR = ' ' * 4
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000040
41
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000042class OutputManager(object):
43 """Manages a number of OutputLines and formats them into aligned columns."""
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000044
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000045 def __init__(self):
46 self.lines = []
47 self.nocolor = False
48 self.max_column_lengths = []
49 self.num_columns = None
iannucci@chromium.orgc050a5b2014-03-26 06:18:50 +000050
calamity@chromium.org9d2c8802014-09-03 02:04:46 +000051 def append(self, line):
52 # All lines must have the same number of columns.
53 if not self.num_columns:
54 self.num_columns = len(line.columns)
55 self.max_column_lengths = [0] * self.num_columns
56 assert self.num_columns == len(line.columns)
57
58 if self.nocolor:
59 line.colors = [''] * self.num_columns
60
61 self.lines.append(line)
62
63 # Update maximum column lengths.
64 for i, col in enumerate(line.columns):
65 self.max_column_lengths[i] = max(self.max_column_lengths[i], len(col))
66
67 def as_formatted_string(self):
68 return '\n'.join(
69 l.as_padded_string(self.max_column_lengths) for l in self.lines)
70
71
72class OutputLine(object):
73 """A single line of data.
74
75 This consists of an equal number of columns, colors and separators."""
76
77 def __init__(self):
78 self.columns = []
79 self.separators = []
80 self.colors = []
81
82 def append(self, data, separator=DEFAULT_SEPARATOR, color=Fore.WHITE):
83 self.columns.append(data)
84 self.separators.append(separator)
85 self.colors.append(color)
86
87 def as_padded_string(self, max_column_lengths):
88 """"Returns the data as a string with each column padded to
89 |max_column_lengths|."""
90 output_string = ''
91 for i, (color, data, separator) in enumerate(
92 zip(self.colors, self.columns, self.separators)):
93 if max_column_lengths[i] == 0:
94 continue
95
96 padding = (max_column_lengths[i] - len(data)) * ' '
97 output_string += color + data + padding + separator
98
99 return output_string.rstrip()
100
101
102class BranchMapper(object):
103 """A class which constructs output representing the tree's branch structure.
104
105 Attributes:
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000106 __branches_info: a map of branches to their BranchesInfo objects which
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000107 consist of the branch hash, upstream and ahead/behind status.
108 __gone_branches: a set of upstreams which are not fetchable by git"""
109
110 def __init__(self):
111 self.verbosity = 0
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000112 self.maxjobs = 0
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000113 self.output = OutputManager()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000114 self.__gone_branches = set()
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000115 self.__branches_info = None
116 self.__parent_map = collections.defaultdict(list)
117 self.__current_branch = None
118 self.__current_hash = None
119 self.__tag_set = None
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000120 self.__status_info = {}
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000121
122 def start(self):
123 self.__branches_info = get_branches_info(
124 include_tracking_status=self.verbosity >= 1)
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000125 if (self.verbosity >= 2):
126 # Avoid heavy import unless necessary.
127 from git_cl import get_cl_statuses
128
129 status_info = get_cl_statuses(self.__branches_info.keys(),
130 fine_grained=self.verbosity > 2,
131 max_processes=self.maxjobs)
132
133 for _ in xrange(len(self.__branches_info)):
134 # This is a blocking get which waits for the remote CL status to be
135 # retrieved.
136 (branch, url, color) = status_info.next()
137 self.__status_info[branch] = (url, color);
138
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000139 roots = set()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000140
141 # A map of parents to a list of their children.
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000142 for branch, branch_info in self.__branches_info.iteritems():
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000143 if not branch_info:
144 continue
145
146 parent = branch_info.upstream
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000147 if not self.__branches_info[parent]:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000148 branch_upstream = upstream(branch)
149 # If git can't find the upstream, mark the upstream as gone.
150 if branch_upstream:
151 parent = branch_upstream
152 else:
153 self.__gone_branches.add(parent)
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000154 # A parent that isn't in the branches info is a root.
155 roots.add(parent)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000156
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000157 self.__parent_map[parent].append(branch)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000158
159 self.__current_branch = current_branch()
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000160 self.__current_hash = hash_one('HEAD', short=True)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000161 self.__tag_set = tags()
162
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000163 if roots:
164 for root in sorted(roots):
165 self.__append_branch(root)
166 else:
167 no_branches = OutputLine()
168 no_branches.append('No User Branches')
169 self.output.append(no_branches)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000170
171 def __is_invalid_parent(self, parent):
172 return not parent or parent in self.__gone_branches
173
174 def __color_for_branch(self, branch, branch_hash):
175 if branch.startswith('origin'):
176 color = Fore.RED
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000177 elif branch.startswith('branch-heads'):
178 color = Fore.BLUE
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000179 elif self.__is_invalid_parent(branch) or branch in self.__tag_set:
180 color = Fore.MAGENTA
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000181 elif self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000182 color = Fore.CYAN
183 else:
184 color = Fore.GREEN
185
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000186 if branch_hash and self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000187 color += Style.BRIGHT
188 else:
189 color += Style.NORMAL
190
191 return color
192
193 def __append_branch(self, branch, depth=0):
194 """Recurses through the tree structure and appends an OutputLine to the
195 OutputManager for each branch."""
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000196 branch_info = self.__branches_info[branch]
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000197 if branch_info:
198 branch_hash = branch_info.hash
199 else:
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000200 try:
201 branch_hash = hash_one(branch, short=True)
202 except subprocess2.CalledProcessError:
203 branch_hash = None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000204
205 line = OutputLine()
206
207 # The branch name with appropriate indentation.
208 suffix = ''
209 if branch == self.__current_branch or (
210 self.__current_branch == 'HEAD' and branch == self.__current_hash):
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000211 suffix = ' *'
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000212 branch_string = branch
213 if branch in self.__gone_branches:
214 branch_string = '{%s:GONE}' % branch
215 if not branch:
216 branch_string = '{NO_UPSTREAM}'
217 main_string = ' ' * depth + branch_string + suffix
218 line.append(
219 main_string,
220 color=self.__color_for_branch(branch, branch_hash))
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000221
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000222 # The branch hash.
223 if self.verbosity >= 2:
224 line.append(branch_hash or '', separator=' ', color=Fore.RED)
225
226 # The branch tracking status.
227 if self.verbosity >= 1:
228 ahead_string = ''
229 behind_string = ''
230 front_separator = ''
231 center_separator = ''
232 back_separator = ''
233 if branch_info and not self.__is_invalid_parent(branch_info.upstream):
234 ahead = branch_info.ahead
235 behind = branch_info.behind
236
237 if ahead:
238 ahead_string = 'ahead %d' % ahead
239 if behind:
240 behind_string = 'behind %d' % behind
241
242 if ahead or behind:
243 front_separator = '['
244 back_separator = ']'
245
246 if ahead and behind:
247 center_separator = '|'
248
249 line.append(front_separator, separator=' ')
250 line.append(ahead_string, separator=' ', color=Fore.MAGENTA)
251 line.append(center_separator, separator=' ')
252 line.append(behind_string, separator=' ', color=Fore.MAGENTA)
253 line.append(back_separator)
254
255 # The Rietveld issue associated with the branch.
256 if self.verbosity >= 2:
257 none_text = '' if self.__is_invalid_parent(branch) else 'None'
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000258 (url, color) = self.__status_info[branch]
259 line.append(url or none_text, color=color)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000260
261 self.output.append(line)
262
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000263 for child in sorted(self.__parent_map.pop(branch, ())):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000264 self.__append_branch(child, depth=depth + 1)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000265
266
267def main(argv):
268 colorama.init()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000269 if get_git_version() < MIN_UPSTREAM_TRACK_GIT_VERSION:
270 print >> sys.stderr, (
271 'This tool will not show all tracking information for git version '
272 'earlier than ' +
273 '.'.join(str(x) for x in MIN_UPSTREAM_TRACK_GIT_VERSION) +
274 '. Please consider upgrading.')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000275
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000276 parser = argparse.ArgumentParser(
277 description='Print a a tree of all branches parented by their upstreams')
278 parser.add_argument('-v', action='count',
279 help='Display branch hash and Rietveld URL')
280 parser.add_argument('--no-color', action='store_true', dest='nocolor',
281 help='Turn off colors.')
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000282 parser.add_argument(
283 '-j', '--maxjobs', action='store', type=int,
284 help='The number of jobs to use when retrieving review status')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000285
sbc@chromium.org013731e2015-02-26 18:28:43 +0000286 opts = parser.parse_args(argv)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000287
288 mapper = BranchMapper()
289 mapper.verbosity = opts.v
290 mapper.output.nocolor = opts.nocolor
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000291 mapper.maxjobs = opts.maxjobs
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000292 mapper.start()
293 print mapper.output.as_formatted_string()
sbc@chromium.org013731e2015-02-26 18:28:43 +0000294 return 0
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000295
296if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000297 try:
298 sys.exit(main(sys.argv[1:]))
299 except KeyboardInterrupt:
300 sys.stderr.write('interrupted\n')
301 sys.exit(1)