1 # Minimal support for git commands on an hg repository
3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2, incorporated herein by reference.
8 '''browse the repository in a graphical way
10 The hgk extension allows browsing the history of a repository in a
11 graphical way. It requires Tcl/Tk version 8.4 or later. (Tcl/Tk is not
12 distributed with Mercurial.)
14 hgk consists of two parts: a Tcl script that does the displaying and
15 querying of information, and an extension to Mercurial named hgk.py,
16 which provides hooks for hgk to get information. hgk can be found in
17 the contrib directory, and the extension is shipped in the hgext
18 repository, and needs to be enabled.
20 The hg view command will launch the hgk Tcl script. For this command
21 to work, hgk must be in your search path. Alternately, you can specify
22 the path to hgk in your .hgrc file::
27 hgk can make use of the extdiff extension to visualize revisions.
28 Assuming you had already configured extdiff vdiff command, just add::
33 Revisions context menu will now display additional entries to fire
34 vdiff on hovered and selected revisions.
38 from mercurial import commands, util, patch, revlog, cmdutil
39 from mercurial.node import nullid, nullrev, short
40 from mercurial.i18n import _
42 def difftree(ui, repo, node1=None, node2=None, *files, **opts):
43 """diff trees from two commits"""
44 def __difftree(repo, node1, node2, files=[]):
45 assert node2 is not None
46 mmap = repo[node1].manifest()
47 mmap2 = repo[node2].manifest()
48 m = cmdutil.match(repo, files)
49 modified, added, removed = repo.status(node1, node2, m)[:3]
53 # TODO get file permissions
54 ui.write(":100664 100664 %s %s M\t%s\t%s\n" %
55 (short(mmap[f]), short(mmap2[f]), f, f))
57 ui.write(":000000 100664 %s %s N\t%s\t%s\n" %
58 (empty, short(mmap2[f]), f, f))
60 ui.write(":100664 000000 %s %s D\t%s\t%s\n" %
61 (short(mmap[f]), empty, f, f))
67 line = raw_input().split(' ')
75 node1 = repo.lookup(node1)
77 node2 = repo.lookup(node2)
80 node1 = repo.changelog.parents(node1)[0]
83 catcommit(ui, repo, node2, "")
84 m = cmdutil.match(repo, files)
85 chunks = patch.diff(repo, node1, node2, match=m,
86 opts=patch.diffopts(ui, {'git': True}))
90 __difftree(repo, node1, node2, files=files)
94 def catcommit(ui, repo, n, prefix, ctx=None):
95 nlprefix = '\n' + prefix;
98 ui.write("tree %s\n" % short(ctx.changeset()[0])) # use ctx.node() instead ??
99 for p in ctx.parents():
100 ui.write("parent %s\n" % p)
103 description = ctx.description().replace("\0", "")
104 lines = description.splitlines()
105 if lines and lines[-1].startswith('committer:'):
106 committer = lines[-1].split(': ')[1].rstrip()
108 committer = ctx.user()
110 ui.write("author %s %s %s\n" % (ctx.user(), int(date[0]), date[1]))
111 ui.write("committer %s %s %s\n" % (committer, int(date[0]), date[1]))
112 ui.write("revision %d\n" % ctx.rev())
113 ui.write("branch %s\n\n" % ctx.branch())
116 ui.write("%s%s\n" % (prefix, description.replace('\n', nlprefix).strip()))
118 ui.write(description + "\n")
122 def base(ui, repo, node1, node2):
123 """output common ancestor information"""
124 node1 = repo.lookup(node1)
125 node2 = repo.lookup(node2)
126 n = repo.changelog.ancestor(node1, node2)
127 ui.write(short(n) + "\n")
129 def catfile(ui, repo, type=None, r=None, **opts):
130 """cat a specific revision"""
131 # in stdin mode, every line except the commit is prefixed with two
132 # spaces. This way the our caller can find the commit without magic
138 (type, r) = raw_input().split(' ');
144 if not type or not r:
145 ui.warn(_("cat-file: type or revision not supplied\n"))
146 commands.help_(ui, 'cat-file')
150 ui.warn(_("aborting hg cat-file only understands commits\n"))
153 catcommit(ui, repo, n, prefix)
156 (type, r) = raw_input().split(' ');
162 # git rev-tree is a confusing thing. You can supply a number of
163 # commit sha1s on the command line, and it walks the commit history
164 # telling you which commits are reachable from the supplied ones via
165 # a bitmask based on arg position.
166 # you can specify a commit to stop at by starting the sha1 with ^
167 def revtree(ui, args, repo, full="tree", maxnr=0, parents=False):
180 for x in xrange(chunk):
182 l[chunk - x:] = [0] * (chunk - x)
186 l[x].changeset() # force reading
189 for x in xrange(chunk-1, -1, -1):
191 yield (i + x, full != None and l[x] or None)
195 # calculate and return the reachability bitmask for sha
196 def is_reachable(ar, reachable, sha):
200 for i in xrange(len(ar)):
201 if sha in reachable[i]:
211 # figure out which commits they are asking for and which ones they
213 for i, arg in enumerate(args):
214 if arg.startswith('^'):
215 s = repo.lookup(arg[1:])
219 want_sha1.append(repo.lookup(arg))
221 # calculate the graph for the supplied commits
222 for i, n in enumerate(want_sha1):
223 reachable.append(set());
230 for p in repo.changelog.parents(n):
231 if p not in reachable[i]:
237 # walk the repository looking for commits that are in our
239 for i, ctx in chlogwalk():
240 n = repo.changelog.node(i)
241 mask = is_reachable(want_sha1, reachable, n)
245 pp = repo.changelog.parents(n)
247 parentstr += " " + short(pp[0])
249 parentstr += " " + short(pp[1])
251 ui.write("%s%s\n" % (short(n), parentstr))
252 elif full == "commit":
253 ui.write("%s%s\n" % (short(n), parentstr))
254 catcommit(ui, repo, n, ' ', ctx)
256 (p1, p2) = repo.changelog.parents(n)
257 (h, h1, h2) = map(short, (n, p1, p2))
258 (i1, i2) = map(repo.changelog.rev, (p1, p2))
261 ui.write("%s %s:%s" % (date, h, mask))
262 mask = is_reachable(want_sha1, reachable, p1)
263 if i1 != nullrev and mask > 0:
264 ui.write("%s:%s " % (h1, mask)),
265 mask = is_reachable(want_sha1, reachable, p2)
266 if i2 != nullrev and mask > 0:
267 ui.write("%s:%s " % (h2, mask))
269 if maxnr and count >= maxnr:
273 def revparse(ui, repo, *revs, **opts):
274 """parse given revisions"""
278 return revlog.hex(repo.lookup(rev))
281 revrange = r.split(':', 1)
282 ui.write('%s\n' % revstr(revrange[0]))
283 if len(revrange) == 2:
284 ui.write('^%s\n' % revstr(revrange[1]))
286 # git rev-list tries to order things by date, and has the ability to stop
287 # at a given commit without walking the whole repo. TODO add the stop
289 def revlist(ui, repo, *revs, **opts):
290 """print revisions"""
295 copy = [x for x in revs]
296 revtree(ui, copy, repo, full, opts['max_count'], opts['parents'])
298 def config(ui, repo, **opts):
299 """print extension options"""
300 def writeopt(name, value):
301 ui.write('k=%s\nv=%s\n' % (name, value))
303 writeopt('vdiff', ui.config('hgk', 'vdiff', ''))
306 def view(ui, repo, *etc, **opts):
307 "start interactive history viewer"
309 optstr = ' '.join(['--%s %s' % (k, v) for k, v in opts.iteritems() if v])
310 cmd = ui.config("hgk", "path", "hgk") + " %s %s" % (optstr, " ".join(etc))
311 ui.debug(_("running %s\n") % cmd)
317 [('l', 'limit', '', _('limit number of changes displayed'))],
318 _('hg view [-l LIMIT] [REVRANGE]')),
321 [('p', 'patch', None, _('generate patch')),
322 ('r', 'recursive', None, _('recursive')),
323 ('P', 'pretty', None, _('pretty')),
324 ('s', 'stdin', None, _('stdin')),
325 ('C', 'copy', None, _('detect copies')),
326 ('S', 'search', "", _('search'))],
327 _('hg git-diff-tree [OPTION]... NODE1 NODE2 [FILE]...')),
330 [('s', 'stdin', None, _('stdin'))],
331 _('hg debug-cat-file [OPTION]... TYPE FILE')),
333 (config, [], _('hg debug-config')),
335 (base, [], _('hg debug-merge-base REV REV')),
338 [('', 'default', '', _('ignored'))],
339 _('hg debug-rev-parse REV')),
342 [('H', 'header', None, _('header')),
343 ('t', 'topo-order', None, _('topo-order')),
344 ('p', 'parents', None, _('parents')),
345 ('n', 'max-count', 0, _('max-count'))],
346 _('hg debug-rev-list [OPTION]... REV...')),