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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __author__ = 'Bill Bumgarner <bbum@friday.com>'
  5. __license__ = 'MIT'
  6. __version__ = '1.2'
  7. import re
  8. import string
  9. import sys
  10. import types
  11.  
  12. class Error(Exception):
  13.     pass
  14.  
  15.  
  16. class ArgumentError(Error):
  17.     pass
  18.  
  19.  
  20. class SpecificationError(Error):
  21.     pass
  22.  
  23.  
  24. class TerminationError(Error):
  25.     pass
  26.  
  27. specificationExpr = re.compile('(?P<required>.)(?P<type>.)(?P<multi>@?)')
  28. ArgRequired = 'Requires an Argument'
  29. ArgOptional = 'Argument Optional'
  30. StringArgType = 'String Argument Type'
  31. IntegerArgType = 'Integer Argument Type'
  32. RealArgType = 'Real Argument Type'
  33. BooleanArgType = 'Boolean Argument Type'
  34. GenericArgType = 'Generic Argument Type'
  35. ConversionFunctions = {
  36.     StringArgType: (lambda x: x),
  37.     IntegerArgType: string.atoi,
  38.     RealArgType: string.atof,
  39.     BooleanArgType: (lambda x: x),
  40.     GenericArgType: (lambda x: x) }
  41.  
  42. class DPyGetOpt:
  43.     
  44.     def __init__(self, spec = None, terminators = [
  45.         '--']):
  46.         self.allowAbbreviations = 1
  47.         self.freeValues = []
  48.         self.ignoreCase = 0
  49.         self.needsParse = 0
  50.         self.optionNames = { }
  51.         self.optionStartExpr = None
  52.         self.optionTuples = []
  53.         self.optionValues = { }
  54.         self.orderMixed = 0
  55.         self.posixCompliance = 0
  56.         self.spec = []
  57.         self.terminators = terminators
  58.         self.termValues = []
  59.         self.terminator = None
  60.         self.setPosixCompliance()
  61.         self.setIgnoreCase()
  62.         self.setAllowAbbreviations()
  63.         if spec:
  64.             self.parseConfiguration(spec)
  65.         
  66.  
  67.     
  68.     def setPosixCompliance(self, aFlag = 0):
  69.         self.posixCompliance = aFlag
  70.         self.needsParse = 1
  71.         if self.posixCompliance:
  72.             self.optionStartExpr = re.compile('(--|-)(?P<option>[A-Za-z0-9_-]+)(?P<arg>=.*)?')
  73.             self.orderMixed = 0
  74.         else:
  75.             self.optionStartExpr = re.compile('(--|-|\\+)(?P<option>[A-Za-z0-9_-]+)(?P<arg>=.*)?')
  76.             self.orderMixed = 1
  77.  
  78.     
  79.     def isPosixCompliant(self):
  80.         return self.posixCompliance
  81.  
  82.     
  83.     def setIgnoreCase(self, aFlag = 1):
  84.         self.needsParse = 1
  85.         self.ignoreCase = aFlag
  86.  
  87.     
  88.     def ignoreCase(self):
  89.         return self.ignoreCase
  90.  
  91.     
  92.     def setAllowAbbreviations(self, aFlag = 1):
  93.         self.allowAbbreviations = aFlag
  94.  
  95.     
  96.     def willAllowAbbreviations(self):
  97.         return self.allowAbbreviations
  98.  
  99.     
  100.     def addTerminator(self, newTerm):
  101.         self.terminators = self.terminators + [
  102.             newTerm]
  103.  
  104.     
  105.     def _addOption(self, oTuple):
  106.         (type, mode, default, multi) = (name,)
  107.         realName = oTuple
  108.         if self.optionNames.has_key(name):
  109.             if realName:
  110.                 raise SpecificationError("Alias '" + name + "' for '" + realName + "' already used for another option or alias.")
  111.             realName
  112.             raise SpecificationError("Option named '" + name + "' specified more than once. Specification: " + option)
  113.         self.optionNames.has_key(name)
  114.         self.optionNames[name] = self.tupleIndex
  115.         self.tupleIndex = self.tupleIndex + 1
  116.         self.optionTuples = self.optionTuples + [
  117.             oTuple]
  118.         if type == BooleanArgType:
  119.             alias = 'no' + name
  120.             specTuple = (type, mode, 0, multi)
  121.             oTuple = (alias, specTuple, name)
  122.             if self.optionNames.has_key(alias):
  123.                 if realName:
  124.                     raise SpecificationError("Negated alias '" + name + "' for '" + realName + "' already used for another option or alias.")
  125.                 realName
  126.                 raise SpecificationError("Negated option named '" + name + "' specified more than once. Specification: " + option)
  127.             self.optionNames.has_key(alias)
  128.             self.optionNames[alias] = self.tupleIndex
  129.             self.tupleIndex = self.tupleIndex + 1
  130.             self.optionTuples = self.optionTuples + [
  131.                 oTuple]
  132.         
  133.  
  134.     
  135.     def addOptionConfigurationTuple(self, oTuple):
  136.         (name, argSpec, realName) = oTuple
  137.         if self.ignoreCase:
  138.             name = string.lower(name)
  139.             if realName:
  140.                 realName = string.lower(realName)
  141.             else:
  142.                 realName = name
  143.             oTuple = (name, argSpec, realName)
  144.         
  145.         self._addOption(oTuple)
  146.  
  147.     
  148.     def addOptionConfigurationTuples(self, oTuple):
  149.         if type(oTuple) is ListType:
  150.             for t in oTuple:
  151.                 self.addOptionConfigurationTuple(t)
  152.             
  153.         else:
  154.             self.addOptionConfigurationTuple(oTuple)
  155.  
  156.     
  157.     def parseConfiguration(self, spec):
  158.         self.spec = spec
  159.         self.optionTuples = []
  160.         self.optionNames = { }
  161.         self.tupleIndex = 0
  162.         tupleIndex = 0
  163.         splitExpr = re.compile('(?P<names>\\w+[-A-Za-z0-9|]*)?(?P<spec>!|[=:][infs]@?)?')
  164.         for option in spec:
  165.             if self.ignoreCase:
  166.                 option = string.lower(option)
  167.             
  168.             match = splitExpr.match(option)
  169.             if match is None:
  170.                 raise SpecificationError('Invalid specification {' + option + '}')
  171.             match is None
  172.             names = match.group('names')
  173.             specification = match.group('spec')
  174.             nlist = string.split(names, '|')
  175.             name = nlist[0]
  176.             aliases = nlist[1:]
  177.             if not specification:
  178.                 argType = GenericArgType
  179.                 argMode = None
  180.                 argDefault = 1
  181.                 argMultiple = 0
  182.             elif specification == '!':
  183.                 argType = BooleanArgType
  184.                 argMode = None
  185.                 argDefault = 1
  186.                 argMultiple = 0
  187.             else:
  188.                 match = specificationExpr.match(specification)
  189.                 if match is None:
  190.                     raise SpecificationError("Invalid configuration for option '" + option + "'")
  191.                 match is None
  192.                 required = match.group('required')
  193.                 if required == '=':
  194.                     argMode = ArgRequired
  195.                 elif required == ':':
  196.                     argMode = ArgOptional
  197.                 else:
  198.                     raise SpecificationError("Unknown requirement configuration '" + required + "'")
  199.                 type = (required == '=').group('type')
  200.                 if type == 's':
  201.                     argType = StringArgType
  202.                     argDefault = ''
  203.                 elif type == 'i':
  204.                     argType = IntegerArgType
  205.                     argDefault = 1
  206.                 elif type == 'f' or type == 'n':
  207.                     argType = RealArgType
  208.                     argDefault = 1
  209.                 else:
  210.                     raise SpecificationError("Unknown type specifier '" + type + "'")
  211.                 if (type == 'n').group('multi') == '@':
  212.                     argMultiple = 1
  213.                 else:
  214.                     argMultiple = 0
  215.             specTuple = (argType, argMode, argDefault, argMultiple)
  216.             oTuple = (name, specTuple, name)
  217.             self._addOption(oTuple)
  218.             for alias in aliases:
  219.                 if self.ignoreCase:
  220.                     alias = string.lower(alias)
  221.                 
  222.                 oTuple = (alias, specTuple, name)
  223.                 self._addOption(oTuple)
  224.             
  225.         
  226.         self.needsParse = 0
  227.  
  228.     
  229.     def _getArgTuple(self, argName):
  230.         
  231.         try:
  232.             tupleIndex = self.optionNames[argName]
  233.             return [
  234.                 self.optionTuples[tupleIndex]]
  235.         except KeyError:
  236.             if not self.allowAbbreviations:
  237.                 return None
  238.         except:
  239.             self.allowAbbreviations
  240.  
  241.         argExpr = re.compile('^' + argName)
  242.         tuples = filter((lambda x, argExpr = argExpr: argExpr.search(x[0]) is not None), self.optionTuples)
  243.         if not len(tuples):
  244.             return None
  245.         return tuples
  246.  
  247.     
  248.     def _isTerminator(self, optionName):
  249.         if optionName in self.terminators:
  250.             self.terminator = optionName
  251.         elif not self.allowAbbreviations:
  252.             return None
  253.         terms = filter((lambda x, on = optionName: string.find(x, on) == 0), self.terminators)
  254.         if not len(terms):
  255.             return None
  256.         if len(terms) > 1:
  257.             raise TerminationError("Ambiguous terminator '" + optionName + "' matches " + repr(terms))
  258.         len(terms) > 1
  259.         self.terminator = terms[0]
  260.         return self.terminator
  261.  
  262.     
  263.     def processArguments(self, args = None):
  264.         if hasattr(sys, 'argv') and args == sys.argv:
  265.             args = sys.argv[1:]
  266.         
  267.         max = len(args)
  268.         self.freeValues = []
  269.         self.optionValues = { }
  270.         index = 0
  271.         self.terminator = None
  272.         self.termValues = []
  273.         while index < max:
  274.             arg = args[index]
  275.             index = index + 1
  276.             if self._isTerminator(arg):
  277.                 self.freeValues = self.freeValues + args[index:]
  278.                 self.termValues = args[index:]
  279.                 return None
  280.             match = self.optionStartExpr.match(arg)
  281.             optName = match.group('option')
  282.             nextArg = match.group('arg')
  283.             if nextArg:
  284.                 nextArg = nextArg[1:]
  285.                 index = index - 1
  286.             else:
  287.                 
  288.                 try:
  289.                     nextArg = args[index]
  290.                 except:
  291.                     nextArg = None
  292.  
  293.             if self.ignoreCase:
  294.                 optName = string.lower(optName)
  295.             
  296.             tuples = self._getArgTuple(optName)
  297.             if tuples == None:
  298.                 raise ArgumentError("Illegal option '" + arg + "'")
  299.             tuples == None
  300.             if len(tuples) > 1:
  301.                 raise ArgumentError("Ambiguous option '" + arg + "';  matches " + repr(map((lambda x: x[0]), tuples)))
  302.             len(tuples) > 1
  303.             config = tuples[0]
  304.             (fullName, spec, realName) = config
  305.             (optType, optMode, optDefault, optMultiple) = spec
  306.             if optMode == ArgRequired:
  307.                 if not nextArg or self._isTerminator(nextArg):
  308.                     raise ArgumentError("Option '" + arg + "' requires an argument of type " + optType)
  309.                 self._isTerminator(nextArg)
  310.             
  311.             if not (optMode == None) and nextArg and not self._isTerminator(nextArg):
  312.                 
  313.                 try:
  314.                     func = ConversionFunctions[optType]
  315.                     
  316.                     try:
  317.                         optionValue = func(nextArg)
  318.                         index = index + 1
  319.                     except:
  320.                         if optMode == ArgRequired:
  321.                             raise ArgumentError("Invalid argument to option '" + arg + "';  should be '" + optType + "'")
  322.                         optMode == ArgRequired
  323.                         optionValue = optDefault
  324.  
  325.                 except ArgumentError:
  326.                     raise 
  327.                 except:
  328.                     None<EXCEPTION MATCH>ArgumentError
  329.                     raise ArgumentError('(' + arg + ") Conversion function for '" + optType + "' not found.")
  330.                 
  331.  
  332.             None<EXCEPTION MATCH>ArgumentError
  333.             optionValue = optDefault
  334.             if optMultiple:
  335.                 
  336.                 try:
  337.                     self.optionValues[realName] = self.optionValues[realName] + [
  338.                         optionValue]
  339.                 self.optionValues[realName] = [
  340.                     optionValue]
  341.  
  342.                 continue
  343.             if self.isPosixCompliant and self.optionValues.has_key(realName):
  344.                 raise ArgumentError("Argument '" + arg + "' occurs multiple times.")
  345.             self.optionValues.has_key(realName)
  346.             self.optionValues[realName] = optionValue
  347.  
  348.     
  349.     def valueForOption(self, optionName, defaultValue = None):
  350.         
  351.         try:
  352.             optionValue = self.optionValues[optionName]
  353.         except:
  354.             optionValue = defaultValue
  355.  
  356.         return optionValue
  357.  
  358.  
  359. test_error = 'Test Run Amok!'
  360.  
  361. def _test():
  362.     
  363.     try:
  364.         DPyGetOpt([
  365.             'foo',
  366.             'bar=s',
  367.             'foo'])
  368.     except Error:
  369.         exc = None
  370.         print "EXCEPTION (should be 'foo' already used..): %s" % exc
  371.  
  372.     
  373.     try:
  374.         DPyGetOpt([
  375.             'foo|bar|apple=s@',
  376.             'baz|apple!'])
  377.     except Error:
  378.         exc = None
  379.         print 'EXCEPTION (should be duplicate alias/name error): %s' % exc
  380.  
  381.     x = DPyGetOpt([
  382.         'apple|atlas=i@',
  383.         'application|executable=f@'])
  384.     
  385.     try:
  386.         x.processArguments([
  387.             '-app',
  388.             '29.3'])
  389.     except Error:
  390.         exc = None
  391.         print 'EXCEPTION (should be ambiguous argument): %s' % exc
  392.  
  393.     x = DPyGetOpt([
  394.         'foo'], [
  395.         'antigravity',
  396.         'antithesis'])
  397.     
  398.     try:
  399.         x.processArguments([
  400.             '-foo',
  401.             'anti'])
  402.     except Error:
  403.         exc = None
  404.         print 'EXCEPTION (should be ambiguous terminator): %s' % exc
  405.  
  406.     profile = [
  407.         'plain-option',
  408.         'boolean-option!',
  409.         'list-of-integers=i@',
  410.         'list-real-option|list-real-alias|list-real-pseudonym=f@',
  411.         'optional-string-option:s',
  412.         'abbreviated-string-list=s@']
  413.     terminators = [
  414.         'terminator']
  415.     args = [
  416.         '-plain-option',
  417.         '+noboolean-option',
  418.         '--list-of-integers',
  419.         '1',
  420.         '+list-of-integers',
  421.         '2',
  422.         '-list-of-integers',
  423.         '3',
  424.         'freeargone',
  425.         '-list-real-option',
  426.         '1.1',
  427.         '+list-real-alias',
  428.         '1.2',
  429.         '--list-real-pseudonym',
  430.         '1.3',
  431.         'freeargtwo',
  432.         '-abbreviated-string-list',
  433.         'String1',
  434.         '--abbreviated-s',
  435.         'String2',
  436.         '-abbrev',
  437.         'String3',
  438.         '-a',
  439.         'String4',
  440.         '-optional-string-option',
  441.         'term',
  442.         'next option should look like an invalid arg',
  443.         '-a']
  444.     print 'Using profile: ' + repr(profile)
  445.     print 'With terminator: ' + repr(terminators)
  446.     print 'Processing arguments: ' + repr(args)
  447.     go = DPyGetOpt(profile, terminators)
  448.     go.processArguments(args)
  449.     print 'Options (and values): ' + repr(go.optionValues)
  450.     print 'free args: ' + repr(go.freeValues)
  451.     print 'term args: ' + repr(go.termValues)
  452.  
  453.