Package translate :: Package storage :: Module ini |
[hide private]
[frames] | no frames]

# Source Code for Module translate.storage.ini

      1  #!/usr/bin/env python
      2  # -*- coding: utf-8 -*-
      3  #
      4  # Copyright 2007,2009 Zuza Software Foundation
      5  #
      6  # This file is part of the Translate Toolkit.
      7  #
      8  # This program 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  # This program 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 this program; if not, see <http://www.gnu.org/licenses/>.
     20
     21  """Class that manages .ini files for translation
     22
     23  @note: A simple summary of what is permissible follows.
     24
     25  # a comment
     26  ; a comment
     27
     28  [Section]
     29  a = a string
     30  b : a string
     31  """
     32
     33  from translate.storage import base
     34  from translate.misc.ini import INIConfig
     35  from StringIO import StringIO
     36  import re
     37
     38  _dialects = {}
     39
     40 -def register_dialect(name, dialect):
     41      """Register the dialect"""
     42      _dialects[name] = dialect
     43
     44 -class Dialect(object):
     45      """Base class for differentiating dialect options and functions"""
     46      pass
     47
     48 -class DialectDefault(Dialect):
     49 -    def unescape(self, text):
     50          return text
     51
     52 -    def escape(self, text):
     53          return text
     54  register_dialect("default", DialectDefault)
     55
     56 -class DialectInno(DialectDefault):
     57 -    def unescape(self, text):
     58          return text.replace("%n", "\n").replace("%t", "\t")
     59
     60 -    def escape(self, text):
     61          return text.replace("\t", "%t").replace("\n", "%n")
     62  register_dialect("inno", DialectInno)
     63
     64
     65 -class iniunit(base.TranslationUnit):
     66      """A INI file entry"""
     67 -    def __init__(self, source=None, encoding="UTF-8"):
     68          self.location = ""
     69          if source:
     70              self.source = source
     71          super(iniunit, self).__init__(source)
     72
     73 -    def addlocation(self, location):
     74          self.location = location
     75
     76 -    def getlocations(self):
     77          return [self.location]
     78
     79 -class inifile(base.TranslationStore):
     80      """An INI file"""
     81      UnitClass = iniunit
     82 -    def __init__(self, inputfile=None, unitclass=iniunit, dialect="default"):
     83          """construct an INI file, optionally reading in from inputfile."""
     84          self.UnitClass = unitclass
     85          self._dialect = _dialects.get(dialect, DialectDefault)()  # fail correctly/use getattr/
     86          base.TranslationStore.__init__(self, unitclass=unitclass)
     87          self.units = []
     88          self.filename = ''
     89          self._inifile = None
     90          if inputfile is not None:
     91              self.parse(inputfile)
     92
     93 -    def __str__(self):
     94          _outinifile = self._inifile
     95          for unit in self.units:
     96              for location in unit.getlocations():
     97                  match = re.match('\\[(?P<section>.+)\\](?P<entry>.+)', location)
     98                  _outinifile[match.groupdict()['section']][match.groupdict()['entry']] = self._dialect.escape(unit.target)
     99          if _outinifile:
    100              return str(_outinifile)
    101          else:
    102              return ""
    103
    104 -    def parse(self, input):
    105          """parse the given file or file source string"""
    106          if hasattr(input, 'name'):
    107              self.filename = input.name
    108          elif not getattr(self, 'filename', ''):
    109              self.filename = ''
    110          if hasattr(input, "read"):
    111              inisrc = input.read()
    112              input.close()
    113              input = inisrc
    114          if isinstance(input, str):
    115              input = StringIO(input)
    116              self._inifile = INIConfig(input, optionxformvalue=None)
    117          else:
    118              self._inifile = INIConfig(file(input), optionxformvalue=None)
    119          for section in self._inifile:
    120              for entry in self._inifile[section]:
    121                  newunit = self.addsourceunit(self._dialect.unescape(self._inifile[section][entry]))
    122                  newunit.addlocation("[%s]%s" % (section, entry))
    123