Commits

Jesper Nøhr committed df0f64a

basic marshaller

  • Participants
  • Parent commits 3ed879b

Comments (0)

Files changed (2)

-import simplejson
+import simplejson, types
 from twisted.internet.protocol import Factory, Protocol
 from twisted.protocols.basic import LineOnlyReceiver
 
 from mercurial import hg, ui
 
-class JSONReply(object):
+class JSONMarshaller(object):
+    RAW_TYPES = [ types.StringType, types.BooleanType, types.DictType,
+                  types.DictionaryType, types.FloatType, types.IntType,
+                  types.ListType, types.LongType, types.NoneType,
+                  types.TupleType, types.UnicodeType ]
+
     def __init__(self, obj):
         self.obj = obj
         
-    def to_json(self):
-        return simplejson.dumps({"reply": "ok.", "id": id(self.obj) })
+    def is_raw(self, obj=None):
+        if obj is None:
+            obj = self.obj
+            
+        for type_ in JSONMarshaller.RAW_TYPES:
+            if isinstance(self.obj, type_):
+                return True
+
+        return False
+        
+    def to_json(self, kwd={ 'reply': 'ok.' }):
+        if self.is_raw():
+            kwd.update({ 'data': self.obj })
+        else:
+            for attr in dir(self.obj):
+                if self.is_raw(attr):
+                    kwd.update({attr:getattr(self.obj, attr)})
+        
+        kwd.update({'id':id(self.obj)})
+            
+        return simplejson.dumps(kwd)
 
 class Hub(LineOnlyReceiver):
     def connectionMade(self):
             ret = cmd(dso['args'])
             id_ = id(ret)
             self.stack[id_] = ret
-            reply = JSONReply(ret)
+            reply = JSONMarshaller(ret)
             self.respond(reply.to_json())
         else:
             self.respond('what?')

tests/example-fs/ehub.py

 
 class fakerepo(object):
     def changectx(self, *args):
-        print "call to changectx with args", args
         return { 'changectx': 'reply' }
 
 class EFSHub(Hub):
     def remote_repository(self, *args):
         return fakerepo()
+        
+    def remote_complex(self, *args):
+        return { 'more': 'complex', 'object': 42 }
 
 class EFSHubFactory(HubFactory):
     protocol = EFSHub