def take_action(self, action, dest, opt, value, values, parser):
        "Extended to handle generation a config file"
        if action == "generate_config":
            parser.generate_and_print_config_file()
            parser.exit()

        Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 2
0
    def _set_attrs(self, attrs):
        """overwrite _set_attrs to allow store_or callbacks"""
        Option._set_attrs(self, attrs)
        if self.action in self.EXTOPTION_STORE_OR:
            setattr(self, 'store_or', self.action)

            def store_or(option, opt_str, value, parser, *args, **kwargs):
                """Callback for supporting options with optional values."""
                # see http://stackoverflow.com/questions/1229146/parsing-empty-options-in-python
                # ugly code, optparse is crap
                if parser.rargs and not parser.rargs[0].startswith('-'):
                    val = parser.rargs[0]
                    parser.rargs.pop(0)
                else:
                    val = kwargs.get('orig_default', None)

                setattr(parser.values, option.dest, val)

            # without the following, --x=y doesn't work; only --x y
            self.nargs = 0  # allow 0 args, will also use 0 args
            if self.type is None:
                # set to not None, for takes_value to return True
                self.type = 'string'

            self.callback = store_or
            self.callback_kwargs = {'orig_default': copy.deepcopy(self.default),
                                    }
            self.action = 'callback'  # act as callback
            if self.store_or == 'store_or_None':
                self.default = None
            else:
                raise ValueError("_set_attrs: unknown store_or %s" % self.store_or)
Ejemplo n.º 3
0
    def take_action(self, action, dest, opt, value, values, parser):
        """
        This function is a wrapper to take certain options passed on command
        prompt and wrap them into an Array.

        @param action: The type of action that will be taken. For example:
        "store_true", "store_false", "extend".
        @type action: String
        @param dest: The name of the variable that will be used to store the
        option.
        @type dest: String/Boolean/Array
        @param opt: The option string that triggered the action.
        @type opt: String
        @param value: The value of opt(option) if it takes a
        value, if not then None.
        @type value:
        @param values: All the opt(options) in a dictionary.
        @type values: Dictionary
        @param parser: The option parser that was orginally called.
        @type parser: OptionParser
        """
        if (action == "extend") :
            value_list = []
            try:
                for v in value.split(","):
                    # Need to add code for dealing with paths if there is option for paths.
                    new_value = value.strip().rstrip()
                    if (len(new_value) > 0):
                        value_list.append(new_value)
            except:
                pass
            else:
                values.ensure_value(dest, []).extend(value_list)
        else:
            Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 4
0
 def take_action(self, action, dest, opt, value, values, parser):
     if action == "map":
         values.ensure_value(dest, parser.map[opt.lstrip('-')])
     elif action == "map_extend":
         values.ensure_value(dest, []).extend(parser.map[opt.lstrip('-')])
     else:
         Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 5
0
 def take_action(self, action, dest, opt, value, values, parser):
     if action == "extend":
         lvalue = value.split(",")
         values.ensure_value(dest, []).extend(lvalue)
     else:
         Option.take_action(
             self, action, dest, opt, value, values, parser)
Ejemplo n.º 6
0
 def take_action(self, action, dest, opt, value, values, parser):
     if action == 'extend':
         split_value = value.split(',')
         ensure_value(qconfig, dest, []).extend(split_value)
     else:
         Option.take_action(
             self, action, dest, opt, value, qconfig, parser)
Ejemplo n.º 7
0
def parse_reqs(reqs_file):
    ''' parse the requirements '''
    options = Option("--workaround")
    options.skip_requirements_regex = None
    options.isolated_mode = True
    install_reqs = parse_requirements(reqs_file, options=options, session=PipSession())
    return [str(ir.req) for ir in install_reqs]
  def __init__(self, *opt_str, **attrs):
    """
      *opt_str: Same meaning as in twitter.common.options.Option, at least one is required.
      **attrs: See twitter.common.options.Option, with the following caveats:

      Exactly one of the following must be provided:

      clusters: A static Clusters object from which to pick clusters.
      cluster_provider: A function that takes a cluster name and returns a Cluster object.
    """
    self.clusters = attrs.pop('clusters', None)
    self.cluster_provider = attrs.pop('cluster_provider', None)
    if not (self.clusters is not None) ^ (self.cluster_provider is not None):
      raise ValueError('Must specify exactly one of clusters and cluster_provider.')

    default_attrs = dict(
      default=None,
      action='store',
      type='mesos_cluster',
      help='Mesos cluster to use (Default: %%default)'
    )

    combined_attrs = default_attrs
    combined_attrs.update(attrs)  # Defensive copy
    Option.__init__(self, *opt_str, **combined_attrs)  # old-style superclass
Ejemplo n.º 9
0
 def __init__( self, *args, **kwargs ):
     try:
         ltype = kwargs.pop('ltype')
     except:
         ltype = None
     Option.__init__( self, *args, **kwargs )
     self.ltype = ltype
Ejemplo n.º 10
0
 def take_action(self,action,dest,opt,value,values,parser):
     log.debug('take_action: %s',action)
     if action in custom_actions:
         custom_actions.get(action)(dest,value,values)
     else:
         Option.take_action(self,action,dest,opt,value,values,parser)
     log.debug('values: %s',values)
Ejemplo n.º 11
0
	def take_action(self, action, dest, opt, value, values, parser):

		if action == "pubsub":

			# read the subscriber and publisher arguments
			value += " "
			for arg in parser.rargs:
				if arg[:2] == "--" and len(arg) > 2: break
				if arg[:1] == "-" and len(arg) > 1: break
				value += arg + " "
			subpubArray = [ x.strip() for x in value.split(",") if x.strip() ] 

			# verify that argument meets requirements
			if len(subpubArray) == 2:
				values.ensure_value(dest, []).append({"name": subpubArray[0], "type": subpubArray[1]})
			else:
				if opt == '-s': exitWithError(ERROR_OPT.SUBSCRIBER_MISSING, len(subpubArray))
				if opt == '-p': exitWithError(ERROR_OPT.PUBLISHER_MISING, len(subpubArray))

		elif action == "strspaces":

			# read the subscriber and publisher arguments
			for arg in parser.rargs:
				if arg[:2] == "--" and len( arg ) > 2: break
				if arg[:1] == "-" and len( arg ) > 1: break
				value += " " + arg

			setattr(values, dest, value )

		else:
			Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 12
0
 def _check_dest(self):
     try:
         Option._check_dest(self)
     except IndexError:
         if self.subopt:
             self.dest = "__%s__%s" % (self.baseopt, self.subopt)
             self.dest = self.dest.replace("-", "")
         else:
             raise
Ejemplo n.º 13
0
 def take_action(self, action, dest, opt, val, vals, parser):
     if action == 'setitem':
         key = opt.strip('-')
         vals.ensure_value(dest, {})[key] = val
     elif action == 'setitem2':
         key, val = val
         vals.ensure_value(dest, {})[key] = val
     else:
         Opt.take_action(self, action, dest, opt, val, vals, parser)
Ejemplo n.º 14
0
    def __init__(self, opt, *args, **kwargs):
        if 'dest' not in kwargs:
            # Override default dest, which would strip first two characters:
            kwargs['dest'] = opt.replace('-', '_')

        self.group = kwargs['group']
        del kwargs['group']

        Option.__init__(self, opt, *args, **kwargs)
Ejemplo n.º 15
0
    def __init__(self, *args, **kwds):
        try:
            self.config_key = kwds["config_key"]
            del kwds["config_key"]
        except KeyError:
            self.config_key = None

        Option.__init__(self, *args, **kwds)
        self._seen = False
Ejemplo n.º 16
0
 def take_action(self, action, dest, opt, value, values, parser):
     if action == "extend":
         lvalue = value.split(",")
         for token in lvalue:
             token = token.strip()
             if token:
                 values.ensure_value(dest, []).append(token)
     else:
         Option.take_action(
             self, action, dest, opt, value, values, parser)
Ejemplo n.º 17
0
 def addOption(self, *args, **kwargs):
     mandatory = kwargs.pop('mandatory', False)
     if 'help' in kwargs and 'default' in kwargs and '{default}' in kwargs['help']:
         kwargs['help'] = kwargs['help'].format(default=kwargs['default'])
     option = Option(*args, **kwargs)
     if option.metavar is None:
         option.metavar = '<{0}>'.format(option.type) if kwargs.get('default') is None else repr(option.default)
     if mandatory:
         self._mandatoryKeys.append(option.dest)
     self._parser.add_option(option)
Ejemplo n.º 18
0
 def take_action(self, action, dest, opt, value, values, parser):
     """ Performs list extension on plugins """
     if action == "extend":
         try:
             lvalue = value.split(",")
         except:
             pass
         else:
             values.ensure_value(dest, deque()).extend(lvalue)
     else:
         Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 19
0
	def take_action(self,action,dest,opt,value,values,parser):
		if action=="dic":
			vals=value.split(",")
			d={}
			for val in vals:
				p=val.split("]")
				k=p[0][1:]
				v=p[1]
				d[k]=v
			setattr(values,dest,d)
		else: Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 20
0
    def take_action(self, action, dest, opt, value, values, parser):
        if action == "extend":
            values.ensure_value(dest, []).append(value)
            for a in parser.rargs[:]:
                if a.startswith("-"):
                    break
                else:
                    values.ensure_value(dest, []).append(a)
                    parser.rargs.remove(a)

        else:
            Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 21
0
    def __init__(self, *opts, **attrs):

       self.subopt_map = {}

       if "subopt" in attrs:
           self._short_opts = []
           self._long_opts = []
           self._set_opt_strings(opts)
           self.baseopt = self._short_opts[0] or self._long_opts[0]
           opts = ()

       Option.__init__(self, *opts, **attrs)
Ejemplo n.º 22
0
    def take_action(self, action, dest, opt, value, values, parser):
        if action == "store_list":
            value = value.strip()
            lvalue = value.split(",")
            size = len(lvalue)
            if size > 0 and lvalue[size - 1] == "":
              lvalue.pop()

            values.ensure_value(dest, []).extend(lvalue)
        else:
            Option.take_action(
                self, action, dest, opt, value, values, parser)
Ejemplo n.º 23
0
 def take_action(self, action, dest, opt, value, values, parser):
     if action == "extend":
         values.ensure_value(dest, []).append(value)
     else:
         Option.take_action(
             self,
             action,
             dest,
             opt,
             value,
             values,
             parser)
Ejemplo n.º 24
0
    def __init__(self, *args, **kwargs):
        self.group_parser = kwargs['group_parser']
        del kwargs['group_parser']

        self.title = kwargs['title']
        del kwargs['title']

        if 'metavar' not in kwargs:
            kwargs['metavar'] = 'opt,opt,...'

        Option.__init__(self, *args, **kwargs)

        self._check_dest()
Ejemplo n.º 25
0
 def take_action(self, action, dest, opt, value, values, parser):
     if (action == "extend") :
         valueList = []
         try:
             for v in value.split(","):
                 newValue = v.strip().rstrip()
                 if (len(newValue) > 0):
                     valueList.append(newValue)
         except:
             pass
         else:
             values.ensure_value(dest, []).extend(valueList)
     else:
         Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 26
0
def parse_reqs(reqs_file):
    """ parse the requirements """
    options = Option("--workaround")
    options.skip_requirements_regex = None
    # Hack for old pip versions: Versions greater than 1.x
    # have a required parameter "sessions" in parse_requierements
    if pip.__version__.startswith("1."):
        install_reqs = parse_requirements(reqs_file, options=options)
    else:
        from pip.download import PipSession  # pylint:disable=E0611

        options.isolated_mode = False
        install_reqs = parse_requirements(reqs_file, options=options, session=PipSession)  # pylint:disable=E1123
    return [str(ir.req) for ir in install_reqs]
Ejemplo n.º 27
0
 def take_action(self, action, dest, opt, value, values, parser):
     ui = 'ui'
     if action == 'runtest':
         action = 'import'
         value = 'test'
         dest = 'ui'
         ui = ''
     if action == 'import':
         environ = {}
         exec("from shop import %s%s as module" % (value,ui), environ)
         setattr(values, dest, environ['module'])
     elif action == 'dir':
         setattr(values, dest, os.path.abspath(value))
     else:
         Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 28
0
 def take_action(self, action, dest, opt, value, values, parser):
     if (action == "extend") :
         valueList = []
         try:
             for v in value.split(","):
                 # Need to add code for dealing with paths if there is option for paths.
                 newValue = value.strip().rstrip()
                 if (len(newValue) > 0):
                     valueList.append(newValue)
         except:
             pass
         else:
             values.ensure_value(dest, []).extend(valueList)
     else:
         Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 29
0
 def take_action(self, action, dest, opt, value, values, parser):
     """Executes `action`"""
     if action == 'license':
         parser.print_license()
         parser.exit()
     elif action == 'copyright':
         parser.print_copyright()
         parser.exit()
     elif action == 'authors':
         parser.print_authors()
         parser.exit()
     elif action == 'print_fields':
         parser.print_fields()
         parser.exit()
     elif action == 'command':
         if hasattr(parser.values, 'command'):
             # raise error if two exlusive commands appeared
             msg = _('Please specify only one command option')
             raise OptionValueError(msg)
         values.command = opt.lstrip('-').replace('-', '_')
         values.command_values = value
         values.args = self.args
     else:
         return Option.take_action(self, action, dest, opt, value,
                                   values, parser)
     return True
Ejemplo n.º 30
0
    def take_action(self, action, dest, opt, value, values, parser):
        """Extended take_action"""
        orig_action = action  # keep copy

        if action == 'shorthelp':
            parser.print_shorthelp()
            parser.exit()
        elif action in ('store_true', 'store_false',) + self.EXTOPTION_LOG:
            if action in self.EXTOPTION_LOG:
                action = 'store_true'

            if opt.startswith("--%s-" % self.ENABLE):
                # keep action
                pass
            elif opt.startswith("--%s-" % self.DISABLE):
                # reverse action
                if action in ('store_true',) + self.EXTOPTION_LOG:
                    action = 'store_false'
                elif action in ('store_false',):
                    action = 'store_true'

            if orig_action in('store_debuglog', 'store_infolog', 'store_warninglog') and action == 'store_true':
                setLogLevel(orig_action.split('_')[1][:-3].upper())

            Option.take_action(self, action, dest, opt, value, values, parser)
        elif action in self.EXTOPTION_EXTRA_OPTIONS:
            if action == "extend":
                # comma separated list convert in list
                lvalue = value.split(self.EXTEND_SEPARATOR)
                values.ensure_value(dest, []).extend(lvalue)
            elif action == "date":
                lvalue = date_parser(value)
                setattr(values, dest, lvalue)
            elif action == "datetime":
                lvalue = datetime_parser(value)
                setattr(values, dest, lvalue)
            else:
                raise(Exception("Unknown extended option action %s (known: %s)" %
                                (action, self.EXTOPTION_EXTRA_OPTIONS)))
        else:
            Option.take_action(self, action, dest, opt, value, values, parser)

        # set flag to mark as passed by action (ie not by default)
        # - distinguish from setting default value through option
        if hasattr(values, '_action_taken'):
            values._action_taken[dest] = True
Ejemplo n.º 31
0
def only_binary():
    # type: () -> Option
    format_control = FormatControl(set(), set())
    return Option(
        "--only-binary",
        dest="format_control",
        action="callback",
        callback=_handle_only_binary,
        type="str",
        default=format_control,
        help="Do not use source packages. Can be supplied multiple times, and "
        'each time adds to the existing value. Accepts either ":all:" to '
        'disable all source packages, ":none:" to empty the set, or one '
        "or more package names with commas between them. Packages "
        "without binary distributions will fail to install when this "
        "option is used on them.",
    )
Ejemplo n.º 32
0
def no_binary():
    # type: () -> Option
    format_control = FormatControl(set(), set())
    return Option(
        "--no-binary",
        dest="format_control",
        action="callback",
        callback=_handle_no_binary,
        type="str",
        default=format_control,
        help="Do not use binary packages. Can be supplied multiple times, and "
        'each time adds to the existing value. Accepts either ":all:" to '
        'disable all binary packages, ":none:" to empty the set (notice '
        "the colons), or one or more package names with commas between "
        "them (no colons). Note that some packages are tricky to compile "
        "and may fail to install when this option is used on them.",
    )
Ejemplo n.º 33
0
 def __init__(self, numa=None):
     BaseTop.__init__(self)
     specific_options = [
         Option('--assert',
                '--assert-mode',
                default=False,
                dest='assert_mode',
                help='Stops running after errors detected.'),
         Option('--dev',
                '--devices',
                default="",
                dest='devices',
                help='Comma-separated list of devices to monitor.'),
         Option('--device-regex',
                default='^.*$',
                help="Regex-mask for devices to monitor."),
         Option(
             '-s',
             '--simple',
             default=False,
             dest='simple_mode',
             action='store_true',
             help=
             'Hides different kinds of error, showing only general counters.'
         ),
         Option('--rx',
                '--rx-only',
                dest='rx_only',
                default=False,
                action='store_true',
                help='Hides tx-counters'),
         Option('--bits', default=False, action='store_true'),
         Option('--bytes', default=False, action='store_true'),
         Option('--kbits', default=False, action='store_true'),
         Option('--mbits', default=True, action='store_true'),
     ]
     self.numa = numa
     self.specific_options.extend(specific_options)
Ejemplo n.º 34
0
def processCommandline():
    "process the commandline, setting the OPTIONS object"
    optionsTable = [
        Option('-c',
               '--channel',
               action='append',
               help=_('name of channel you want to (un)subscribe')),
        Option('-a',
               '--add',
               action='store_true',
               help=_('subscribe to channel')),
        Option('-r',
               '--remove',
               action='store_true',
               help=_('unsubscribe from channel')),
        Option('-l', '--list', action='store_true', help=_('list channels')),
        Option('-L',
               '--available-channels',
               action='store_true',
               help=_('list all available child channels')),
        Option('-v',
               '--verbose',
               action='store_true',
               help=_('verbose output')),
        Option('-u', '--user', action='store', help=_('your user name')),
        Option('-p', '--password', action='store', help=_('your password')),
    ]
    optionParser = OptionParser(option_list=optionsTable)
    global OPTIONS
    OPTIONS, args = optionParser.parse_args()

    # we take no extra commandline arguments that are not linked to an option
    if args:
        systemExit(
            1,
            _("ERROR: these arguments make no sense in this context (try --help)"
              ))
    if not OPTIONS.user and not OPTIONS.list:
        print _("Username: "),
        OPTIONS.user = sys.stdin.readline().rstrip('\n')
    if not OPTIONS.password and not OPTIONS.list:
        OPTIONS.password = getpass.getpass()
Ejemplo n.º 35
0
def get_opt_parser():
    # use module docstring for help output
    p = OptionParser(usage="%s [OPTIONS] [FILE ...]\n\n" % sys.argv[0] +
                     __doc__,
                     version="%prog " + nib.__version__)

    p.add_options([
        Option("-v",
               "--verbose",
               action="count",
               dest="verbose",
               default=0,
               help="Make more noise.  Could be specified multiple times"),
        Option(
            "-H",
            "--header-fields",
            dest="header_fields",
            default='',
            help=
            "Header fields (comma separated) to be printed as well (if present)"
        ),
        Option("-s",
               "--stats",
               action="store_true",
               dest='stats',
               default=False,
               help="Output basic data statistics"),
        Option("-c",
               "--counts",
               action="store_true",
               dest='counts',
               default=False,
               help="Output counts - number of entries for each numeric value "
               "(useful for int ROI maps)"),
        Option("--all-counts",
               action="store_true",
               dest='all_counts',
               default=False,
               help="Output all counts, even if number of unique values > %d" %
               MAX_UNIQUE),
        Option(
            "-z",
            "--zeros",
            action="store_true",
            dest='stats_zeros',
            default=False,
            help=
            "Include zeros into output basic data statistics (--stats, --counts)"
        ),
    ])

    return p
Ejemplo n.º 36
0
class DumpHeader(ConsoleTool):

    # configure command line options
    usage = "usage: %prog [options] fidfile"
    options = (Option("-b",
                      "--blocknum",
                      help="dump header for a particular data block",
                      metavar="<blocknum>"), )

    #-------------------------------------------------------------------------
    def run(self):
        options, args = self.parse_args()

        # get the filename
        if not args:
            self.print_help()
            sys.exit(0)
        else:
            filename = args[0]

        # open fidfile
        try:
            fh = FidFile(filename)
        except IOError, e:
            print e
            self.print_help()
            sys.exit(0)

        # dump the file header
        if options.blocknum is None:
            for fieldname in fh.HEADER_FIELD_NAMES:
                print "%s:" % fieldname, getattr(fh, fieldname)

        # or dump a block header
        else:
            bnum = int(options.blocknum)
            if bnum < 0 or bnum >= fh.nblocks:
                print "Bad blocknum %s.  File has %s blocks." % (bnum,
                                                                 fh.nblocks)
                self.print_help()
                sys.exit(0)
            block = fh.getBlock(bnum)
            for fieldname in block.HEADER_FIELD_NAMES:
                print "%s:" % fieldname, getattr(block, fieldname)
Ejemplo n.º 37
0
class Command(CeleryCommand):
    """The celery command."""
    help = 'celery commands, see celery help'
    options = (
        Option('-A', '--app', default=None),
        Option('--broker', default=None),
        Option('--loader', default=None),
        Option('--config', default=None),
        Option('--workdir', default=None, dest='working_directory'),
        Option('--result-backend', default=None),
        Option('--no-color', '-C', action='store_true', default=None),
        Option('--quiet', '-q', action='store_true'),
    )
    if base.get_options() is not None:
        options = (options + CeleryCommand.options + base.get_options())

    def run_from_argv(self, argv):
        argv = self.handle_default_options(argv)
        base.execute_from_commandline(['{0[0]} {0[1]}'.format(argv)] +
                                      argv[2:], )
Ejemplo n.º 38
0
 def startElement(self, name, attrs):
     if len(attrs) == 0:
         self._group = OptionGroup(self._opts, name)
     if self._group != self._opts and self._groups and self._group.title not in self._groups:
         return
     if 'type' in attrs and name != "help":
         if self._options and name not in self._options:
             return
         help = attrs.get("help", "")
         option = Option("--" + name, help=help)
         if attrs["type"] == "BOOL":
             option = Option(
                 "--" + name, action="store_true", default=False, help=help)
         elif attrs["type"] in ["FLOAT", "TIME"]:
             option.type = "float"
             if attrs["value"]:
                 option.default = float(attrs["value"])
         elif attrs["type"] == "INT":
             option.type = "int"
             if attrs["value"]:
                 option.default = int(attrs["value"])
         else:
             option.default = attrs["value"]
         self._group.add_option(option)
Ejemplo n.º 39
0
def processCommandline():
    "process the command-line"
    credentials = Credentials()

    optionsTable = [
        Option('-c', '--channel', action='append', dest='channels',
               help=_('name of channel you want to (un)subscribe')),
        Option('-a', '--add', action='store_true',
               help=_('subscribe to channel')),
        Option('-r', '--remove', action='store_true',
               help=_('unsubscribe from channel')),
        Option('-l', '--list', action='store_true',
               help=_('list channels')),
        Option('-b', '--base', action='store_true',
               help=_('show base channel of a system')),
        Option('-L', '--available-channels', action='store_true',
               help=_('list all available child channels')),
        Option('-v', '--verbose', action='store_true',
               help=_('verbose output')),
        Option('-u', '--user', action='callback', callback=credentials.user_callback,
               nargs=1, type='string', help=_('your user name')),
        Option('-p', '--password', action='callback', callback=credentials.password_callback,
               nargs=1, type='string', help=_('your password')),
    ]
    optionParser = OptionParser(option_list=optionsTable)
    opts, args = optionParser.parse_args()

    # we take no extra commandline arguments that are not linked to an option
    if args:
        systemExit(1, _("ERROR: these arguments make no sense in this context (try --help)"))

    # remove confusing stuff
    delattr(opts, 'user')
    delattr(opts, 'password')

    return opts, credentials
Ejemplo n.º 40
0
def processCommandline():
    options = [
        Option('--sanity-only',  action='store_true', help="confirm certificate sanity. Does not activate"
               + "the Red Hat Satellite locally or remotely."),
        Option('--ignore-expiration', action='store_true', help='execute regardless of the expiration'
               + 'of the RHN Certificate (not recommended).'),
        Option('--ignore-version-mismatch', action='store_true', help='execute regardless of version '
               + 'mismatch of existing and new certificate.'),
        Option('-v', '--verbose', action='count',      help='be verbose '
               + '(accumulable: -vvv means "be *really* verbose").'),
        Option('--dump-version', action='store', help="requested version of XML dump"),
        Option('--manifest',     action='store',      help='the RHSM manifest path/filename to activate for CDN'),
        Option('--cdn-deactivate', action='store_true', help='deactivate CDN-activated Satellite'),
        Option('--disconnected', action='store_true', help="activate locally, not subscribe to remote repository")
    ]

    options, args = OptionParser(option_list=options).parse_args()

    # we take no extra commandline arguments that are not linked to an option
    if args:
        msg = "ERROR: these arguments make no sense in this context (try --help): %s\n" % repr(args)
        raise ValueError(msg)

    initCFG('server.satellite')

    # No need to check further if deactivating
    if options.cdn_deactivate:
        return options

    if options.sanity_only:
        options.disconnected = 1

    if CFG.DISCONNECTED and not options.disconnected:
        sys.stderr.write("""ERROR: Satellite server has been setup to run in disconnected mode.
       Either correct server configuration in /etc/rhn/rhn.conf
       or use --disconnected to activate it locally.
""")
        sys.exit(1)

    return options
Ejemplo n.º 41
0
    def _getDefaultOpts(self):
        # get the code segment of _init_user_parser()
        with open(self.path, 'rbU') as f:
            code = f.read()
            try:
                funcStart = code.index('_init_user_parser(self):')
                f.seek(0)
                f.read(funcStart)
                f.readline()  # escape line "def _init_user_parser(self):"
                userParserCode = ''
                nextLine = f.readline()
                while not re.findall('(?:^    \S)|(?:^\S\S)', nextLine):
                    userParserCode += nextLine
                    nextLine = f.readline()
                pass
            except ValueError:  # no user defined parser
                return {}

        # strip whitespace characters
        codeStream = StringIO(userParserCode)
        options = []
        argsStr = ''
        for eachLine in codeStream:
            if eachLine.strip().startswith('self.user_parser.add_option'):
                options.append(argsStr)
                argsStr = eachLine.strip()
            else:
                argsStr += eachLine.strip()
        options.append(argsStr)

        # convert string args into variable instance
        reStr = r"([dest|default|type|help|action]+)\s?=\s?(.*?)[,|\)]"
        pattern = re.compile(reStr)
        optDict = {}
        for argsStr in options[1:]:
            args = pattern.findall(argsStr)
            dictStr = '{%s}' % ','.join("'%s':%s" % \
                                        (i[0], i[1]) for i in args if i[0] != 'help')
            argsDict = eval(dictStr)
            opt = Option('--arbitrary', **argsDict)
            optDict.setdefault(argsDict['dest'], opt.default)
        return optDict
Ejemplo n.º 42
0
def setupExtensionsOptions(parser):
    """
    Takes an instance of an OptionParser 
    and adds the options for all extensions
    
    If an extension adds it's own options, those
    options are put in their own group.
    """
    
    if len(extDict) == 0:
        return None
    
    firstGroup = OptionGroup(parser,"Extension options")
    groups = [firstGroup]
    
    for extName, extModule in extDict.items():
        helpArg = {}
        if hasattr(extModule, 'usage'):
            helpArg['help'] = extModule.usage()
            
        extOption = Option('--' + extName, action='append_const', 
                             const = extName, dest = 'active_extensions', **helpArg )
        
        try:
            if hasattr(extModule, 'addExtensionOptions'):
                group = OptionGroup(parser, extName.capitalize() + " extension options")
                group.add_option(extOption)
                
                extModule.addExtensionOptions(group)
                
                if len(group.option_list) == 1:
                    opt = group.option_list[0]
                    group.remove_option(opt.get_opt_string())
                    firstGroup.add_option(opt)
                else:
                    groups.append(group)   
                
            else:
                firstGroup.add_option(extOption)
                
        except OptionConflictError, value:
            print 'Error adding command line options for extension ' + extName + ' ' + '(' + str(value) + ')'
Ejemplo n.º 43
0
def option_recommendation_to_cli_option(add_option, rec):
    opt = rec.option
    switches = ['-' + opt.short_switch] if opt.short_switch else []
    switches.append('--' + opt.long_switch)
    attrs = dict(dest=opt.name,
                 help=opt.help,
                 choices=opt.choices,
                 default=rec.recommended_value)
    if isinstance(rec.recommended_value, type(True)):
        attrs['action'] = 'store_false' if rec.recommended_value else \
                          'store_true'
    else:
        if isinstance(rec.recommended_value, numbers.Integral):
            attrs['type'] = 'int'
        if isinstance(rec.recommended_value, numbers.Real):
            attrs['type'] = 'float'

    if opt.long_switch == 'verbose':
        attrs['action'] = 'count'
        attrs.pop('type', '')
    if opt.name == 'read_metadata_from_opf':
        switches.append('--from-opf')
    elif opt.name == 'transform_css_rules':
        attrs['help'] = _(
            'Path to a file containing rules to transform the CSS styles'
            ' in this book. The easiest way to create such a file is to'
            ' use the wizard for creating rules in the calibre GUI. Access'
            ' it in the "Look & feel->Transform styles" section of the conversion'
            ' dialog. Once you create the rules, you can use the "Export" button'
            ' to save them to a file.')
    elif opt.name == 'transform_html_rules':
        attrs['help'] = _(
            'Path to a file containing rules to transform the HTML'
            ' in this book. The easiest way to create such a file is to'
            ' use the wizard for creating rules in the calibre GUI. Access'
            ' it in the "Look & feel->Transform HTML" section of the conversion'
            ' dialog. Once you create the rules, you can use the "Export" button'
            ' to save them to a file.')
    if opt.name in DEFAULT_TRUE_OPTIONS and rec.recommended_value is True:
        switches = ['--disable-' + opt.long_switch]
    add_option(Option(*switches, **attrs))
Ejemplo n.º 44
0
def main():
    """
    The main routine.
    """
    # Instantiate the app
    app = CmdlineApplication()

    # Handle command-line arguments
    urlOption = Option("-u",
                       "--url",
                       dest="url",
                       default=0,
                       help="URL for the venue server to manage.")
    app.AddCmdLineOption(urlOption)

    # Initialize the application
    try:
        app.Initialize("VenueMgmt")
    except Exception, e:
        print "Exception: ", e
        sys.exit(0)
Ejemplo n.º 45
0
class Command(object):
    long_descr = """\
Purpose: command's purposed (default description)
Usage: command's usage (default description)
"""
    short_descr = None
    # XXX: decide how to deal with subcommands options
    common_options = [Option('-h', '--help',
                             help="Show this message and exits.",
                             action="store_true")]

    def run(self, ctx):
        raise NotImplementedError("run method should be implemented by command classes.")

    def init(self, ctx):
        pass

    def register_options(self, options_context, package_options=None):
        pass

    def finish(self, ctx):
        pass
Ejemplo n.º 46
0
 def _format_option(self,
                    option: optparse.Option,
                    cmd_name: Optional[str] = None) -> List[str]:
     bookmark_line = (f".. _`{cmd_name}_{option._long_opts[0]}`:"
                      if cmd_name else f".. _`{option._long_opts[0]}`:")
     line = ".. option:: "
     if option._short_opts:
         line += option._short_opts[0]
     if option._short_opts and option._long_opts:
         line += ", " + option._long_opts[0]
     elif option._long_opts:
         line += option._long_opts[0]
     if option.takes_value():
         metavar = option.metavar or option.dest
         assert metavar is not None
         line += f" <{metavar.lower()}>"
     # fix defaults
     assert option.help is not None
     opt_help = option.help.replace("%default", str(option.default))
     # fix paths with sys.prefix
     opt_help = opt_help.replace(sys.prefix, "<sys.prefix>")
     return [bookmark_line, "", line, "", "    " + opt_help, ""]
Ejemplo n.º 47
0
def option_recommendation_to_cli_option(add_option, rec):
    opt = rec.option
    switches = ['-'+opt.short_switch] if opt.short_switch else []
    switches.append('--'+opt.long_switch)
    attrs = dict(dest=opt.name, help=opt.help,
                     choices=opt.choices, default=rec.recommended_value)
    if isinstance(rec.recommended_value, type(True)):
        attrs['action'] = 'store_false' if rec.recommended_value else \
                          'store_true'
    else:
        if isinstance(rec.recommended_value, int):
            attrs['type'] = 'int'
        if isinstance(rec.recommended_value, float):
            attrs['type'] = 'float'

    if opt.long_switch == 'verbose':
        attrs['action'] = 'count'
        attrs.pop('type', '')
    if opt.name == 'read_metadata_from_opf':
        switches.append('--from-opf')
    if opt.name in DEFAULT_TRUE_OPTIONS and rec.recommended_value is True:
        switches = ['--disable-'+opt.long_switch]
    add_option(Option(*switches, **attrs))
Ejemplo n.º 48
0
            )
# If log_file is none, logger.py will attempt to find the log file specified in
# INI [DISPLAY] LOG_FILE, failing that it will log to $HOME/<base_log_name>.log

# Note: In all other modules it is best to use the `__name__` attribute
#   to ensure we get a logger with the correct hierarchy.
#   Ex: LOG = logger.getLogger(__name__)

STATUS = Status()
INFO = Info()
PATH = Path()
ERROR_COUNT = 0

options = [
    Option('-c',
           dest='component',
           metavar='NAME',
           help="Set component name to NAME. Default is basename of UI file"),
    Option('-a',
           action='store_true',
           dest='always_top',
           default=False,
           help="set the window to always be on top"),
    Option('-d',
           action='store_true',
           dest='debug',
           default=False,
           help="Enable debug output"),
    Option('-v',
           action='store_true',
           dest='verbose',
           default=False,
Ejemplo n.º 49
0
import sys
import xmlrpclib
from time import strptime
from datetime import datetime

from optparse import OptionParser, Option
from spacewalk.common.cli import getUsernamePassword, xmlrpc_login, xmlrpc_logout

_topdir = '/usr/share/rhn'
if _topdir not in sys.path:
    sys.path.append(_topdir)

client = None

options_table = [
    Option("-v", "--verbose", action="count", help="Increase verbosity"),
    Option("-u", "--username", action="store", help="Username"),
    Option("-p", "--password", action="store", help="Password"),
    Option("-d", "--delete", action="count", help="Delete snapshots."),
    Option("-l", "--list", action="count", help="List snapshot summary."),
    Option("-L",
           "--long-list",
           action="count",
           help="Display comprehensive snapshot list."),
    Option("-a",
           "--all",
           action="count",
           help="Include all snapshots based on criteria provided."),
    Option(
        "--start-date",
        action="store",
Ejemplo n.º 50
0
def processCommandline():

    cfg = config.initUp2dateConfig()
    up2date_cfg = dict(cfg.items())

    if type(up2date_cfg['serverURL']) is type([]):
        rhn_parent = urlparse.urlparse(up2date_cfg['serverURL'][0])[1]
    else:
        rhn_parent = urlparse.urlparse(up2date_cfg['serverURL'])[1]

    httpProxy = urlparse.urlparse(up2date_cfg['httpProxy'])[1]
    httpProxyUsername = up2date_cfg['proxyUser']
    httpProxyPassword = up2date_cfg['proxyPassword']

    if not httpProxy:
        httpProxyUsername, httpProxyPassword = '', ''
    if not httpProxyUsername:
        httpProxyPassword = ''
    ca_cert = ''
    defaultVersion = '5.2'

    # parse options
    optionsTable = [
        Option(
            '-s',
            '--server',
            action='store',
            default=rhn_parent,
            help="alternative server hostname to connect to, default is %s" %
            repr(rhn_parent)),
        Option(
            '--http-proxy',
            action='store',
            default=httpProxy,
            help=
            "alternative HTTP proxy to connect to (HOSTNAME:PORT), default is %s"
            % repr(httpProxy)),
        Option('--http-proxy-username',
               action='store',
               default=httpProxyUsername,
               help="alternative HTTP proxy usename, default is %s" %
               repr(httpProxyUsername)),
        Option('--http-proxy-password',
               action='store',
               default=httpProxyPassword,
               help="alternative HTTP proxy password, default is %s" %
               repr(httpProxyPassword)),
        Option('--ca-cert',
               action='store',
               default=ca_cert,
               help="alternative SSL certificate to use, default is %s" %
               repr(ca_cert)),
        Option('--no-ssl',
               action='store_true',
               help='turn off SSL (not advisable), default is on.'),
        Option(
            '--version',
            action='store',
            default=defaultVersion,
            help=
            'which X.Y version of the Spacewalk Proxy are you upgrading to?' +
            ' Default is your current proxy version (' + defaultVersion + ')'),
        Option('-m',
               '--enable-monitoring',
               action='store_true',
               help='enable MonitoringScout on this proxy.'),
        Option('--deactivate',
               action='store_true',
               help='deactivate proxy, if already activated'),
        Option('-l',
               '--list-available-versions',
               action='store_true',
               help='print list of versions available to this system'),
        Option('--non-interactive',
               action='store_true',
               help='non-interactive mode'),
        Option('-q',
               '--quiet',
               action='store_true',
               help='quiet non-interactive mode.'),
    ]
    parser = OptionParser(option_list=optionsTable)
    options, _args = parser.parse_args()

    if options.server:
        if options.server.find('http') != 0:
            options.server = 'https://' + options.server
        options.server = urlparse.urlparse(options.server)[1]

    if options.no_ssl:
        if not options.quiet:
            sys.stderr.write('warning: user disabled SSL\n')
        options.ca_cert = ''

    if not options.http_proxy:
        options.http_proxy_username, options.http_proxy_password = '', ''

    if not options.http_proxy_username:
        options.http_proxy_password = ''
    exploded_version = options.version.split('.')
    # Pad it to be at least 2 components
    if len(exploded_version) == 1:
        exploded_version.append('0')

    # Make it a string
    options.version = '.'.join(exploded_version[:2])

    if options.quiet:
        options.non_interactive = 1

    return options
Ejemplo n.º 51
0
def main():
    parser = OptionParser(usage="%s WHEEL_FILENAME\n\n" % sys.argv[0] +
                          __doc__,
                          version="%prog " + __version__)
    parser.add_option(
        Option("-p",
               "--plat-tag",
               action="append",
               type='string',
               help="Platform tag to add (e.g. macosx_10_9_intel) (can be "
               "specified multiple times)"))
    parser.add_option(
        Option("-x",
               "--osx-ver",
               action="append",
               type='string',
               help='Alternative method to specify platform tags, by giving '
               'OSX version numbers - e.g. "10_10" results in adding platform '
               'tags "macosx_10_10_intel, "macosx_10_10_x86_64") (can be '
               "specified multiple times)"))
    parser.add_option(
        Option("-w",
               "--wheel-dir",
               action="store",
               type='string',
               help="Directory to store delocated wheels (default is to "
               "overwrite input)"))
    parser.add_option(
        Option("-c",
               "--clobber",
               action="store_true",
               help="Overwrite pre-existing wheels"))
    parser.add_option(
        Option("-r",
               "--rm-orig",
               action="store_true",
               help="Remove unmodified wheel if wheel is rewritten"))
    parser.add_option(
        Option("-k",
               "--skip-errors",
               action="store_true",
               help="Skip wheels that raise errors (e.g. pure wheels)"))
    parser.add_option(
        Option("-v",
               "--verbose",
               action="store_true",
               help="Show more verbose report of progress and failure"))
    (opts, wheels) = parser.parse_args()
    if len(wheels) < 1:
        parser.print_help()
        sys.exit(1)
    multi = len(wheels) > 1
    if opts.wheel_dir:
        wheel_dir = expanduser(opts.wheel_dir)
        if not exists(wheel_dir):
            os.makedirs(wheel_dir)
    else:
        wheel_dir = None
    plat_tags = [] if opts.plat_tag is None else opts.plat_tag
    if opts.osx_ver is not None:
        for ver in opts.osx_ver:
            plat_tags += [
                'macosx_{0}_intel'.format(ver), 'macosx_{0}_x86_64'.format(ver)
            ]
    if len(plat_tags) == 0:
        raise RuntimeError('Need at least one --osx-ver or --plat-tag')
    for wheel in wheels:
        if multi or opts.verbose:
            print('Setting platform tags {0} for wheel {1}'.format(
                ','.join(plat_tags), wheel))
        try:
            fname = add_platforms(wheel,
                                  plat_tags,
                                  wheel_dir,
                                  clobber=opts.clobber)
        except WheelToolsError as e:
            if opts.skip_errors:
                print("Cannot modify {0} because {1}".format(wheel, e))
                continue
            raise
        if opts.verbose:
            if fname is None:
                print('{0} already has tags {1}'.format(
                    wheel, ', '.join(plat_tags)))
            else:
                print("Wrote {0}".format(fname))
        if (opts.rm_orig and fname is not None
                and realpath(fname) != realpath(wheel)):
            os.unlink(wheel)
            if opts.verbose:
                print("Deleted old wheel " + wheel)
Ejemplo n.º 52
0
 def take_action(self, action, dest, opt, value, values, parser):
     if action == "extend":
         values.ensure_value(dest, []).append(value)
     else:
         Option.take_action(self, action, dest, opt, value, values, parser)
Ejemplo n.º 53
0
"""
__author__ = "Leo Singer <*****@*****.**>"


# Command line interface

from optparse import Option, OptionParser
from lalinference.bayestar import command
import lalinference.cmap
from matplotlib import cm
colormap_choices = sorted(cm.cmap_d.keys())
parser = OptionParser(
    description = __doc__,
    usage = "%prog [options] [INPUT]",
    option_list = [
        Option("-o", "--output", metavar="FILE.{pdf,png}",
            help="name of output file [default: plot to screen]"),
        Option("--colormap", default="cylon", choices=colormap_choices,
            metavar='|'.join(colormap_choices),
            help="name of matplotlib colormap [default: %default]"),
        Option("--figure-width", metavar="INCHES", type=float, default=8.,
            help="width of figure in inches [default: %default]"),
        Option("--figure-height", metavar="INCHES", type=float, default=6.,
            help="height of figure in inches [default: %default]"),
        Option("--dpi", metavar="PIXELS", type=int, default=300,
            help="resolution of figure in dots per inch [default: %default]"),
        Option("--contour", metavar="PERCENT", type=float, action="append",
            default=[], help="plot contour enclosing this percentage of"
            + " probability mass [may be specified multiple times, default: none]"),
        Option("--colorbar", default=False, action="store_true",
            help="Show colorbar [default: %default]"),
        Option("--radec", nargs=2, metavar="RA Dec", type=float, action="append",
Ejemplo n.º 54
0
            mc = mtotal * np.power(eta, 3. / 5.)
            m1, m2 = bppu.mc2ms(mc, eta)
        elif has_q:
            m1 = mtotal / (1 + samples['q'])
            m2 = mtotal - m1
        else:
            raise ValueError("Chirp mass given with no mass ratio.")
    return mc, eta, m1, m2, mtotal


if __name__ == "__main__":
    parser = OptionParser(description=__doc__,
                          usage="%prog [options] [INPUT]",
                          option_list=[
                              Option("-o",
                                     "--output",
                                     metavar="FILE.xml",
                                     help="name of output XML file"),
                              Option("--num-of-injs",
                                     metavar="NUM",
                                     type=int,
                                     default=200,
                                     help="number of injections"),
                              Option("--approx",
                                     metavar="APPROX",
                                     default="SpinTaylorT4threePointFivePN",
                                     help="approximant to be injected"),
                              Option("--taper",
                                     metavar="TAPER",
                                     default="TAPER_NONE",
                                     help="Taper methods for injections"),
                              Option("--flow",
Ejemplo n.º 55
0
"""
cfgmgr command line actions and options
"""
import svc
import mgr_parser as mp
from rcOptParser import OptParser
from optparse import Option

PROG = "cfgmgr"

OPT = mp.OPT
OPT.update({
    "key": Option(
        "--key", default=None,
        action="store", dest="key",
        help="The configuration key name."),
    "value_from": Option(
        "--from", default=None,
        action="store", dest="value_from",
        help="Read the configuration values from a file or a directory. If set to '-' or '/dev/stdin', the value is read from stdin, and the --key is mandatory. If set to a file path, the key name is the file basename. If set to a directory, one key per file is added, and the keyname is the relative path, the --key value being used as the relative path prefix."),
    "path": Option(
        "--path", default=None,
        action="store", dest="path",
        help="The path where to install configuration keys."),
    "value": Option(
        "--value", default=None,
        action="store", dest="value",
        help="The configuration key value."),
})

ACTIONS = mp.ACTIONS
Ejemplo n.º 56
0

def _split_comma_semicolon_lists_callback(option, optstr, value, parser):
    """Callback to split provided values
    """
    if value is None:
        return None
    if __debug__:
        debug("CMDLINE", "Splitting %s for %s" % (value, optstr))
    value_split = split_comma_semicolon_lists(value)
    setattr(parser.values, option.dest, value_split)


opt.help = \
    Option("-h", "--help", "--sos",
           action="help",
           help="Show this help message and exit")

opt.verbose = \
    Option("-v", "--verbose", "--verbosity",
           action="callback", callback=_verbose_callback, nargs=1,
           type="int", dest="verbose", default=0,
           help="Verbosity level of output" + _DEF)
"""Pre-cooked `optparse`'s option to specify verbose level"""

commonopts_list = [opt.verbose, opt.help]

if __debug__:
    from mvpa2.base import debug

    ##REF: Name was automagically refactored
Ejemplo n.º 57
0
from lalinference.bayestar import command

methods = '''
    toa_phoa_snr
    toa_snr_mcmc
    toa_phoa_snr_mcmc
    toa_snr_mcmc_kde
    toa_phoa_snr_mcmc_kde
    '''.split()
default_method = "toa_phoa_snr"
parser = OptionParser(
    formatter = command.NewlinePreservingHelpFormatter(),
    description = __doc__,
    usage = '%prog [options] [INPUT.xml[.gz]]',
    option_list = [
        Option("--nside", "-n", type=int, default=-1,
            help="HEALPix lateral resolution [default: auto]"),
        Option("--f-low", type=float, metavar="Hz",
            help="Low frequency cutoff [required]"),
        Option("--waveform",
            help="Waveform to use for determining parameter estimation accuracy from signal model [required]"),
        Option("--min-distance", type=float, metavar="Mpc",
            help="Minimum distance of prior in megaparsec [default: infer from effective distance]"),
        Option("--max-distance", type=float, metavar="Mpc",
            help="Maximum distance of prior in megaparsecs [default: infer from effective distance]"),
        Option("--prior-distance-power", type=int, metavar="-1|2",
            help="Distance prior [-1 for uniform in log, 2 for uniform in volume, default: 2]"),
        Option("--method", choices=methods, metavar='|'.join(methods), default=[], action="append",
            help="Sky localization method [may be specified multiple times, default: "
            + default_method + "]"),
        Option("--chain-dump", default=False, action="store_true",
            help="For MCMC methods, dump the sample chain to disk [default: no]"),
Ejemplo n.º 58
0

def show(name=None, **kwargs):
    cdata = load_context()
    if name is None:
        print(json.dumps(cdata.get("contexts", {}), indent=4))
    else:
        print(json.dumps(cdata.get("contexts", {}).get(name, {}), indent=4))


PROG = "om ctx"
OPT = Storage({
    "help":
    Option("-h",
           "--help",
           action="store_true",
           dest="parm_help",
           help="show this help message and exit"),
    "user":
    Option("--user", action="store", dest="user", help="User name."),
    "cluster":
    Option("--cluster", action="store", dest="cluster", help="Cluster name."),
    "namespace":
    Option("--namespace",
           action="store",
           dest="namespace",
           help="Namespace name or glob pattern."),
    "name":
    Option("--name",
           action="store",
           dest="name",
Ejemplo n.º 59
0
class inspect(Command):
    choices = {
        "active": 1.0,
        "active_queues": 1.0,
        "scheduled": 1.0,
        "reserved": 1.0,
        "stats": 1.0,
        "revoked": 1.0,
        "registered_tasks": 1.0,  # alias to registered
        "registered": 1.0,
        "enable_events": 1.0,
        "disable_events": 1.0,
        "ping": 0.2,
        "add_consumer": 1.0,
        "cancel_consumer": 1.0
    }
    option_list = Command.option_list + (
        Option("--timeout",
               "-t",
               type="float",
               dest="timeout",
               default=None,
               help="Timeout in seconds (float) waiting for reply"),
        Option("--destination",
               "-d",
               dest="destination",
               help="Comma separated list of destination node names."))
    show_body = True

    def usage(self, command):
        return "%%prog %s [options] %s [%s]" % (command, self.args, "|".join(
            self.choices.keys()))

    def run(self, *args, **kwargs):
        self.quiet = kwargs.get("quiet", False)
        self.show_body = kwargs.get("show_body", True)
        if not args:
            raise Error("Missing inspect command. See --help")
        command = args[0]
        if command == "help":
            raise Error("Did you mean 'inspect --help'?")
        if command not in self.choices:
            raise Error("Unknown inspect command: %s" % command)

        destination = kwargs.get("destination")
        timeout = kwargs.get("timeout") or self.choices[command]
        if destination and isinstance(destination, basestring):
            destination = map(str.strip, destination.split(","))

        def on_reply(body):
            c = self.colored
            node = body.keys()[0]
            reply = body[node]
            status, preply = self.prettify(reply)
            self.say("->", c.cyan(node, ": ") + status, indent(preply))

        self.say("<-", command)
        i = self.app.control.inspect(destination=destination,
                                     timeout=timeout,
                                     callback=on_reply)
        replies = getattr(i, command)(*args[1:])
        if not replies:
            raise Error("No nodes replied within time constraint.")
        return replies

    def say(self, direction, title, body=""):
        c = self.colored
        if direction == "<-" and self.quiet:
            return
        dirstr = not self.quiet and c.bold(c.white(direction), " ") or ""
        self.out(c.reset(dirstr, title))
        if body and self.show_body:
            self.out(body)
Ejemplo n.º 60
0
def processCommandline():
    options = [
        Option('--sanity-only',
               action='store_true',
               help="confirm certificate sanity. Does not activate " +
               "the Red Hat Satellite locally or remotely."),
        Option('--ignore-expiration',
               action='store_true',
               help='execute regardless of the expiration ' +
               'of the RHN Certificate (not recommended).'),
        Option('--ignore-version-mismatch',
               action='store_true',
               help='execute regardless of version ' +
               'mismatch of existing and new certificate.'),
        Option('-v',
               '--verbose',
               action='count',
               help='be verbose ' +
               '(accumulable: -vvv means "be *really* verbose").'),
        Option('--dump-version',
               action='store',
               help="requested version of XML dump"),
        Option('--manifest',
               action='store',
               help='the RHSM manifest path/filename to activate for CDN'),
        Option('--rhn-cert',
               action='store',
               help='this option is deprecated, use --manifest instead'),
        Option('--deactivate',
               action='store_true',
               help='deactivate CDN-activated Satellite'),
        Option('--disconnected',
               action='store_true',
               help="activate locally, not subscribe to remote repository"),
        Option('--manifest-info',
               action='store_true',
               help="show information about currently activated manifest"),
        Option('--manifest-download',
               action='store_true',
               help="download new manifest from RHSM to temporary location"),
        Option('--manifest-refresh',
               action='store_true',
               help="download new manifest from RHSM and activate it"),
        Option('--manifest-reconcile-request',
               action='store_true',
               help="request regeneration of entitlement certificates")
    ]

    parser = OptionParser(option_list=options)
    options, args = parser.parse_args()

    initCFG('server.satellite')
    if options.verbose is None:
        options.verbose = 0
    CFG.set('DEBUG', options.verbose)
    rhnLog.initLOG(LOG_PATH, options.verbose)
    log2disk(0, "Command: %s" % str(sys.argv))

    # we take no extra commandline arguments that are not linked to an option
    if args:
        writeError(
            "These arguments make no sense in this context (try --help): %s" %
            repr(args))
        sys.exit(1)

    # No need to check further if deactivating
    if options.deactivate:
        return options

    if options.sanity_only:
        options.disconnected = 1

    if options.manifest_refresh:
        options.manifest_download = 1

    if CFG.DISCONNECTED and not options.disconnected:
        msg = """Satellite server has been setup to run in disconnected mode.
       Either correct server configuration in /etc/rhn/rhn.conf
       or use --disconnected to activate it locally."""
        writeError(msg)
        sys.exit(1)

    options.http_proxy = idn_ascii_to_puny(CFG.HTTP_PROXY)
    options.http_proxy_username = CFG.HTTP_PROXY_USERNAME
    options.http_proxy_password = CFG.HTTP_PROXY_PASSWORD
    log(1, 'HTTP_PROXY: %s' % options.http_proxy)
    log(1, 'HTTP_PROXY_USERNAME: %s' % options.http_proxy_username)
    log(1, 'HTTP_PROXY_PASSWORD: <password>')

    return options