Simplify the JSON webcommands by better integration with hg.
authorDirkjan Ochtman <dirkjan@ochtman.nl>
Wed, 06 Aug 2008 15:50:57 +0200
changeset 39 8d8e307c084ed50e7969aaa7b91b199a71c1ed97
parent 38 e4fa26d9ea14031fee573a6868e8a4b7d01c2eea
child 40 ef3a130e1e1487f57d2b4c17ead34830fb702b55
push id15
push usertmielczarek@mozilla.com
push dateWed, 13 Aug 2008 19:07:41 +0000
Simplify the JSON webcommands by better integration with hg.
hgwebjson.py
--- a/hgwebjson.py
+++ b/hgwebjson.py
@@ -1,24 +1,26 @@
 from mercurial import demandimport, context, util
 from mercurial.node import hex, nullid
-import mercurial.hgweb.protocol as hgwebprotocol
-from mercurial.hgweb.common import HTTP_OK, HTTP_NOT_FOUND, HTTP_SERVER_ERROR
-from mercurial.hgweb.hgwebdir_mod import hgwebdir
+from mercurial.hgweb import webcommands
+from mercurial import templatefilters
 
 demandimport.disable()
 import simplejson
 demandimport.enable()
 
 isodate = lambda x: util.datestr(x, '%Y-%m-%d %H:%M %1%2')
 
 class HGJSONEncoder(simplejson.JSONEncoder):
     def __init__(self):
         simplejson.JSONEncoder.__init__(self, indent=1)
 
+    def __call__(self, obj):
+        return self.encode(obj)
+
     def default(self, v):
         if isinstance(v, context.changectx):
             return {'rev':         v.rev(),
                     'node':        hex(v.node()),
                     'user':        v.user(),
                     'date':        isodate(v.date()),
                     'description': v.description(),
                     'branch':      v.branch(),
@@ -34,54 +36,48 @@ class HGJSONEncoder(simplejson.JSONEncod
             return {'filerev':     v.filerev(),
                     'filenode':    hex(v.filenode())}
 
         if hasattr(v, '__iter__'):
             return [o for o in v]
 
         return simplejson.JSONEncoder.default(self, v)
 
+templatefilters.filters['mozjson'] = HGJSONEncoder()
+
 def printjson(ui, repo, *args):
     e = HGJSONEncoder(repo)
     print e.encode([repo.changectx(arg) for arg in args])
 
 # For kicks and testing, add a command-line JSON printer
 
 cmdtable = {
     'printjson': (printjson, [], "hg printjson [rev...]"),
 }
 
 # Add hgweb hooks
 
 def addwebcommand(f, name):
-    setattr(hgwebprotocol, name, f)
-    hgwebprotocol.__all__.append(name)
-
-JSON_MIMETYPE = 'application/json'
+    setattr(webcommands, name, f)
+    webcommands.__all__.append(name)
 
-def heads(web, req):
-    e = HGJSONEncoder()
-    resp = e.encode([web.repo.changectx(n) for n in web.repo.heads()])
-    req.respond(HTTP_OK, JSON_MIMETYPE, length=len(resp))
-    req.write(resp)
+def heads(web, req, tmpl):
+    heads = web.repo.heads()
+    return tmpl('heads', heads=[web.repo.changectx(n) for n in heads])
 
-addwebcommand(heads, 'jsonheads')
+addwebcommand(heads, 'webheads')
 
-def tags(web, req):
-    tags = web.repo.tagslist()
-    e = HGJSONEncoder()
-    resp = e.encode([{'tag': tag,
-                      'changeset': web.repo.changectx(node)}
-                     for tag, node in tags])
-    req.respond(HTTP_OK, JSON_MIMETYPE, length=len(resp))
-    req.write(resp)
+def tags(web, req, tmpl):
+    return tmpl('tags', tags=[{'tag': tag,
+                               'changeset': web.repo.changectx(node)}
+                              for tag, node in web.repo.tagslist()])
 
-addwebcommand(tags, 'jsontags')
+addwebcommand(tags, 'webtags')
 
-def family(web, req):
+def family(web, req, tmpl):
     """Get all the changesets related to a particular node, both children and
     parents, by walking backwards/forwards to a limit."""
 
     node = req.form['node'][0]
     ctx = web.repo.changectx(node)
 
     try:
         limit = int(req.form['limit'][0])
@@ -100,29 +96,19 @@ def family(web, req):
         for p in n.parents():
             if p:
                 nodelist.append(p)
             if curlimit < limit:
                 parents(p, curlimit + 1)
 
     children(ctx, 1)
     parents(ctx, 1)
+    return tmpl('family', family={'context': hex(ctx.node()),
+                                  'nodes': nodelist})
 
-    e = HGJSONEncoder(web.repo)
-    resp = e.encode({'context': hex(ctx.node()),
-                     'nodes': nodelist})
-    req.respond(HTTP_OK, JSON_MIMETYPE, length=len(resp))
-    req.write(resp)
+addwebcommand(family, 'family')
 
-addwebcommand(family, 'jsonfamily')    
-
-def info(web, req):
+def info(web, req, tmpl):
     """Get JSON information about the specified nodes."""
-    e = HGJSONEncoder()
-    d = {}
-    for node in req.form['node']:
-        d[node] = web.repo.changectx(node)
+    nodes = dict((n, web.repo.changectx(n)) for n in req.form['node'])
+    return tmpl('info', nodes=nodes)
 
-    resp = e.encode(d)
-    req.respond(HTTP_OK, JSON_MIMETYPE, length=len(resp))
-    req.write(resp)
-
-addwebcommand(info, 'jsoninfo')
+addwebcommand(info, 'info')