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  import re
     34  from StringIO import StringIO
     35
     36  from translate.misc.ini import INIConfig
     37  from translate.storage import base
     38
     39  _dialects = {}
     40
     41
     42 -def register_dialect(name, dialect):
     43      """Register the dialect"""
     44      _dialects[name] = dialect
     45
     46
     47 -class Dialect(object):
     48      """Base class for differentiating dialect options and functions"""
     49      pass
     50
     51
     52 -class DialectDefault(Dialect):
     53
     54 -    def unescape(self, text):
     55          return text
     56
     57 -    def escape(self, text):
     58          return text
     59  register_dialect("default", DialectDefault)
     60
     61
     62 -class DialectInno(DialectDefault):
     63
     64 -    def unescape(self, text):
     65          return text.replace("%n", "\n").replace("%t", "\t")
     66
     67 -    def escape(self, text):
     68          return text.replace("\t", "%t").replace("\n", "%n")
     69  register_dialect("inno", DialectInno)
     70
     71
     72 -class iniunit(base.TranslationUnit):
     73      """A INI file entry"""
     74
     75 -    def __init__(self, source=None, encoding="UTF-8"):
     76          self.location = ""
     77          if source:
     78              self.source = source
     79          super(iniunit, self).__init__(source)
     80
     81 -    def addlocation(self, location):
     82          self.location = location
     83
     84 -    def getlocations(self):
     85          return [self.location]
     86
     87
     88 -class inifile(base.TranslationStore):
     89      """An INI file"""
     90      UnitClass = iniunit
     91
     92 -    def __init__(self, inputfile=None, unitclass=iniunit, dialect="default"):
     93          """construct an INI file, optionally reading in from inputfile."""
     94          self.UnitClass = unitclass
     95          self._dialect = _dialects.get(dialect, DialectDefault)()  # fail correctly/use getattr/
     96          base.TranslationStore.__init__(self, unitclass=unitclass)
     97          self.units = []
     98          self.filename = ''
     99          self._inifile = None
    100          if inputfile is not None:
    101              self.parse(inputfile)
    102
    103 -    def __str__(self):
    104          _outinifile = self._inifile
    105          for unit in self.units:
    106              for location in unit.getlocations():
    107                  match = re.match('\\[(?P<section>.+)\\](?P<entry>.+)', location)
    108                  _outinifile[match.groupdict()['section']][match.groupdict()['entry']] = self._dialect.escape(unit.target)
    109          if _outinifile:
    110              return str(_outinifile)
    111          else:
    112              return ""
    113
    114 -    def parse(self, input):
    115          """parse the given file or file source string"""
    116          if hasattr(input, 'name'):
    117              self.filename = input.name
    118          elif not getattr(self, 'filename', ''):
    119              self.filename = ''
    120          if hasattr(input, "read"):
    121              inisrc = input.read()
    122              input.close()
    123              input = inisrc
    124          if isinstance(input, str):
    125              input = StringIO(input)
    126              self._inifile = INIConfig(input, optionxformvalue=None)
    127          else:
    128              self._inifile = INIConfig(file(input), optionxformvalue=None)
    129          for section in self._inifile:
    130              for entry in self._inifile[section]:
    131                  newunit = self.addsourceunit(self._dialect.unescape(self._inifile[section][entry]))
    132                  newunit.addlocation("[%s]%s" % (section, entry))
    133