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 = u"\n"
     34
     35
     36 -class reprop:
     37
     38 -    def __init__(self, templatefile, inputstore, personality, encoding=None,
     39                   remove_untranslated=False):
     40          self.templatefile = templatefile
     41          self.inputstore = inputstore
     42          self.personality = properties.get_dialect(personality)
     43          self.encoding = encoding
     44          if self.encoding is None:
     45              self.encoding = self.personality.default_encoding
     46          self.remove_untranslated = remove_untranslated
     47
     48 -    def convertstore(self, includefuzzy=False):
     49          self.includefuzzy = includefuzzy
     50          self.inmultilinemsgid = False
     51          self.inecho = False
     52          self.inputstore.makeindex()
     53          outputlines = []
     54          # Readlines doesn't work for UTF-16, we read() and splitlines(keepends) instead
     55          content = self.templatefile.read().decode(self.encoding)
     56          for line in content.splitlines(True):
     57              outputstr = self.convertline(line)
     58              outputlines.append(outputstr)
     59          return u"".join(outputlines).encode(self.encoding)
     60
     61 -    def convertline(self, line):
     62          returnline = u""
     63          # handle multiline msgid if we're in one
     64          if self.inmultilinemsgid:
     65              msgid = quote.rstripeol(line).strip()
     66              # see if there's more
     67              self.inmultilinemsgid = (msgid[-1:] == '\\')
     68              # if we're echoing...
     69              if self.inecho:
     70                  returnline = line
     71          # otherwise, this could be a comment
     72          elif line.strip()[:1] == '#':
     73              returnline = quote.rstripeol(line)+eol
     74          else:
     75              line = quote.rstripeol(line)
     76              delimiter_char, delimiter_pos = self.personality.find_delimiter(line)
     77              if quote.rstripeol(line)[-1:] == '\\':
     78                  self.inmultilinemsgid = True
     79              if delimiter_pos == -1:
     80                  key = self.personality.key_strip(line)
     81                  delimiter = " %s " % self.personality.delimiters[0]
     82              else:
     83                  key = self.personality.key_strip(line[:delimiter_pos])
     84                  # Calculate space around the equal sign
     85                  prespace = line[line.find(' ', len(key)):delimiter_pos]
     86                  postspacestart = len(line[delimiter_pos+1:])
     87                  postspaceend = len(line[delimiter_pos+1:].lstrip())
     88                  postspace = line[delimiter_pos+1:delimiter_pos+(postspacestart-postspaceend)+1]
     89                  delimiter = prespace + delimiter_char + postspace
     90              if key in self.inputstore.locationindex:
     91                  unit = self.inputstore.locationindex[key]
     92                  if self.remove_untranslated and (unit.source == unit.target or
     93                                                   unit.isfuzzy() or
     94                                                   len(unit.target) == 0):
     95                      returnline = u""
     96                  else:
     97                      if unit.isfuzzy() and not self.includefuzzy or len(unit.target) == 0:
     98                          value = unit.source
     99                      else:
    100                          value = unit.target
    101                      self.inecho = False
    102                      assert isinstance(value, unicode)
    103                      returnline = "%(key)s%(del)s%(value)s%(term)s%(eol)s" % \
    104                           {"key": "%s%s%s" % (self.personality.key_wrap_char,
    105                                               key,
    106                                               self.personality.key_wrap_char),
    107                            "del": delimiter,
    108                            "value": "%s%s%s" % (self.personality.value_wrap_char,
    109                                                 self.personality.encode(value),
    110                                                 self.personality.value_wrap_char),
    111                            "term": self.personality.pair_terminator,
    112                            "eol": eol,
    113                           }
    114              else:
    115                  self.inecho = True
    116                  returnline = line + eol
    117          assert isinstance(returnline, unicode)
    118          return returnline
    119
    120
    121 -def convertstrings(inputfile, outputfile, templatefile, personality="strings",
    122                     includefuzzy=False, encoding=None,
    123                     remove_untranslated=False):
    124      """.strings specific convertor function"""
    125      return convertprop(inputfile, outputfile, templatefile,
    126                         personality="strings", includefuzzy=includefuzzy,
    127                         encoding=encoding,
    128                         remove_untranslated=remove_untranslated)
    129
    130
    131 -def convertmozillaprop(inputfile, outputfile, templatefile,
    132                         includefuzzy=False, remove_untranslated=False):
    133      """Mozilla specific convertor function"""
    134      return convertprop(inputfile, outputfile, templatefile,
    135                         personality="mozilla", includefuzzy=includefuzzy,
    136                         remove_untranslated=remove_untranslated)
    137
    138
    139 -def convertprop(inputfile, outputfile, templatefile, personality="java",
    140                  includefuzzy=False, encoding=None, remove_untranslated=False):
    141      inputstore = po.pofile(inputfile)
    142      if templatefile is None:
    143          raise ValueError("must have template file for properties files")
    144          # convertor = po2prop()
    145      else:
    146          convertor = reprop(templatefile, inputstore, personality, encoding,
    147                             remove_untranslated)
    148      outputprop = convertor.convertstore(includefuzzy)
    149      outputfile.write(outputprop)
    150      return 1
    151
    152  formats = {
    153      ("po", "properties"): ("properties", convertprop),
    154      ("po", "lang"): ("lang", convertprop),
    155      ("po", "strings"): ("strings", convertstrings),
    156  }
    157
    158
    159 -def main(argv=None):
    160      # handle command line options
    161      from translate.convert import convert
    162      parser = convert.ConvertOptionParser(formats, usetemplates=True,
    163                                           description=__doc__)
    164      parser.add_option("", "--personality", dest="personality",
    165              default=properties.default_dialect, type="choice",
    166              choices=properties.dialects.keys(),
    167              help="override the input file format: %s (for .properties files, default: %s)" %
    168                   (", ".join(properties.dialects.iterkeys()),
    169                    properties.default_dialect),
    170              metavar="TYPE")
    171      parser.add_option("", "--encoding", dest="encoding", default=None,
    172              help="override the encoding set by the personality",
    173              metavar="ENCODING")
    174      parser.add_option("", "--removeuntranslated", dest="remove_untranslated",
    175              default=False, action="store_true",
    176              help="remove key value from output if it is untranslated")
    177      parser.add_fuzzy_option()
    178      parser.passthrough.append("personality")
    179      parser.passthrough.append("encoding")
    180      parser.passthrough.append("remove_untranslated")
    181      parser.run(argv)
    182
    183  if __name__ == '__main__':
    184      main()
    185