blob: 50b403d4c9637f49a48f549166d57bf5ec541f15 [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
iannucci@chromium.orgeed06d62016-04-01 00:59:42 +000030import os
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000031import sys
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +000032import subprocess2
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000033
34from third_party import colorama
35from third_party.colorama import Fore, Style
36
calamity@chromium.org745ffa62014-09-08 01:03:19 +000037from git_common import current_branch, upstream, tags, get_branches_info
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +000038from git_common import get_git_version, MIN_UPSTREAM_TRACK_GIT_VERSION, hash_one
borenet@google.com09156ec2015-03-26 14:10:06 +000039from git_common import run
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +000040
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.
sdefresne@chromium.org32f122f2015-06-11 09:39:40 +0000130 from git_cl import get_cl_statuses, color_for_status
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000131
132 status_info = get_cl_statuses(self.__branches_info.keys(),
133 fine_grained=self.verbosity > 2,
134 max_processes=self.maxjobs)
135
136 for _ in xrange(len(self.__branches_info)):
137 # This is a blocking get which waits for the remote CL status to be
138 # retrieved.
sdefresne@chromium.org32f122f2015-06-11 09:39:40 +0000139 (branch, url, status) = status_info.next()
140 self.__status_info[branch] = (url, color_for_status(status))
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000141
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000142 roots = set()
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000143
144 # A map of parents to a list of their children.
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000145 for branch, branch_info in self.__branches_info.iteritems():
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000146 if not branch_info:
147 continue
148
149 parent = branch_info.upstream
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000150 if not self.__branches_info[parent]:
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000151 branch_upstream = upstream(branch)
152 # If git can't find the upstream, mark the upstream as gone.
153 if branch_upstream:
154 parent = branch_upstream
155 else:
156 self.__gone_branches.add(parent)
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000157 # A parent that isn't in the branches info is a root.
158 roots.add(parent)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000159
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000160 self.__parent_map[parent].append(branch)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000161
162 self.__current_branch = current_branch()
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000163 self.__current_hash = hash_one('HEAD', short=True)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000164 self.__tag_set = tags()
165
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000166 if roots:
167 for root in sorted(roots):
168 self.__append_branch(root)
169 else:
170 no_branches = OutputLine()
171 no_branches.append('No User Branches')
172 self.output.append(no_branches)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000173
174 def __is_invalid_parent(self, parent):
175 return not parent or parent in self.__gone_branches
176
177 def __color_for_branch(self, branch, branch_hash):
jsbell@google.com4f1fc352016-03-24 22:23:46 +0000178 if branch.startswith('origin/'):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000179 color = Fore.RED
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000180 elif branch.startswith('branch-heads'):
181 color = Fore.BLUE
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000182 elif self.__is_invalid_parent(branch) or branch in self.__tag_set:
183 color = Fore.MAGENTA
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000184 elif self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000185 color = Fore.CYAN
186 else:
187 color = Fore.GREEN
188
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000189 if branch_hash and self.__current_hash.startswith(branch_hash):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000190 color += Style.BRIGHT
191 else:
192 color += Style.NORMAL
193
194 return color
195
196 def __append_branch(self, branch, depth=0):
197 """Recurses through the tree structure and appends an OutputLine to the
198 OutputManager for each branch."""
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000199 branch_info = self.__branches_info[branch]
iannucci@chromium.org4c82eb52014-09-08 02:12:24 +0000200 if branch_info:
201 branch_hash = branch_info.hash
202 else:
calamity@chromium.org4cd0a8b2014-09-23 03:30:50 +0000203 try:
204 branch_hash = hash_one(branch, short=True)
205 except subprocess2.CalledProcessError:
206 branch_hash = None
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000207
208 line = OutputLine()
209
210 # The branch name with appropriate indentation.
211 suffix = ''
212 if branch == self.__current_branch or (
213 self.__current_branch == 'HEAD' and branch == self.__current_hash):
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000214 suffix = ' *'
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000215 branch_string = branch
216 if branch in self.__gone_branches:
217 branch_string = '{%s:GONE}' % branch
218 if not branch:
219 branch_string = '{NO_UPSTREAM}'
220 main_string = ' ' * depth + branch_string + suffix
221 line.append(
222 main_string,
223 color=self.__color_for_branch(branch, branch_hash))
iannucci@chromium.orga112f032014-03-13 07:47:50 +0000224
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000225 # The branch hash.
226 if self.verbosity >= 2:
227 line.append(branch_hash or '', separator=' ', color=Fore.RED)
228
229 # The branch tracking status.
230 if self.verbosity >= 1:
231 ahead_string = ''
232 behind_string = ''
233 front_separator = ''
234 center_separator = ''
235 back_separator = ''
236 if branch_info and not self.__is_invalid_parent(branch_info.upstream):
237 ahead = branch_info.ahead
238 behind = branch_info.behind
239
240 if ahead:
241 ahead_string = 'ahead %d' % ahead
242 if behind:
243 behind_string = 'behind %d' % behind
244
245 if ahead or behind:
246 front_separator = '['
247 back_separator = ']'
248
249 if ahead and behind:
250 center_separator = '|'
251
252 line.append(front_separator, separator=' ')
253 line.append(ahead_string, separator=' ', color=Fore.MAGENTA)
254 line.append(center_separator, separator=' ')
255 line.append(behind_string, separator=' ', color=Fore.MAGENTA)
256 line.append(back_separator)
257
258 # The Rietveld issue associated with the branch.
259 if self.verbosity >= 2:
260 none_text = '' if self.__is_invalid_parent(branch) else 'None'
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000261 (url, color) = self.__status_info[branch]
262 line.append(url or none_text, color=color)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000263
borenet@google.com09156ec2015-03-26 14:10:06 +0000264 # The subject of the most recent commit on the branch.
265 if self.show_subject:
266 line.append(run('log', '-n1', '--format=%s', branch))
267
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000268 self.output.append(line)
269
calamity@chromium.org745ffa62014-09-08 01:03:19 +0000270 for child in sorted(self.__parent_map.pop(branch, ())):
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000271 self.__append_branch(child, depth=depth + 1)
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000272
273
274def main(argv):
iannucci@chromium.orgeed06d62016-04-01 00:59:42 +0000275 colorama.init(wrap="TERM" not in os.environ)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000276 if get_git_version() < MIN_UPSTREAM_TRACK_GIT_VERSION:
277 print >> sys.stderr, (
278 'This tool will not show all tracking information for git version '
279 'earlier than ' +
280 '.'.join(str(x) for x in MIN_UPSTREAM_TRACK_GIT_VERSION) +
281 '. Please consider upgrading.')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000282
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000283 parser = argparse.ArgumentParser(
284 description='Print a a tree of all branches parented by their upstreams')
285 parser.add_argument('-v', action='count',
286 help='Display branch hash and Rietveld URL')
287 parser.add_argument('--no-color', action='store_true', dest='nocolor',
288 help='Turn off colors.')
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000289 parser.add_argument(
290 '-j', '--maxjobs', action='store', type=int,
291 help='The number of jobs to use when retrieving review status')
borenet@google.com09156ec2015-03-26 14:10:06 +0000292 parser.add_argument('--show-subject', action='store_true',
293 dest='show_subject', help='Show the commit subject.')
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000294
sbc@chromium.org013731e2015-02-26 18:28:43 +0000295 opts = parser.parse_args(argv)
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000296
297 mapper = BranchMapper()
298 mapper.verbosity = opts.v
299 mapper.output.nocolor = opts.nocolor
calamity@chromium.orgffde55c2015-03-12 00:44:17 +0000300 mapper.maxjobs = opts.maxjobs
borenet@google.com09156ec2015-03-26 14:10:06 +0000301 mapper.show_subject = opts.show_subject
calamity@chromium.org9d2c8802014-09-03 02:04:46 +0000302 mapper.start()
303 print mapper.output.as_formatted_string()
sbc@chromium.org013731e2015-02-26 18:28:43 +0000304 return 0
iannucci@chromium.org8bc9b5c2014-03-12 01:36:18 +0000305
306if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000307 try:
308 sys.exit(main(sys.argv[1:]))
309 except KeyboardInterrupt:
310 sys.stderr.write('interrupted\n')
311 sys.exit(1)