home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / gtk-2.0 / glib / option.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2009-10-12  |  12.3 KB  |  334 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''GOption command line parser
  5.  
  6. Extends optparse to use the GOptionGroup, GOptionEntry and GOptionContext
  7. objects. So it is possible to use the gtk, gnome_program and gstreamer command
  8. line groups and contexts.
  9.  
  10. Use this interface instead of the raw wrappers of GOptionContext and
  11. GOptionGroup in glib.
  12. '''
  13. import sys
  14. import optparse
  15. from optparse import OptParseError, OptionError, OptionValueError, BadOptionError, OptionConflictError
  16. import glib
  17. _glib = sys.modules['glib._glib']
  18. __all__ = [
  19.     'OptParseError',
  20.     'OptionError',
  21.     'OptionValueError',
  22.     'BadOptionError',
  23.     'OptionConflictErrorOption',
  24.     'OptionGroup',
  25.     'OptionParser',
  26.     'make_option']
  27.  
  28. class Option(optparse.Option):
  29.     """Represents a command line option
  30.  
  31.     To use the extended possibilities of the GOption API Option
  32.     (and make_option) are extended with new types and attributes.
  33.  
  34.     Types:
  35.         filename   The supplied arguments are read as filename, GOption
  36.                    parses this type in with the GLib filename encoding.
  37.  
  38.     Attributes:
  39.         optional_arg  This does not need a arguement, but it can be supplied.
  40.         hidden        The help list does not show this option
  41.         in_main       This option apears in the main group, this should only
  42.                       be used for backwards compatibility.
  43.  
  44.     Use Option.REMAINING as option name to get all positional arguments.
  45.  
  46.     NOTE: Every argument to an option is passed as utf-8 coded string, the only
  47.           exception are options which use the 'filename' type, its arguments
  48.           are passed as strings in the GLib filename encoding.
  49.  
  50.     For further help, see optparse.Option.
  51.     """
  52.     TYPES = optparse.Option.TYPES + ('filename',)
  53.     ATTRS = optparse.Option.ATTRS + [
  54.         'hidden',
  55.         'in_main',
  56.         'optional_arg']
  57.     REMAINING = '--' + _glib.OPTION_REMAINING
  58.     
  59.     def __init__(self, *args, **kwargs):
  60.         optparse.Option.__init__(self, *args, **kwargs)
  61.         if not self._long_opts:
  62.             raise ValueError('%s at least one long option name.')
  63.         self._long_opts
  64.         if len(self._long_opts) < len(self._short_opts):
  65.             raise ValueError('%s at least more long option names than short option names.')
  66.         len(self._long_opts) < len(self._short_opts)
  67.         if not self.help:
  68.             raise ValueError('%s needs a help message.', self._long_opts[0])
  69.         self.help
  70.  
  71.     
  72.     def _set_opt_string(self, opts):
  73.         if self.REMAINING in opts:
  74.             self._long_opts.append(self.REMAINING)
  75.         
  76.         optparse.Option._set_opt_string(self, opts)
  77.         if len(self._short_opts) > len(self._long_opts):
  78.             raise OptionError('goption.Option needs more long option names than short option names')
  79.         len(self._short_opts) > len(self._long_opts)
  80.  
  81.     
  82.     def _to_goptionentries(self):
  83.         flags = 0
  84.         if self.hidden:
  85.             self.flags |= _glib.OPTION_FLAG_HIDDEN
  86.         
  87.         if self.in_main:
  88.             self.flags |= _glib.OPTION_FLAG_IN_MAIN
  89.         
  90.         if self.takes_value():
  91.             if self.optional_arg:
  92.                 flags |= _glib.OPTION_FLAG_OPTIONAL_ARG
  93.             
  94.         else:
  95.             flags |= _glib.OPTION_FLAG_NO_ARG
  96.         if self.type == 'filename':
  97.             flags |= _glib.OPTION_FLAG_FILENAME
  98.         
  99.         for long_name, short_name in zip(self._long_opts, self._short_opts):
  100.             yield (long_name[2:], short_name[1], flags, self.help, self.metavar)
  101.         
  102.         for long_name in self._long_opts[len(self._short_opts):]:
  103.             yield (long_name[2:], '\x00', flags, self.help, self.metavar)
  104.         
  105.  
  106.  
  107.  
  108. class OptionGroup(optparse.OptionGroup):
  109.     '''A group of command line options.
  110.  
  111.     Arguements:
  112.        name:             The groups name, used to create the
  113.                          --help-{name} option
  114.        description:      Shown as title of the groups help view
  115.        help_description: Shown as help to the --help-{name} option
  116.        option_list:      The options used in this group, must be option.Option()
  117.        defaults:         A dicitionary of default values
  118.        translation_domain: Sets the translation domain for gettext().
  119.  
  120.     NOTE: This OptionGroup does not exactly map the optparse.OptionGroup
  121.           interface. There is no parser object to supply, but it is possible
  122.           to set default values and option_lists. Also the default values and
  123.           values are not shared with the OptionParser.
  124.  
  125.     To pass a OptionGroup into a function which expects a GOptionGroup (e.g.
  126.     gnome_program_init() ). OptionGroup.get_option_group() can be used.
  127.  
  128.     For further help, see optparse.OptionGroup.
  129.     '''
  130.     
  131.     def __init__(self, name, description, help_description = '', option_list = None, defaults = None, translation_domain = None):
  132.         optparse.OptionContainer.__init__(self, Option, 'error', description)
  133.         self.name = name
  134.         self.parser = None
  135.         self.help_description = help_description
  136.         if defaults:
  137.             self.defaults = defaults
  138.         
  139.         self.values = None
  140.         self.translation_domain = translation_domain
  141.         if option_list:
  142.             for option in option_list:
  143.                 self.add_option(option)
  144.             
  145.         
  146.  
  147.     
  148.     def _create_option_list(self):
  149.         self.option_list = []
  150.         self._create_option_mappings()
  151.  
  152.     
  153.     def _to_goptiongroup(self, parser):
  154.         
  155.         def callback(option_name, option_value, group):
  156.             if option_name.startswith('--'):
  157.                 opt = self._long_opt[option_name]
  158.             else:
  159.                 opt = self._short_opt[option_name]
  160.             
  161.             try:
  162.                 opt.process(option_name, option_value, self.values, parser)
  163.             except OptionValueError:
  164.                 error = sys.exc_info()[1]
  165.                 gerror = _glib.GError(str(error))
  166.                 gerror.domain = _glib.OPTION_ERROR
  167.                 gerror.code = _glib.OPTION_ERROR_BAD_VALUE
  168.                 gerror.message = str(error)
  169.                 raise gerror
  170.  
  171.  
  172.         group = _glib.OptionGroup(self.name, self.description, self.help_description, callback)
  173.         if self.translation_domain:
  174.             group.set_translation_domain(self.translation_domain)
  175.         
  176.         entries = []
  177.         for option in self.option_list:
  178.             entries.extend(option._to_goptionentries())
  179.         
  180.         group.add_entries(entries)
  181.         return group
  182.  
  183.     
  184.     def get_option_group(self, parser = None):
  185.         ''' Returns the corresponding GOptionGroup object.
  186.  
  187.         Can be used as parameter for gnome_program_init(), gtk_init().
  188.         '''
  189.         self.set_values_to_defaults()
  190.         return self._to_goptiongroup(parser)
  191.  
  192.     
  193.     def set_values_to_defaults(self):
  194.         for option in self.option_list:
  195.             default = self.defaults.get(option.dest)
  196.             if isinstance(default, basestring):
  197.                 opt_str = option.get_opt_string()
  198.                 self.defaults[option.dest] = option.check_value(opt_str, default)
  199.                 continue
  200.         
  201.         self.values = optparse.Values(self.defaults)
  202.  
  203.  
  204.  
  205. class OptionParser(optparse.OptionParser):
  206.     '''Command line parser with GOption support.
  207.  
  208.     NOTE: The OptionParser interface is not the exactly the same as the
  209.           optparse.OptionParser interface. Especially the usage parameter
  210.           is only used to show the metavar of the arguements.
  211.  
  212.     Attribues:
  213.         help_enabled:           The --help, --help-all and --help-{group}
  214.                                 options are enabled (default).
  215.         ignore_unknown_options: Do not throw a exception when a option is not
  216.                                 knwon, the option will be in the result list.
  217.  
  218.     OptionParser.add_option_group() does not only accept OptionGroup instances
  219.     but also glib.OptionGroup, which is returned by gtk_get_option_group().
  220.  
  221.     Only glib.option.OptionGroup and glib.option.Option instances should
  222.     be passed as groups and options.
  223.  
  224.     For further help, see optparse.OptionParser.
  225.     '''
  226.     
  227.     def __init__(self, *args, **kwargs):
  228.         if 'option_class' not in kwargs:
  229.             kwargs['option_class'] = Option
  230.         
  231.         self.help_enabled = kwargs.pop('help_enabled', True)
  232.         self.ignore_unknown_options = kwargs.pop('ignore_unknown_options', False)
  233.         optparse.OptionParser.__init__(self, add_help_option = False, *args, **kwargs)
  234.  
  235.     
  236.     def set_usage(self, usage):
  237.         if usage is None:
  238.             self.usage = ''
  239.         elif usage.startswith('%prog'):
  240.             self.usage = usage[len('%prog'):]
  241.         else:
  242.             self.usage = usage
  243.  
  244.     
  245.     def _to_goptioncontext(self, values):
  246.         if self.description:
  247.             parameter_string = self.usage + ' - ' + self.description
  248.         else:
  249.             parameter_string = self.usage
  250.         context = _glib.OptionContext(parameter_string)
  251.         context.set_help_enabled(self.help_enabled)
  252.         context.set_ignore_unknown_options(self.ignore_unknown_options)
  253.         for option_group in self.option_groups:
  254.             if isinstance(option_group, _glib.OptionGroup):
  255.                 g_group = option_group
  256.             else:
  257.                 g_group = option_group.get_option_group(self)
  258.             context.add_group(g_group)
  259.         
  260.         
  261.         def callback(option_name, option_value, group):
  262.             if option_name.startswith('--'):
  263.                 opt = self._long_opt[option_name]
  264.             else:
  265.                 opt = self._short_opt[option_name]
  266.             opt.process(option_name, option_value, values, self)
  267.  
  268.         main_group = _glib.OptionGroup(None, None, None, callback)
  269.         main_entries = []
  270.         for option in self.option_list:
  271.             main_entries.extend(option._to_goptionentries())
  272.         
  273.         main_group.add_entries(main_entries)
  274.         context.set_main_group(main_group)
  275.         return context
  276.  
  277.     
  278.     def add_option_group(self, *args, **kwargs):
  279.         if isinstance(args[0], basestring):
  280.             optparse.OptionParser.add_option_group(self, OptionGroup(self, *args, **kwargs))
  281.             return None
  282.         optparse.OptionParser.add_option_group(self, *args, **kwargs)
  283.  
  284.     
  285.     def _get_all_options(self):
  286.         options = self.option_list[:]
  287.         for group in self.option_groups:
  288.             if isinstance(group, optparse.OptionGroup):
  289.                 options.extend(group.option_list)
  290.                 continue
  291.         
  292.         return options
  293.  
  294.     
  295.     def _process_args(self, largs, rargs, values):
  296.         context = self._to_goptioncontext(values)
  297.         rargs[:] = context.parse([
  298.             sys.argv[0]] + rargs)[1:]
  299.  
  300.     
  301.     def parse_args(self, args = None, values = None):
  302.         if not args:
  303.             pass
  304.         old_args = []
  305.         
  306.         try:
  307.             (options, args) = optparse.OptionParser.parse_args(self, args, values)
  308.         except _glib.GError:
  309.             error = sys.exc_info()[1]
  310.             if error.domain != _glib.OPTION_ERROR:
  311.                 raise 
  312.             error.domain != _glib.OPTION_ERROR
  313.             if error.code == _glib.OPTION_ERROR_BAD_VALUE:
  314.                 raise OptionValueError(error.message)
  315.             error.code == _glib.OPTION_ERROR_BAD_VALUE
  316.             if error.code == _glib.OPTION_ERROR_UNKNOWN_OPTION:
  317.                 raise BadOptionError(error.message)
  318.             error.code == _glib.OPTION_ERROR_UNKNOWN_OPTION
  319.             if error.code == _glib.OPTION_ERROR_FAILED:
  320.                 raise OptParseError(error.message)
  321.             error.code == _glib.OPTION_ERROR_FAILED
  322.             raise 
  323.  
  324.         for group in self.option_groups:
  325.             for key, value in group.values.__dict__.items():
  326.                 options.ensure_value(key, value)
  327.             
  328.         
  329.         args = args[2:-len(old_args)]
  330.         return (options, args)
  331.  
  332.  
  333. make_option = Option
  334.