Package translate :: Package convert :: Module po2prop

[hide private]
[frames] | no frames]

# Source Code for Module translate.convert.po2prop

      1  #!/usr/bin/env python
      2  # -*- coding: utf-8 -*-
      3  #
      4  # Copyright 2002-2006 Zuza Software Foundation
      5  #
      6  # This file is part of translate.
      7  #
      8  # translate is free software; you can redistribute it and/or modify
      9  # it under the terms of the GNU General Public License as published by
     10  # the Free Software Foundation; either version 2 of the License, or
     11  # (at your option) any later version.
     12  #
     13  # translate is distributed in the hope that it will be useful,
     14  # but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16  # GNU General Public License for more details.
     17  #
     18  # You should have received a copy of the GNU General Public License
     19  # along with translate; if not, write to the Free Software
     20  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     21
     22
     23  """convert Gettext PO localization files to Java/Mozilla .properties files
     24
     25  see: http://translate.sourceforge.net/wiki/toolkit/po2prop for examples and
     26  usage instructions
     27  """
     28
     29  from translate.misc import quote
     30  from translate.storage import po
     31  from translate.storage import properties
     32
     33  eol = "\n"
     34
     35
     36 -class reprop:
     37
     38 -    def __init__(self, templatefile, inputstore, personality, encoding=None):
     39          self.templatefile = templatefile
     40          self.inputstore = inputstore
     41          self.personality = properties.get_dialect(personality)
     42          self.encoding = encoding
     43          if self.encoding is None:
     44              self.encoding = self.personality.default_encoding
     45
     46 -    def convertstore(self, includefuzzy=False):
     47          self.includefuzzy = includefuzzy
     48          self.inmultilinemsgid = False
     49          self.inecho = False
     50          self.inputstore.makeindex()
     51          outputlines = []
     52          # Readlines doesn't work for UTF-16, we read() and splitlines(keepends) instead
     53          content = self.templatefile.read().decode(self.encoding)
     54          for line in content.splitlines(True):
     55              outputstr = self.convertline(line)
     56              outputlines.append(outputstr)
     57          return u"".join(outputlines).encode(self.encoding)
     58
     59 -    def convertline(self, line):
     60          returnline = u""
     61          # handle multiline msgid if we're in one
     62          if self.inmultilinemsgid:
     63              msgid = quote.rstripeol(line).strip()
     64              # see if there's more
     65              self.inmultilinemsgid = (msgid[-1:] == '\\')
     66              # if we're echoing...
     67              if self.inecho:
     68                  returnline = line
     69          # otherwise, this could be a comment
     70          elif line.strip()[:1] == '#':
     71              returnline = quote.rstripeol(line)+eol
     72          else:
     73              line = quote.rstripeol(line)
     74              delimiter_char, delimiter_pos = self.personality.find_delimiter(line)
     75              if quote.rstripeol(line)[-1:] == '\\':
     76                  self.inmultilinemsgid = True
     77              if delimiter_pos == -1:
     78                  key = self.personality.key_strip(line)
     79                  delimiter = " %s " % self.personality.delimiters[0]
     80              else:
     81                  key = self.personality.key_strip(line[:delimiter_pos])
     82                  # Calculate space around the equal sign
     83                  prespace = line[line.find(' ', len(key)):delimiter_pos]
     84                  postspacestart = len(line[delimiter_pos+1:])
     85                  postspaceend = len(line[delimiter_pos+1:].lstrip())
     86                  postspace = line[delimiter_pos+1:delimiter_pos+(postspacestart-postspaceend)+1]
     87                  delimiter = prespace + delimiter_char + postspace
     88              if key in self.inputstore.locationindex:
     89                  unit = self.inputstore.locationindex[key]
     90                  if unit.isfuzzy() and not self.includefuzzy or len(unit.target) == 0:
     91                      value = unit.source
     92                  else:
     93                      value = unit.target
     94                  self.inecho = False
     95                  assert isinstance(value, unicode)
     96                  returnline = "%(key)s%(del)s%(value)s%(term)s%(eol)s" % \
     97                       {"key": "%s%s%s" % (self.personality.key_wrap_char,
     98                                           key,
     99                                           self.personality.key_wrap_char),
    100                        "del": delimiter,
    101                        "value": "%s%s%s" % (self.personality.value_wrap_char,
    102                                             self.personality.encode(value),
    103                                             self.personality.value_wrap_char),
    104                        "term": self.personality.pair_terminator,
    105                        "eol": eol,
    106                       }
    107              else:
    108                  self.inecho = True
    109                  returnline = line + eol
    110          assert isinstance(returnline, unicode)
    111          return returnline
    112
    113
    114 -def convertstrings(inputfile, outputfile, templatefile, personality="strings",
    115                         includefuzzy=False, encoding=None):
    116      """.strings specific convertor function"""
    117      return convertprop(inputfile, outputfile, templatefile,
    118                         personality="strings", includefuzzy=includefuzzy,
    119                         encoding=encoding)
    120
    121
    122 -def convertmozillaprop(inputfile, outputfile, templatefile,
    123                         includefuzzy=False):
    124      """Mozilla specific convertor function"""
    125      return convertprop(inputfile, outputfile, templatefile,
    126                         personality="mozilla", includefuzzy=includefuzzy)
    127
    128
    129 -def convertprop(inputfile, outputfile, templatefile, personality="java",
    130                  includefuzzy=False, encoding=None):
    131      inputstore = po.pofile(inputfile)
    132      if templatefile is None:
    133          raise ValueError("must have template file for properties files")
    134          # convertor = po2prop()
    135      else:
    136          convertor = reprop(templatefile, inputstore, personality, encoding)
    137      outputprop = convertor.convertstore(includefuzzy)
    138      outputfile.write(outputprop)
    139      return 1
    140
    141  formats = {
    142      ("po", "properties"): ("properties", convertprop),
    143      ("po", "lang"): ("lang", convertprop),
    144      ("po", "strings"): ("strings", convertstrings),
    145  }
    146
    147
    148 -def main(argv=None):
    149      # handle command line options
    150      from translate.convert import convert
    151      parser = convert.ConvertOptionParser(formats, usetemplates=True,
    152                                           description=__doc__)
    153      parser.add_option("", "--personality", dest="personality",
    154              default=properties.default_dialect, type="choice",
    155              choices=properties.dialects.keys(),
    156              help="override the input file format: %s (for .properties files, default: %s)" %
    157                   (", ".join(properties.dialects.iterkeys()),
    158                    properties.default_dialect),
    159              metavar="TYPE")
    160      parser.add_option("", "--encoding", dest="encoding", default=None,
    161              help="override the encoding set by the personality",
    162              metavar="ENCODING")
    163      parser.add_fuzzy_option()
    164      parser.passthrough.append("personality")
    165      parser.passthrough.append("encoding")
    166      parser.run(argv)
    167
    168  if __name__ == '__main__':
    169      main()
    170