wurfl2python

Module wurfl2python |
[hide private]
[frames] | no frames]

# Source Code for Module wurfl2python

      1  #!/usr/bin/env python
      2  # WURFL 2 Python - Wireless Universal Resource File to Python conversion utility
      3  # Copyright (C) 2004-2011 Armand Lynch
      4  #
      5  # This library is free software; you can redistribute it and/or modify it
      6  # under the terms of the GNU Lesser General Public License as published by the
      7  # Free Software Foundation; either version 2.1 of the License, or (at your
      8  # option) any later version.
      9  #
     10  # This library is distributed in the hope that it will be useful, but WITHOUT
     11  # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
     12  # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
     13  # details.
     14  #
     15  # You should have received a copy of the GNU Lesser General Public License
     16  # along with this library; if not, write to the Free Software Foundation, Inc.,
     17  # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
     18  #
     19  # Armand Lynch <lyncha@users.sourceforge.net>
     20
     21  __doc__ = \
     22  """
     23  WURFL <wurfl.sourceforge.net> conversion utility
     24
     25  usage: wurfl2python.py [options] WURFL_XML_FILE
     26  """
     27
     28  import sys
     29  import codecs
     30  from time import ctime
     31
     32  from pywurfl.wurflprocessor import DeviceHandler, WurflProcessor, op, main
     33
     34
     35  __version__ = "5.0.0a"
     36  __license__ = "LGPL"
     37  __copyright__ = "Copyright 2004-2011, Armand Lynch"
     38  __author__ = "Armand Lynch <lyncha@users.sourceforge.net>"
     39  __contributors__ = "Pau Aliagas <pau@newtral.org>"
     40  __url__ = "http://celljam.net/"
     41  __all__ = ['DeviceSerializer']
     42
     43
     44 -class DeviceSerializer(DeviceHandler):
     45
     46      idstr = u"devices.devids[ur'''%s'''] = "
     47      new_caps = idstr + u"devclass(%s, ur'''%s''', ur'''%s''', %s, {%s})\n"
     48      no_caps = idstr + u"devclass(%s, ur'''%s''', ur'''%s''', %s, None)\n"
     49      capability_types = {}
     50
     51 -    def encoded_str(self):
     52          s = []
     53          c = []
     54
     55          if self.parent == u"root":
     56              parent = u"None"
     57          else:
     58              parent = u"devices.devids[ur'''%s''']" % self.parent
     59
     60          for cap in sorted(self.capabilities):
     61              value = self.capabilities[cap]
     62              cap_type = self.capability_types.get(cap, None)
     63              if cap_type == int:
     64                  c.append("ur'''%s''':%d" % (cap, int(value.strip())))
     65              elif cap_type == float:
     66                  c.append("ur'''%s''':%f" % (cap, float(value.strip())))
     67              elif cap_type == bool:
     68                  if value.lower() == "true":
     69                      c.append("ur'''%s''':True" % cap)
     70                  elif value.lower() == "false":
     71                      c.append("ur'''%s''':False" % cap)
     72              else:
     73                  c.append("ur'''%s''':ur'''%s'''" % (cap, value))
     74
     75          if c:
     76              s.append(self.new_caps % (self.devid, parent, self.devid,
     77                                        self.devua, self.actual_device_root,
     78                                        u','.join(c)))
     79          else:
     80              s.append(self.no_caps % (self.devid, parent, self.devid, self.devua,
     81                                       self.actual_device_root))
     82
     83          return u''.join(s)
     84
     85
     86 -class WurflPythonWriter(WurflProcessor):
     87
     88 -    def __init__(self, wurflxml, device_handler=None,
     89                   options={"outfile":"wurfl.py"}):
     90          WurflProcessor.__init__(self, wurflxml, device_handler=device_handler,
     91                                  options=options)
     92          self.groups = {}
     93
     94 -    def handle_device(self, devobj):
     95          self.outfile.write(devobj.encoded_str())
     96
     97 -    def process_options(self):
     98          if self.logfile != sys.stderr:
     99              self.logfile = codecs.open(self.logfile, "wb", "utf8")
    100          if self.outfile is not None:
    101              self.outfile = codecs.open(self.outfile, "wb", "utf8")
    102          else:
    103              self.outfile = codecs.open("wurfl.py", "wb", "utf8")
    104
    105 -    def process_capability(self, devobj, group, capability):
    106          attrs = capability.attrib
    107          devobj.capabilities[attrs["name"]] = attrs["value"]
    108          if devobj.devid == 'generic':
    109              try:
    110                  self.groups[group.get('id')].append(attrs["name"])
    111              except KeyError:
    112                  self.groups[group.get('id')] = []
    113                  self.groups[group.get('id')].append(attrs["name"])
    114
    115 -    def start_process(self):
    116          self.device_handler.capability_types = get_normalized_types(self.tree)
    117
    118          version = self.tree.findtext("*/ver").strip()
    119          self.outfile.write(u"# -*- coding: utf-8 -*-\n")
    120          self.outfile.write(u'"""\n%s\n\n' % self.outfile.name)
    121          self.outfile.write(u"Generated on: %s\n" % ctime())
    122          self.outfile.write(u"Generated by: wurfl2python.py v%s\n" % __version__)
    123          self.outfile.write(u'"""\n\n')
    124          self.outfile.write(u"__all__ = ['devices', 'wurfl_version']\n")
    125          self.outfile.write(u"wurfl_version = '''%s'''\n\n" % version)
    126          self.outfile.write(u"from pywurfl import *\n\n")
    127          self.outfile.write(u"devices = Devices()\n")
    128
    129 -    def end_process(self):
    130          for group, names in self.groups.iteritems():
    131              self.outfile.write(u"devices.devids['''generic'''].groups")
    132              self.outfile.write(u"[ur'''%s'''] = [ur'''%s''']\n" %
    133                                 (group, u"''', ur'''".join(names)))
    134          self.outfile.write(u"\n")
    135          self.outfile.write(u"for device in devices.devids.itervalues():\n")
    136          self.outfile.write(u"    devices.devuas[device.devua] = device\n")
    137          self.outfile.write(u"del device\n")
    138          self.outfile.write(u"\n")
    139
    140
    141 -def get_normalized_types(tree):
    142      caps = {}
    143      for capability in tree.findall("devices/device/group/capability"):
    144          name = capability.attrib['name']
    145          value = capability.attrib['value']
    146          if name not in caps:
    147              try:
    148                  int(value)
    149                  caps[name] = int
    150                  continue
    151              except (TypeError, ValueError):
    152                  pass
    153              try:
    154                  float(value)
    155                  caps[name] = float
    156                  continue
    157              except (TypeError, ValueError):
    158                  pass
    159
    160              if value.strip().lower() in ("true", "false"):
    161                  caps[name] = bool
    162                  continue
    163              else:
    164                  caps[name] = str
    165          else:
    166              if caps[name] == str:
    167                  continue
    168              elif caps[name] == bool:
    169                  if value.strip().lower() in ("true", "false"):
    170                      continue
    171                  else:
    172                      caps[name] = str
    173              elif caps[name] == float:
    174                  try:
    175                      float(value)
    176                      continue
    177                  except (TypeError, ValueError):
    178                      caps[name] = str
    179              elif caps[name] == int:
    180                  try:
    181                      int(value)
    182                      continue
    183                  except (TypeError, ValueError):
    184                      caps[name] = str
    185      return caps
    186
    187
    188  if __name__ == "__main__":
    189      op.add_option("-o", "--output", dest="outfile", default=None,
    190                    help="The name of the module to produce.")
    191      main(WurflPythonWriter, DeviceSerializer, op)
    192