Package translate :: Package tools :: Module porestructure

[hide private]
[frames] | no frames]

# Source Code for Module translate.tools.porestructure

      1  #!/usr/bin/env python
      2  # -*- coding: utf-8 -*-
      3  #
      4  # Copyright 2005, 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  """Restructure Gettxt PO files produced by poconflicts into the original
     23  directory tree for merging using pomerge
     24
     25  See: http://translate.sourceforge.net/wiki/toolkit/porestructure for examples and
     26  usage instructions
     27  """
     28
     29  import sys, os
     30  from translate.storage import po
     31  from translate.misc import optrecurse
     32
     33 -class SplitOptionParser(optrecurse.RecursiveOptionParser):
     34      """a specialized Option Parser for posplit"""
     35 -    def parse_args(self, args=None, values=None):
     36          """parses the command line options, handling implicit input/output args"""
     37          (options, args) = optrecurse.RecursiveOptionParser.parse_args(self, args, values)
     38          if not options.output:
     39              self.error("Output file is rquired")
     40          return (options, args)
     41
     42 -    def set_usage(self, usage=None):
     43          """sets the usage string - if usage not given, uses getusagestring for each option"""
     44          if usage is None:
     45              self.usage = "%prog " + " ".join([self.getusagestring(option) for option in self.option_list]) + \
     46              "\n  input directory is searched for PO files with (poconflicts) comments, all entries are written to files in a directory structure for pomerge"
     47          else:
     48              super(SplitOptionParser, self).set_usage(usage)
     49
     50 -    def recursiveprocess(self, options):
     51          """recurse through directories and process files"""
     52          if not self.isrecursive(options.output, 'output'):
     53              try:
     54                  self.warning("Output directory does not exist. Attempting to create")
     55                  #TODO: maybe we should only allow it to be created, otherwise we mess up an existing tree...
     56                  os.mkdir(options.output)
     57              except:
     58                  self.error(optrecurse.optparse.OptionValueError("Output directory does not exist, attempt to create failed"))
     59          if self.isrecursive(options.input, 'input') and getattr(options, "allowrecursiveinput", True):
     60              if isinstance(options.input, list):
     61                  inputfiles = self.recurseinputfilelist(options)
     62              else:
     63                  inputfiles = self.recurseinputfiles(options)
     64          else:
     65              if options.input:
     66                  inputfiles = [os.path.basename(options.input)]
     67                  options.input = os.path.dirname(options.input)
     68              else:
     69                  inputfiles = [options.input]
     70          self.textmap = {}
     71          self.initprogressbar(inputfiles, options)
     72          for inputpath in inputfiles:
     73              fullinputpath = self.getfullinputpath(options, inputpath)
     74              try:
     75                  success = self.processfile(options, fullinputpath)
     76              except Exception, error:
     77                  if isinstance(error, KeyboardInterrupt):
     78                      raise self.warning("Error processing: input %s" % (fullinputpath), options, sys.exc_info())
     79                  success = False
     80              self.reportprogress(inputpath, success)
     81          del self.progressbar
     82
     83 -    def processfile(self, options, fullinputpath):
     84          """process an individual file"""
     85          inputfile = self.openinputfile(options, fullinputpath)
     86          inputpofile = po.pofile(inputfile)
     87          for pounit in inputpofile.units:
     88              if not (pounit.isheader() or pounit.hasplural()): #XXX
     89                  if pounit.hasmarkedcomment("poconflicts"):
     90                      for comment in pounit.othercomments:
     91                          if comment.find("# (poconflicts)") == 0:
     92                              pounit.othercomments.remove(comment)
     93                              break
     94                      #TODO: refactor writing out
     95                      outputpath = comment[comment.find(")") + 2:].strip()
     96                      self.checkoutputsubdir(options, os.path.dirname(outputpath))
     97                      fulloutputpath = os.path.join(options.output, outputpath)
     98                      if os.path.isfile(fulloutputpath):
     99                          outputfile = open(fulloutputpath, 'r')
    100                          outputpofile = po.pofile(outputfile)
    101                      else:
    102                          outputpofile = po.pofile()
    103                      outputpofile.units.append(pounit)   #TODO:perhaps check to see if it's already there...
    104                      outputfile = open(fulloutputpath, 'w')
    105                      outputfile.write(str(outputpofile))
    106
    107 -def main():
    108      #outputfile extentions will actually be determined by the comments in the po files
    109      pooutput = ("po", None)
    110      formats = {(None, None): pooutput, ("po", "po"): pooutput, "po": pooutput}
    111      parser = SplitOptionParser(formats, description=__doc__)
    112      parser.set_usage()
    113      parser.run()
    114
    115
    116  if __name__ == '__main__':
    117      main()
    118