[or-cvs] r17366: {updater} Add a quick and dirty thandy-client json2xml command. I am g (updater/trunk/lib/thandy)

nickm at seul.org nickm at seul.org
Sat Nov 22 19:13:11 UTC 2008


Author: nickm
Date: 2008-11-22 14:13:10 -0500 (Sat, 22 Nov 2008)
New Revision: 17366

Added:
   updater/trunk/lib/thandy/encodeToXML.py
Modified:
   updater/trunk/lib/thandy/ClientCLI.py
   updater/trunk/lib/thandy/formats.py
   updater/trunk/lib/thandy/tests.py
Log:
Add a quick and dirty thandy-client json2xml command.  I am going to regret this someday.

Modified: updater/trunk/lib/thandy/ClientCLI.py
===================================================================
--- updater/trunk/lib/thandy/ClientCLI.py	2008-11-22 18:23:02 UTC (rev 17365)
+++ updater/trunk/lib/thandy/ClientCLI.py	2008-11-22 19:13:10 UTC (rev 17366)
@@ -5,6 +5,10 @@
 import os
 import sys
 import time
+try:
+    import json
+except ImportError:
+    import simplejson as json
 
 import thandy.formats
 import thandy.util
@@ -13,6 +17,7 @@
 import thandy.master_keys
 import thandy.packagesys.PackageSystem
 import thandy.socksurls
+import thandy.encodeToXML
 
 def update(args):
     repoRoot = thandy.util.userFilename("cache")
@@ -153,14 +158,20 @@
         logging.info("All downloads finished.")
 
 
-# Tell me what to install.
+def json2xml(args):
+    if len(args) != 1:
+        usage()
+    f = open(args[0], 'r')
+    obj = json.load(f)
+    f.close()
+    thandy.encodeToXML.encodeToXML(obj, sys.stdout.write)
 
-
 def usage():
     print "Known commands:"
     print "  update [--repo=repository] [--no-download] [--loop]"
     print "         [--no-packagesys] [--install] [--socks-port=port]"
     print "         [--debug|--info|--warn] [--force-check]"
+    print "  json2xml file"
     sys.exit(1)
 
 def main():
@@ -169,7 +180,7 @@
         usage()
     cmd = sys.argv[1]
     args = sys.argv[2:]
-    if cmd in [ "update" ]:
+    if cmd in [ "update", "json2xml" ]:
         globals()[cmd](args)
     else:
         usage()

Added: updater/trunk/lib/thandy/encodeToXML.py
===================================================================
--- updater/trunk/lib/thandy/encodeToXML.py	                        (rev 0)
+++ updater/trunk/lib/thandy/encodeToXML.py	2008-11-22 19:13:10 UTC (rev 17366)
@@ -0,0 +1,70 @@
+# Copyright 2008 The Tor Project, Inc.  See LICENSE for licensing information.
+
+import re
+
+def xml_str_encoder(s):
+    s = s.replace("&", "&")
+    s = s.replace("<", "&lt;")
+    s = s.replace(">", "&gt;")
+    return s
+
+def isAsciiName(s):
+    """
+       Return true iff s is pure-ascii, and a syntactically valid XML name.
+
+       >>> isAsciiName("a")
+       True
+       >>> isAsciiName("ab.-dc")
+       True
+       >>> isAsciiName("")
+       False
+       >>> isAsciiName(".foo")
+       False
+    """
+    return re.match(r'^[A-Za-z\_\:][A-Za-z0-9\_\:\-\.]*$', s) != None
+
+def _encodeToXML(obj, outf, indent=0):
+    if isinstance(obj, basestring):
+        outf(xml_str_encoder(obj))
+    elif obj is True:
+        outf("true")
+    elif obj is False:
+        outf("false")
+    elif obj is None:
+        outf("null")
+    elif isinstance(obj, (int,long)):
+        outf(str(obj))
+    elif isinstance(obj, (tuple, list)):
+        istr = " "*indent
+        outf("<list>\n")
+        for item in obj:
+            outf("<item>")
+            _encodeToXML(item, outf)
+            outf("</item> ")
+        outf("</list>\n")
+    elif isinstance(obj, dict):
+        outf("<dict>\n")
+        for k,v in sorted(obj.items()):
+            isAscii = isAsciiName(k)
+            if isAscii:
+                outf("<%s>"%k)
+                _encodeToXML(v, outf)
+                outf("</%s>\n"%k)
+            else:
+                outf("<dict-entry><key>%s</key><val>"%xml_str_encoder(k))
+                _encodeToXML(v, outf)
+                outf("</val></dict-entry>\n")
+        outf("</dict>\n")
+    else:
+        raise thandy.FormatException("I can't encode %r"%obj)
+
+def encodeToXML(obj, outf=None):
+    """Convert a json-encodable object to a quick-and-dirty XML equivalent."""
+    result = None
+    if outf == None:
+        outf = result.append
+
+    _encodeToXML(obj, outf)
+    if result is not None:
+        return "".join(result)
+

Modified: updater/trunk/lib/thandy/formats.py
===================================================================
--- updater/trunk/lib/thandy/formats.py	2008-11-22 18:23:02 UTC (rev 17365)
+++ updater/trunk/lib/thandy/formats.py	2008-11-22 19:13:10 UTC (rev 17366)
@@ -173,7 +173,7 @@
     elif obj is True:
         outf("true")
     elif obj is False:
-            outf("false")
+        outf("false")
     elif obj is None:
         outf("null")
     elif isinstance(obj, (int,long)):
@@ -235,7 +235,6 @@
     if result is not None:
         return "".join(result)
 
-
 def getDigest(obj, digestObj=None):
     """Update 'digestObj' (typically a SHA256 object) with the digest of
        the canonical json encoding of obj.  If digestObj is none,

Modified: updater/trunk/lib/thandy/tests.py
===================================================================
--- updater/trunk/lib/thandy/tests.py	2008-11-22 18:23:02 UTC (rev 17365)
+++ updater/trunk/lib/thandy/tests.py	2008-11-22 19:13:10 UTC (rev 17366)
@@ -9,6 +9,7 @@
 import thandy.formats
 import thandy.repository
 import thandy.checkJson
+import thandy.encodeToXML
 import thandy.util
 
 import thandy.tests
@@ -122,6 +123,7 @@
     suite.addTest(doctest.DocTestSuite(thandy.formats))
     suite.addTest(doctest.DocTestSuite(thandy.keys))
     suite.addTest(doctest.DocTestSuite(thandy.checkJson))
+    suite.addTest(doctest.DocTestSuite(thandy.encodeToXML))
 
     loader = unittest.TestLoader()
     suite.addTest(loader.loadTestsFromModule(thandy.tests))



More information about the tor-commits mailing list