home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_331 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  14.9 KB  |  560 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import re
  5. __all__ = [
  6.     'NoSectionError',
  7.     'DuplicateSectionError',
  8.     'NoOptionError',
  9.     'InterpolationError',
  10.     'InterpolationDepthError',
  11.     'InterpolationSyntaxError',
  12.     'ParsingError',
  13.     'MissingSectionHeaderError',
  14.     'ConfigParser',
  15.     'SafeConfigParser',
  16.     'RawConfigParser',
  17.     'DEFAULTSECT',
  18.     'MAX_INTERPOLATION_DEPTH']
  19. DEFAULTSECT = 'DEFAULT'
  20. MAX_INTERPOLATION_DEPTH = 10
  21.  
  22. class Error(Exception):
  23.     
  24.     def _get_message(self):
  25.         return self._Error__message
  26.  
  27.     
  28.     def _set_message(self, value):
  29.         self._Error__message = value
  30.  
  31.     message = property(_get_message, _set_message)
  32.     
  33.     def __init__(self, msg = ''):
  34.         self.message = msg
  35.         Exception.__init__(self, msg)
  36.  
  37.     
  38.     def __repr__(self):
  39.         return self.message
  40.  
  41.     __str__ = __repr__
  42.  
  43.  
  44. class NoSectionError(Error):
  45.     
  46.     def __init__(self, section):
  47.         Error.__init__(self, 'No section: %r' % (section,))
  48.         self.section = section
  49.  
  50.  
  51.  
  52. class DuplicateSectionError(Error):
  53.     
  54.     def __init__(self, section):
  55.         Error.__init__(self, 'Section %r already exists' % section)
  56.         self.section = section
  57.  
  58.  
  59.  
  60. class NoOptionError(Error):
  61.     
  62.     def __init__(self, option, section):
  63.         Error.__init__(self, 'No option %r in section: %r' % (option, section))
  64.         self.option = option
  65.         self.section = section
  66.  
  67.  
  68.  
  69. class InterpolationError(Error):
  70.     
  71.     def __init__(self, option, section, msg):
  72.         Error.__init__(self, msg)
  73.         self.option = option
  74.         self.section = section
  75.  
  76.  
  77.  
  78. class InterpolationMissingOptionError(InterpolationError):
  79.     
  80.     def __init__(self, option, section, rawval, reference):
  81.         msg = 'Bad value substitution:\n\tsection: [%s]\n\toption : %s\n\tkey    : %s\n\trawval : %s\n' % (section, option, reference, rawval)
  82.         InterpolationError.__init__(self, option, section, msg)
  83.         self.reference = reference
  84.  
  85.  
  86.  
  87. class InterpolationSyntaxError(InterpolationError):
  88.     pass
  89.  
  90.  
  91. class InterpolationDepthError(InterpolationError):
  92.     
  93.     def __init__(self, option, section, rawval):
  94.         msg = 'Value interpolation too deeply recursive:\n\tsection: [%s]\n\toption : %s\n\trawval : %s\n' % (section, option, rawval)
  95.         InterpolationError.__init__(self, option, section, msg)
  96.  
  97.  
  98.  
  99. class ParsingError(Error):
  100.     
  101.     def __init__(self, filename):
  102.         Error.__init__(self, 'File contains parsing errors: %s' % filename)
  103.         self.filename = filename
  104.         self.errors = []
  105.  
  106.     
  107.     def append(self, lineno, line):
  108.         self.errors.append((lineno, line))
  109.         self.message += '\n\t[line %2d]: %s' % (lineno, line)
  110.  
  111.  
  112.  
  113. class MissingSectionHeaderError(ParsingError):
  114.     
  115.     def __init__(self, filename, lineno, line):
  116.         Error.__init__(self, 'File contains no section headers.\nfile: %s, line: %d\n%r' % (filename, lineno, line))
  117.         self.filename = filename
  118.         self.lineno = lineno
  119.         self.line = line
  120.  
  121.  
  122.  
  123. class RawConfigParser:
  124.     
  125.     def __init__(self, defaults = None, dict_type = dict):
  126.         self._dict = dict_type
  127.         self._sections = self._dict()
  128.         self._defaults = self._dict()
  129.         if defaults:
  130.             for key, value in defaults.items():
  131.                 self._defaults[self.optionxform(key)] = value
  132.             
  133.         
  134.  
  135.     
  136.     def defaults(self):
  137.         return self._defaults
  138.  
  139.     
  140.     def sections(self):
  141.         return self._sections.keys()
  142.  
  143.     
  144.     def add_section(self, section):
  145.         if section.lower() == 'default':
  146.             raise ValueError, 'Invalid section name: %s' % section
  147.         section.lower() == 'default'
  148.         if section in self._sections:
  149.             raise DuplicateSectionError(section)
  150.         section in self._sections
  151.         self._sections[section] = self._dict()
  152.  
  153.     
  154.     def has_section(self, section):
  155.         return section in self._sections
  156.  
  157.     
  158.     def options(self, section):
  159.         
  160.         try:
  161.             opts = self._sections[section].copy()
  162.         except KeyError:
  163.             raise NoSectionError(section)
  164.  
  165.         opts.update(self._defaults)
  166.         if '__name__' in opts:
  167.             del opts['__name__']
  168.         
  169.         return opts.keys()
  170.  
  171.     
  172.     def read(self, filenames):
  173.         if isinstance(filenames, basestring):
  174.             filenames = [
  175.                 filenames]
  176.         
  177.         read_ok = []
  178.         for filename in filenames:
  179.             
  180.             try:
  181.                 fp = open(filename)
  182.             except IOError:
  183.                 continue
  184.  
  185.             self._read(fp, filename)
  186.             fp.close()
  187.             read_ok.append(filename)
  188.         
  189.         return read_ok
  190.  
  191.     
  192.     def readfp(self, fp, filename = None):
  193.         if filename is None:
  194.             
  195.             try:
  196.                 filename = fp.name
  197.             except AttributeError:
  198.                 filename = '<???>'
  199.             except:
  200.                 None<EXCEPTION MATCH>AttributeError
  201.             
  202.  
  203.         None<EXCEPTION MATCH>AttributeError
  204.         self._read(fp, filename)
  205.  
  206.     
  207.     def get(self, section, option):
  208.         opt = self.optionxform(option)
  209.         if section not in self._sections:
  210.             if section != DEFAULTSECT:
  211.                 raise NoSectionError(section)
  212.             section != DEFAULTSECT
  213.             if opt in self._defaults:
  214.                 return self._defaults[opt]
  215.             raise NoOptionError(option, section)
  216.         section not in self._sections
  217.         if opt in self._sections[section]:
  218.             return self._sections[section][opt]
  219.         if opt in self._defaults:
  220.             return self._defaults[opt]
  221.         raise NoOptionError(option, section)
  222.  
  223.     
  224.     def items(self, section):
  225.         
  226.         try:
  227.             d2 = self._sections[section]
  228.         except KeyError:
  229.             if section != DEFAULTSECT:
  230.                 raise NoSectionError(section)
  231.             section != DEFAULTSECT
  232.             d2 = self._dict()
  233.  
  234.         d = self._defaults.copy()
  235.         d.update(d2)
  236.         if '__name__' in d:
  237.             del d['__name__']
  238.         
  239.         return d.items()
  240.  
  241.     
  242.     def _get(self, section, conv, option):
  243.         return conv(self.get(section, option))
  244.  
  245.     
  246.     def getint(self, section, option):
  247.         return self._get(section, int, option)
  248.  
  249.     
  250.     def getfloat(self, section, option):
  251.         return self._get(section, float, option)
  252.  
  253.     _boolean_states = {
  254.         '1': True,
  255.         'yes': True,
  256.         'true': True,
  257.         'on': True,
  258.         '0': False,
  259.         'no': False,
  260.         'false': False,
  261.         'off': False }
  262.     
  263.     def getboolean(self, section, option):
  264.         v = self.get(section, option)
  265.         if v.lower() not in self._boolean_states:
  266.             raise ValueError, 'Not a boolean: %s' % v
  267.         v.lower() not in self._boolean_states
  268.         return self._boolean_states[v.lower()]
  269.  
  270.     
  271.     def optionxform(self, optionstr):
  272.         return optionstr.lower()
  273.  
  274.     
  275.     def has_option(self, section, option):
  276.         if not section or section == DEFAULTSECT:
  277.             option = self.optionxform(option)
  278.             return option in self._defaults
  279.         if section not in self._sections:
  280.             return False
  281.         option = self.optionxform(option)
  282.         if not option in self._sections[section]:
  283.             pass
  284.         return option in self._defaults
  285.  
  286.     
  287.     def set(self, section, option, value):
  288.         if not section or section == DEFAULTSECT:
  289.             sectdict = self._defaults
  290.         else:
  291.             
  292.             try:
  293.                 sectdict = self._sections[section]
  294.             except KeyError:
  295.                 raise NoSectionError(section)
  296.  
  297.         sectdict[self.optionxform(option)] = value
  298.  
  299.     
  300.     def write(self, fp):
  301.         if self._defaults:
  302.             fp.write('[%s]\n' % DEFAULTSECT)
  303.             for key, value in self._defaults.items():
  304.                 fp.write('%s = %s\n' % (key, str(value).replace('\n', '\n\t')))
  305.             
  306.             fp.write('\n')
  307.         
  308.         for section in self._sections:
  309.             fp.write('[%s]\n' % section)
  310.             for key, value in self._sections[section].items():
  311.                 if key != '__name__':
  312.                     fp.write('%s = %s\n' % (key, str(value).replace('\n', '\n\t')))
  313.                     continue
  314.             
  315.             fp.write('\n')
  316.         
  317.  
  318.     
  319.     def remove_option(self, section, option):
  320.         if not section or section == DEFAULTSECT:
  321.             sectdict = self._defaults
  322.         else:
  323.             
  324.             try:
  325.                 sectdict = self._sections[section]
  326.             except KeyError:
  327.                 raise NoSectionError(section)
  328.  
  329.         option = self.optionxform(option)
  330.         existed = option in sectdict
  331.         if existed:
  332.             del sectdict[option]
  333.         
  334.         return existed
  335.  
  336.     
  337.     def remove_section(self, section):
  338.         existed = section in self._sections
  339.         if existed:
  340.             del self._sections[section]
  341.         
  342.         return existed
  343.  
  344.     SECTCRE = re.compile('\\[(?P<header>[^]]+)\\]')
  345.     OPTCRE = re.compile('(?P<option>[^:=\\s][^:=]*)\\s*(?P<vi>[:=])\\s*(?P<value>.*)$')
  346.     
  347.     def _read(self, fp, fpname):
  348.         cursect = None
  349.         optname = None
  350.         lineno = 0
  351.         e = None
  352.         while True:
  353.             line = fp.readline()
  354.             if not line:
  355.                 break
  356.             
  357.             lineno = lineno + 1
  358.             if line.strip() == '' or line[0] in '#;':
  359.                 continue
  360.             
  361.             if line.split(None, 1)[0].lower() == 'rem' and line[0] in 'rR':
  362.                 continue
  363.             
  364.             if line[0].isspace() and cursect is not None and optname:
  365.                 value = line.strip()
  366.                 if value:
  367.                     cursect[optname] = '%s\n%s' % (cursect[optname], value)
  368.                 
  369.             value
  370.             mo = self.SECTCRE.match(line)
  371.             if mo:
  372.                 sectname = mo.group('header')
  373.                 if sectname in self._sections:
  374.                     cursect = self._sections[sectname]
  375.                 elif sectname == DEFAULTSECT:
  376.                     cursect = self._defaults
  377.                 else:
  378.                     cursect = self._dict()
  379.                     cursect['__name__'] = sectname
  380.                     self._sections[sectname] = cursect
  381.                 optname = None
  382.                 continue
  383.             if cursect is None:
  384.                 raise MissingSectionHeaderError(fpname, lineno, line)
  385.             cursect is None
  386.             mo = self.OPTCRE.match(line)
  387.             if mo:
  388.                 (optname, vi, optval) = mo.group('option', 'vi', 'value')
  389.                 if vi in ('=', ':') and ';' in optval:
  390.                     pos = optval.find(';')
  391.                     if pos != -1 and optval[pos - 1].isspace():
  392.                         optval = optval[:pos]
  393.                     
  394.                 
  395.                 optval = optval.strip()
  396.                 if optval == '""':
  397.                     optval = ''
  398.                 
  399.                 optname = self.optionxform(optname.rstrip())
  400.                 cursect[optname] = optval
  401.                 continue
  402.             if not e:
  403.                 e = ParsingError(fpname)
  404.             
  405.             e.append(lineno, repr(line))
  406.         if e:
  407.             raise e
  408.         e
  409.  
  410.  
  411.  
  412. class ConfigParser(RawConfigParser):
  413.     
  414.     def get(self, section, option, raw = False, vars = None):
  415.         d = self._defaults.copy()
  416.         
  417.         try:
  418.             d.update(self._sections[section])
  419.         except KeyError:
  420.             if section != DEFAULTSECT:
  421.                 raise NoSectionError(section)
  422.             section != DEFAULTSECT
  423.  
  424.         if vars:
  425.             for key, value in vars.items():
  426.                 d[self.optionxform(key)] = value
  427.             
  428.         
  429.         option = self.optionxform(option)
  430.         
  431.         try:
  432.             value = d[option]
  433.         except KeyError:
  434.             raise NoOptionError(option, section)
  435.  
  436.         if raw:
  437.             return value
  438.         return self._interpolate(section, option, value, d)
  439.  
  440.     
  441.     def items(self, section, raw = False, vars = None):
  442.         d = self._defaults.copy()
  443.         
  444.         try:
  445.             d.update(self._sections[section])
  446.         except KeyError:
  447.             if section != DEFAULTSECT:
  448.                 raise NoSectionError(section)
  449.             section != DEFAULTSECT
  450.  
  451.         if vars:
  452.             for key, value in vars.items():
  453.                 d[self.optionxform(key)] = value
  454.             
  455.         
  456.         options = d.keys()
  457.         if '__name__' in options:
  458.             options.remove('__name__')
  459.         
  460.         if raw:
  461.             return [ (option, d[option]) for option in options ]
  462.         return [ (option, self._interpolate(section, option, d[option], d)) for option in options ]
  463.  
  464.     
  465.     def _interpolate(self, section, option, rawval, vars):
  466.         value = rawval
  467.         depth = MAX_INTERPOLATION_DEPTH
  468.         while depth:
  469.             depth -= 1
  470.             if '%(' in value:
  471.                 value = self._KEYCRE.sub(self._interpolation_replace, value)
  472.                 
  473.                 try:
  474.                     value = value % vars
  475.                 except KeyError:
  476.                     e = None
  477.                     raise InterpolationMissingOptionError(option, section, rawval, e.args[0])
  478.                 except:
  479.                     None<EXCEPTION MATCH>KeyError
  480.                 
  481.  
  482.             None<EXCEPTION MATCH>KeyError
  483.             break
  484.         if '%(' in value:
  485.             raise InterpolationDepthError(option, section, rawval)
  486.         '%(' in value
  487.         return value
  488.  
  489.     _KEYCRE = re.compile('%\\(([^)]*)\\)s|.')
  490.     
  491.     def _interpolation_replace(self, match):
  492.         s = match.group(1)
  493.         if s is None:
  494.             return match.group()
  495.         return '%%(%s)s' % self.optionxform(s)
  496.  
  497.  
  498.  
  499. class SafeConfigParser(ConfigParser):
  500.     
  501.     def _interpolate(self, section, option, rawval, vars):
  502.         L = []
  503.         self._interpolate_some(option, L, rawval, section, vars, 1)
  504.         return ''.join(L)
  505.  
  506.     _interpvar_re = re.compile('%\\(([^)]+)\\)s')
  507.     
  508.     def _interpolate_some(self, option, accum, rest, section, map, depth):
  509.         if depth > MAX_INTERPOLATION_DEPTH:
  510.             raise InterpolationDepthError(option, section, rest)
  511.         depth > MAX_INTERPOLATION_DEPTH
  512.         while rest:
  513.             p = rest.find('%')
  514.             if p < 0:
  515.                 accum.append(rest)
  516.                 return None
  517.             if p > 0:
  518.                 accum.append(rest[:p])
  519.                 rest = rest[p:]
  520.             
  521.             c = rest[1:2]
  522.             if c == '%':
  523.                 accum.append('%')
  524.                 rest = rest[2:]
  525.                 continue
  526.             if c == '(':
  527.                 m = self._interpvar_re.match(rest)
  528.                 if m is None:
  529.                     raise InterpolationSyntaxError(option, section, 'bad interpolation variable reference %r' % rest)
  530.                 m is None
  531.                 var = self.optionxform(m.group(1))
  532.                 rest = rest[m.end():]
  533.                 
  534.                 try:
  535.                     v = map[var]
  536.                 except KeyError:
  537.                     raise InterpolationMissingOptionError(option, section, rest, var)
  538.  
  539.                 if '%' in v:
  540.                     self._interpolate_some(option, accum, v, section, map, depth + 1)
  541.                 else:
  542.                     accum.append(v)
  543.             '%' in v
  544.             raise InterpolationSyntaxError(option, section, "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
  545.  
  546.     
  547.     def set(self, section, option, value):
  548.         if not isinstance(value, basestring):
  549.             raise TypeError('option values must be strings')
  550.         isinstance(value, basestring)
  551.         tmp_value = value.replace('%%', '')
  552.         tmp_value = self._interpvar_re.sub('', tmp_value)
  553.         percent_index = tmp_value.find('%')
  554.         if percent_index != -1:
  555.             raise ValueError('invalid interpolation syntax in %r at position %d' % (value, percent_index))
  556.         percent_index != -1
  557.         ConfigParser.set(self, section, option, value)
  558.  
  559.  
  560.