Source

hg-compass / compass.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#!/usr/bin/python

# =============================================================================
#
#    hg-compass - Mercurial compass extension
#    Copyright (C) 2009 Oben Sonne <obensonne@googlemail.com>
#
#    This file is part of hg-compass.
#
#    hg-compass is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    hg-compass is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with hg-compass. If not, see <http://www.gnu.org/licenses/>.
#
# =============================================================================

"""navigate in a repository with multiple heads and branches

The compass extension helps to find your way in repositories with multiple
heads, branches and bookmarks. Compass shows where you are, where you could be
and what happens on update or commit.

Requires Mercurial >= 1.3

You can run `tests/extra/build-repo.sh` to create a somewhat freaky repository.
In this repository update to different revisions and run `hg compass` to see
what this extension has to say.

Website: http://bitbucket.org/obensonne/hg-compass

"""

import os.path
import re
import time

from mercurial.context import changectx
from mercurial import bookmarks

# =============================================================================
# constants
# =============================================================================

MLL = 79 # maximum line length for output

NI_TMPL="""
Rev {rev:6} {branch} {bookmarks}{fill:}{tags}{labels}[{age:10}]
"""

NI_TMPL_VERBOSE="""
Rev {rev:6} {branch} {bookmarks}{fill:}{tags}{labels}[{age:10}]
           {desc:}
"""

BI_TMPL="""
{name} {labels:}{heads} heads ({active} active, {inactive} inactive, {bookmarked} bookmarked)
"""

# =============================================================================
# utility classes
# =============================================================================

class RepoInfo(object):
    """Various information about the repository."""
    
    def __init__(self, repo, opts):
        
        self.repo = repo
        self.out_closed = not opts["hide_closed"]
        self.out_inactive = not opts["hide_inactive"]
        
        # all head revisions
        self.head_revs = _csi2rev(repo, repo.heads())
        
        # name of currently active bookmark
        self.bm_current = bookmarks.readcurrent(repo)
        
        # all bookmarked revisions
        bm_names = bookmarks.read(repo).keys()
        self.bm_revs = [repo[x].rev() for x in bm_names]
        
        # branch info objects, heads and tips
        self.bi_map = {} # BranchInfo map
        self.bh_revs = [] # branch head revisions
        for branch, bh_nodes in repo.branchmap().items():
            bh_revs = _csi2rev(repo, bh_nodes)
            bi = BranchInfo(self, branch, bh_revs, opts["verbose"])
            self.bi_map[branch] = bi
            if self.out_closed or not bi.closed:
                self.bh_revs += bh_revs
        self.bh_revs = list(set(self.bh_revs))
        
        # exclude head revisions from closed branches:
        self.head_revs = [x for x in self.head_revs if x in self.bh_revs]
        
        # all _inactive_ branch head revisions
        self.bh_revs_ia = self.out_inactive and [x for x in self.bh_revs if not x in self.head_revs] or []

        # all _inactive_ bookmarked revisions
        self.bm_revs_ia = self.out_inactive and [x for x in self.bm_revs if not x in self.head_revs] or []
        
        # all bookmarked and branch head revisions
        self.bh_and_bm_revs = list(set(self.bh_revs + self.bm_revs))
        
        # all _inactive_ bookmarked and branch head revisions
        self.bh_and_bm_revs_ia = set(self.bh_revs_ia + self.bm_revs_ia)
        
    def head_revs_above(self, ctx):
        
        revs = _csi2rev(self.repo, self.repo.heads(ctx.node()))
        if ctx.rev() in revs:
            revs.remove(ctx.rev())
        return revs
    
class BranchInfo(object):
    """Various information about a branch."""
    
    def __init__(self, ri, name, bh_revs, verbose):
        
        self.name = name
        
        self.tip_rev = _csi2rev(ri.repo, ri.repo.branchtags()[name])
        self.head_revs = bh_revs
        self.head_revs_bm = [x for x in self.head_revs if x in ri.bm_revs]
        self.head_revs_active = [x for x in self.head_revs if x in ri.head_revs]
        self.head_revs_inactive = [x for x in self.head_revs
                                   if not x in ri.head_revs]
        
        self.closed = ri.repo[self.tip_rev].extra().get('close', '0') == '1'
        
        self.labels = self.closed and ["closed"] or []

    def __str__(self):
        """Get a nice string representation of this branch."""
        
        td = {}
        td["name"] = self.name
        td["heads"] = len(self.head_revs)
        td["active"] = len(self.head_revs_active)
        td["inactive"] = len(self.head_revs_inactive)
        td["bookmarked"] = len(self.head_revs_bm)
        td["labels"] = _slist(self.labels, sep=", ", pre="(", suf=")")
        
        return _template(BI_TMPL, td)

class NodeInfo(object):
    """Various information about a node (a.k.a. changeset)."""
    
    def __init__(self, ri, ctx, verbose):
        """Create a new node information object.
        
        @param ri:
            a RepoInfo object
        @param ctx:
            the node's change context
        @keyword short:
            whether to provide detailed or short output in __str__()
            
        """
        self.ri = ri
        self.ctx = ctx
        self.verbose = verbose

        self.rev = ctx.rev()
        self.branch = ctx.branch()
        self.bi = ri.bi_map[self.branch]
        self.bookmarks = ctx.bookmarks()
        self.tags = ctx.tags()
        self.labels = []
        if self.bi.closed:
            self.labels.append("closed")
        if self.rev == self.bi.tip_rev:
            self.labels.append("b-tip")
        elif not self.tags and not self.bookmarks:
            self.labels.append("anon")
        self.desc = ctx.changeset()[4]
        self.time = ctx.changeset()[2][0]
        
    def __str__(self):
        """Get a nice string representation of this node."""
        
        td = {}
        td["rev"] = self.rev
        td["desc"] = self.desc
        td["age"] = self.__format_age()
        td["branch"] = self.branch
        td["bookmarks"] = _slist(self.bookmarks, pre="(", suf=")")
        if self.ctx == self.ri.repo["."]:
            td["bookmarks"] = re.sub(r'([( ])(%s)([ )])' % self.ri.bm_current,
                                     r'\1\2*\3', td["bookmarks"])
        td["tags"] = _slist(self.tags, suf=" ")
        self.labels = [("@%s" % x) for x in self.labels]
        td["labels"] = _slist(self.labels, suf=" ")
        
        if self.verbose:
            return _template(NI_TMPL_VERBOSE, td)
        else:
            return _template(NI_TMPL, td)

    def __format_age(self):
        """Get an age string for this node, e.g. '45 minutes'."""
        
        seconds = int(time.time() - self.time)
        minutes = seconds // 60
        hours = minutes // 60
        days = hours // 24
        months = days // 31
        years = days // 365
        
        for unit in ((years, "years"), (months, "months"), (days, "days"),
                     (hours, "hours"), (minutes, "minutes")):
            if unit[0]:
                return "%d %s" % unit
            
        return "%d seconds" % seconds
        
# =============================================================================
# utility functions
# =============================================================================

def _slist(l, sep=' ', alt='', pre='', suf=''):
    """List to string.
    
    @param l: the list
    @keyword sep: element separator
    @keyword alt: alternative string if list is empty
    @keyword pre: prefix for returned string if list is *not* empty
    @keyword suf: suffix for returned string if list is *not* empty
    
    @return: list as a string
    
    """
    s = sep.join([str(x) for x in l])
    s = s and "%s%s%s" % (pre, s, suf) or alt
    return s

def _csi2rev(repo, csi):
    """Convert changeset identifier(s) to local revision number(s).
    
    @param csi: a (list of) changeset identifier - a node, tag, branch,
        bookmark, changectx or already a revision number
        
    @return: the corresponding (list of) revision number(s)
    
    """
    if isinstance(csi, list) or isinstance(csi, tuple):
        csi = [isinstance(x, changectx) and x.node() or x for x in csi]
        return [repo[x].rev() for x in csi] # list of csi's
    else:
        csi = isinstance(csi, changectx) and csi.node() or csi
        return repo[csi].rev() # single csi
            
def _template(tmpl, td):
    """Evaluate a node info template."""
    
    # sanitize input
    tmpl = tmpl.strip("\n")
    tmpl = tmpl.split('\n')
    for key, value in td.items():
        td[key] = str(value)
    td["fill"] = ""
    
    # compile regular expressions
    re_patt_exp = re.compile(r'{(\w+):}')
    re_patt_fix = re.compile(r'{(\w+):(-?[0-9]+)}')
    re_patt_std = re.compile(r'{(\w+)}')

    output = ""
    
    # iterate template lines
    for line in tmpl:
            
        # standard elements #
        matches = re_patt_std.findall(line)
        for key in matches:
            value = td[key]
            line = line.replace("{%s}" % key, value)

        # fixed length elements #
        matches = re_patt_fix.findall(line)
        for key, slen in matches:
            slen = int(slen)
            value = td[key]
            if slen < 0:
                value = value.ljust(abs(slen))
            else:
                value = value.rjust(slen)
            line = line.replace("{%s:%s}" % (key, slen), value)
        
        # expanding element #
        line_tmp = re_patt_exp.sub("", line)
        slen = max(MLL - len(line_tmp), 0)
        matches = re_patt_exp.findall(line)
        if matches:
            key = matches[0]
            value = td[key].split('\n')[0]
            if len(value) > slen:
                value = "%s..." % value[:(slen-3)]
            else:
                value = value.ljust(slen)
            line = line.replace("{%s:}" % key, value)
        
        output += "%s\n" % line
        #print(line)
        
    return output

def _header(title, em="#", fc="-"):
    """Get a nice header string for the given title."""
    
    sep = "%s%s%s" % (em ,fc * (MLL - 2), em)
    title = "%s%s%s" % (em, title.center(MLL - 2), em)
    return "%s\n%s\n%s\n" % (sep, title, sep)

# =============================================================================
# extension interface
# =============================================================================

def compass(ui, repo, **opts):
    """Show where you are, where you could be and where you go on commit.
    
    Compass lists information about the working dir's parent revision and
    various other relevant revisions grouped by heads, inactive branch heads
    and inactive bookmarks. For each listed revision it prints a line like:
    
    'Rev. <REV-NUMBER> <BRANCH_NAME> (<BOOKMARKS>) <TAGS+LABELS> [<REV-AGE>]'
    
    Labels are generated dynamically (not stored anywhere) and start with `@`:

    :@above:  revision is a head revision above your current revision
    :@anon:   revision is anonymous, i.e. the only way to update to is
              specifying its revision number
    :@b-tip:  revision is tip of its branch, i.e. you'll get to this revision
              when updating to its branch name
    :@closed: revision is part of a closed branch
     
    Finally compass prints out an overview about all existing branches and
    prints a warning if a commit will create a new head.
    
    """
    if not repo.changelog:
        ui.write(_header("You are in a virgin repository", fc="="))    
        return
    
    opts["verbose"] = ui.verbose
    
    ctx = repo["."]
    
    ### get info bout repo and working dir parent ###
    
    ri = RepoInfo(repo, opts)
    ni = NodeInfo(ri, ctx, ui.verbose)

    ### current location ###
    
    wcparents = repo[None].parents()
    if len(wcparents) > 1:
        location = "in a merge (with revision %s)" % wcparents[1].rev()
    elif ni.rev in ri.head_revs:
        location = "at a head"
    elif ni.rev in ri.bh_revs_ia:
        location = "at an inactive branch head"
    elif ni.rev in ri.bm_revs_ia:
        location = "at an inactive bookmark"
    elif ni.tags:
        location = "at a tagged revision"
    else:
        location = "lost in the middle of nowhere"
    
    if ni.bi.closed:
        location += " in a closed branch"
    
    s = ""
    s += _header("You are %s" % location, fc="=")
    s += str(ni)
    
    ### other points of interest ###
    
    # heads
    ni_list = []
    head_revs_above = ri.head_revs_above(ctx)
    for rev in ri.head_revs:
        if rev == ni.rev:
            continue
        head_ni = NodeInfo(ri, repo[rev], ui.verbose)
        if rev in head_revs_above:
            head_ni.labels.insert(0, "above")
        ni_list.append(head_ni)
    title = ni.rev in ri.head_revs and "Other heads" or "Heads"
    s += _slist(ni_list, sep="", pre=_header(title)) 
    
    # inactive heads
    if not opts["hide_inactive"]:
        ni_list = []
        for rev in ri.bh_revs_ia:
            ni_list.append(NodeInfo(ri, repo[rev], ui.verbose))
        s += _slist(ni_list, sep="", pre=_header("Inactive branch heads")) 
    
    # inactive bookmarks
    if not opts["hide_inactive"]:
        ni_list = []
        for rev in ri.bm_revs_ia:
            if not rev in ri.bh_revs_ia:
                ni_list.append(NodeInfo(ri, repo[rev], ui.verbose))
        s += _slist(ni_list, sep="", pre=_header("Inactive bookmarks")) 
            
    ### branch overview ###

    if not opts["hide_branch_overview"]:
        s += _header("Branch overview")
        for bi in ri.bi_map.values():
            if not bi.closed or not opts["hide_closed"]:
                if bi.name == ni.branch:
                    bi.name += "*"
                s += str(bi)
    
    ### commit warning for current location ###
    
    if not ni.rev in ri.head_revs:
        s += _header("Next commit will create a new head!", fc="-")
    
    ui.write(s)
    
# =============================================================================
# command table
# =============================================================================

cmdtable = {
    "compass": (compass,
                [('b', 'hide-branch-overview', False, 'hide branch overview'),
                 ('i', 'hide-inactive', False,
                  'hide inactive branch heads and bookmarks'),
                 ('c', 'hide-closed', False, 'hide closed branches'),
                 ],
                "[options]")
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.