Package translate :: Package convert :: Module po2php

[hide private]
[frames] | no frames]

# Source Code for Module translate.convert.po2php

      1  #!/usr/bin/env python
      2  # -*- coding: utf-8 -*-
      3  #
      4  # Copyright 2002-2008 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 PHP localization files
     24
     25  see: http://translate.sourceforge.net/wiki/toolkit/po2php 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 php
     32
     33  eol = "\n"
     34
     35 -class rephp:
     36 -    def __init__(self, templatefile):
     37          self.templatefile = templatefile
     38          self.inputdict = {}
     39
     40 -    def convertstore(self, inputstore, includefuzzy=False):
     41          self.inmultilinemsgid = False
     42          self.inecho = False
     43          self.makestoredict(inputstore, includefuzzy)
     44          outputlines = []
     45          for line in self.templatefile.readlines():
     46              outputstr = self.convertline(line)
     47              outputlines.append(outputstr)
     48          return outputlines
     49
     50 -    def makestoredict(self, store, includefuzzy=False):
     51          '''make a dictionary of the translations'''
     52          for unit in store.units:
     53              if includefuzzy or not unit.isfuzzy():
     54                  for location in unit.getlocations():
     55                      inputstring = unit.target
     56                      if len(inputstring.strip()) == 0:
     57                          inputstring = unit.source
     58                      self.inputdict[location] = inputstring
     59
     60 -    def convertline(self, line):
     61          line = unicode(line, 'utf-8')
     62          returnline = ""
     63          # handle multiline msgid if we're in one
     64          if self.inmultilinemsgid:
     65              # see if there's more
     66              endpos = line.rfind("%s;" % self.quotechar)
     67              # if there was no '; or the quote is escaped, we have to continue
     68              if endpos >= 0 and line[endpos-1] != '\\':
     69                  self.inmultilinemsgid = False
     70              # if we're echoing...
     71              if self.inecho:
     72                  returnline = line
     73          # otherwise, this could be a comment
     74          elif line.strip()[:2] == '//' or line.strip()[:2] == '/*':
     75              returnline = quote.rstripeol(line)+eol
     76          else:
     77              line = quote.rstripeol(line)
     78              equalspos = line.find('=')
     79              hashpos = line.find("#")
     80              # if no equals, just repeat it
     81              if equalspos == -1:
     82                  returnline = quote.rstripeol(line)+eol
     83              elif 0 <= hashpos < equalspos:
     84                  # Assume that this is a '#' comment line
     85                  returnline = quote.rstripeol(line)+eol
     86              # otherwise, this is a definition
     87              else:
     88                  # now deal with the current string...
     89                  key = line[:equalspos].strip()
     90                  lookupkey = key.replace(" ", "")
     91                  # Calculate space around the equal sign
     92                  prespace = line[len(line[:equalspos].rstrip()):equalspos]
     93                  postspacestart = len(line[equalspos+1:])
     94                  postspaceend = len(line[equalspos+1:].lstrip())
     95                  postspace = line[equalspos+1:equalspos+(postspacestart-postspaceend)+1]
     96                  self.quotechar = line[equalspos+(postspacestart-postspaceend)+1]
     97                  inlinecomment_pos = line.rfind("%s;" % self.quotechar)
     98                  if inlinecomment_pos > -1:
     99                      inlinecomment = line[inlinecomment_pos+2:]
    100                  else:
    101                      inlinecomment = ""
    102                  if self.inputdict.has_key(lookupkey):
    103                      self.inecho = False
    104                      value = php.phpencode(self.inputdict[lookupkey], self.quotechar)
    105                      if isinstance(value, str):
    106                          value = value.decode('utf8')
    107                      returnline = key + prespace + "=" + postspace + self.quotechar + value + self.quotechar + ';' + inlinecomment + eol
    108                  else:
    109                      self.inecho = True
    110                      returnline = line+eol
    111                  # no string termination means carry string on to next line
    112                  endpos = line.rfind("%s;" % self.quotechar)
    113                  # if there was no '; or the quote is escaped, we have to continue
    114                  if endpos == -1 or line[endpos-1] == '\\':
    115                      self.inmultilinemsgid = True
    116          if isinstance(returnline, unicode):
    117              returnline = returnline.encode('utf-8')
    118          return returnline
    119
    120 -def convertphp(inputfile, outputfile, templatefile, includefuzzy=False):
    121      inputstore = po.pofile(inputfile)
    122      if templatefile is None:
    123          raise ValueError("must have template file for php files")
    124          # convertor = po2php()
    125      else:
    126          convertor = rephp(templatefile)
    127      outputphplines = convertor.convertstore(inputstore, includefuzzy)
    128      outputfile.writelines(outputphplines)
    129      return 1
    130
    131 -def main(argv=None):
    132      # handle command line options
    133      from translate.convert import convert
    134      formats = {("po", "php"): ("php", convertphp)}
    135      parser = convert.ConvertOptionParser(formats, usetemplates=True, description=__doc__)
    136      parser.add_fuzzy_option()
    137      parser.run(argv)
    138
    139  if __name__ == '__main__':
    140      main()
    141