def _set_opt_strings(self, opts): for opt in opts: if len(opt) < 2: msg = 'invalid option string %r: must be at least two characters long' % opt raise optparse.OptionError(msg, self) else: if not (opt[0] == '-' and opt[1] != '-'): msg = 'invalid long option string %r: must start with--, followed by non-dash' % opt raise optparse.OptionError(msg, self) self._long_opts.append(opt)
def _check_choice(self): if self.type in ("choice", "multiple_choice"): if self.choices is None: raise optparse.OptionError( "must supply a list of choices for type 'choice'", self) elif not isinstance(self.choices, (tuple, list)): raise optparse.OptionError( "choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self) elif self.choices is not None: raise optparse.OptionError( "must not supply choices for type %r" % self.type, self)
def _check_choice(self): if self.type in {"choice", "multiple_choice", "confidence"}: if self.choices is None: raise optparse.OptionError( "must supply a list of choices for type 'choice'", self) if not isinstance(self.choices, (tuple, list)): raise optparse.OptionError( # pylint: disable-next=consider-using-f-string "choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self, ) elif self.choices is not None: raise optparse.OptionError( f"must not supply choices for type {self.type!r}", self)
def parse_args(argv): parser = _define_options() args_options, args = parser.parse_args(argv) if args_options.dry_run and args_options.auto: print('The --dry-run and --auto options are mutually exclusive.') sys.exit(1) if args_options.prompt and args_options.auto: print('The --prompt and --auto options are mutually exclusive.') sys.exit(1) # The user may have not been case sensitive on the key name! builder = None if args_options.builder: builders = [ key for key in _builders.iterkeys() if key.lower() == args_options.builder.lower() ] builder = builders[0] if len(builders) == 1 else None if not builder: raise optparse.OptionError( 'Invalid builder specified {0}'.format(args_options.builder), option.builder) build_type = None if args_options.buildtype and args_options.buildtype.capitalize() in [ 'Release', 'Debug' ]: build_type = args_options.buildtype.capitalize() builder_options = BuilderOptions(prompt=args_options.prompt, verbose=args_options.verbose, build_type=build_type, compiler=args_options.compiler, \ timeout=args_options.timeout) return args, args_options, builder, builder_options
def get_suites(values, args): if values.executor_file: raise optparse.OptionError( "superceded by --suites; specify --suites={} {} to run the test(s) under those suite" " configuration(s)".format(values.executor_file, " ".join(args)), "--executor") suite_roots = None if args: # Do not change the execution order of the tests passed as args, unless a tag option is # specified. If an option is specified, then sort the tests for consistent execution order. _config.ORDER_TESTS_BY_NAME = any(tag_filter is not None for tag_filter in (_config.EXCLUDE_WITH_ANY_TAGS, _config.INCLUDE_WITH_ANY_TAGS)) # Build configuration for list of files to run. suite_roots = _get_suite_roots(args) suite_files = values.suite_files.split(",") suites = [] for suite_filename in suite_files: suite_config = _get_suite_config(suite_filename) if suite_roots: # Override the suite's default test files with those passed in from the command line. suite_config.update(suite_roots) suite = testing.suite.Suite(suite_filename, suite_config) suites.append(suite) return suites
def configure(self, options, conf): super(Plugin, self).configure(options, conf) if options.only_focus and options.just_ignore: raise optparse.OptionError( "Please specify only one --with-focus or --without-ignored", "--with-focus") self.enabled = options.only_focus or options.just_ignore self.just_ignore = options.just_ignore
def get_option_def(self, opt): """return the dictionary defining an option given its name""" assert self.options for option in self.options: if option[0] == opt: return option[1] raise optparse.OptionError('no such option %s in section %r' % (opt, self.name), opt)
def get_option_def(self, opt): """return the dictionary defining an option given its name""" assert self.options for option in self.options: if option[0] == opt: return option[1] raise optparse.OptionError( f"no such option {opt} in section {self.name!r}", opt)
def my_parse_args(): res = parser.parse_args_orig() if extraargs is None: if res[1]: raise optparse.OptionError('unrecognized arguments', res[1]) else: res = parser.parse_args_orig() res[0].ensure_value(extraargs, res[1]) return res[0]
def configure(self, options, conf): super(Plugin, self).configure(options, conf) if options.only_focus and options.just_ignore: raise optparse.OptionError("Please specify only one --with-focus or --without-ignored", "--with-focus") self.enabled = options.only_focus or options.just_ignore or options.only_include_filename self.lineage.selector = Selector(conf) self.only_focus = options.only_focus self.just_ignore = options.just_ignore self.only_include_filename = options.only_include_filename self.logger = logging.getLogger('{0}.{1}'.format(__name__, type(self).__name__))
def get_option_def(self, opt: str) -> OptionDict: # pragma: no cover """DEPRECATED: Return the dictionary defining an option given its name. :raises OptionError: If the option isn't found. """ warnings.warn( "get_option_def has been deprecated. It will be removed " "in a future release.", DeprecationWarning, ) assert self.options for option in self.options: if option[0] == opt: return option[1] raise optparse.OptionError( f"no such option {opt} in section {self.name!r}", opt # type: ignore[arg-type] )
def __init__(self, *opts, **kw): # Peel off the container_pair option, etc. kw = self._peel(**kw) optparse.Option.__init__(self, *opts, **kw) if self.type == "boolean": if self.default is optparse.NO_DEFAULT: self.default = False if self._short_opts: raise optparse.OptionError("boolean type not permitted with short opts: %s" % \ ", ".join(self._short_opts), self) if (self.type == "choice") and (self.metavar is None) and (self.choices is not None): self.metavar = " | ".join(self.choices) # Default values. # THE NAME IS NOT THE DEST. self._matName = self.get_opt_string()[2:] # This is a container for options which can't be registered # because they're duplicates. self.phantom_container = None
def exit(self, status=0, msg=None): if status: raise optparse.OptionError(msg, "") else: raise _ExitQuietlyOptionError(msg, "")
def _check_required(self): if self.required and not self.takes_value(): raise optparse.OptionError( "required flag set for option that doesn't take a value", self)
def error(self, msg): raise optparse.OptionError(msg, "")
def startup_options(self): self.action = None self.from_ = None self.to = None self.parser = None self.emitter = None self.emit_header = None self.emit_trailer = None self.in_ = sys.stdin self.out = sys.stdout self.debug = False self.randomize = True self.cc = None self.hostname = None self.listfile = None self.listplugooni = False self.plugin_name = "all" self.controlproxy = None # "socks4a://127.0.0.1:9050/" self.experimentproxy = None usage = """ 'ooni' is the Open Observatory of Network Interference command line usage: ooni-probe [options]""" optparser = optparse.OptionParser(usage=usage) # --plugin def cb_plugin(option, opt, value, oparser): self.action = opt[2:] self.plugin_name = str(value) optparser.add_option("--plugin", type="string", action="callback", callback=cb_plugin, help="run the Plugooni plgoo plugin specified") # --listplugins def cb_list_plugins(option, opt, value, oparser): self.action = opt[2:] optparser.add_option( "--listplugins", action="callback", callback=cb_list_plugins, help="list available Plugooni as plgoos plugin names") # --captiveportal def cb_captiveportal(option, opt, value, oparser): self.action = opt[2:] optparser.add_option("--captiveportal", action="callback", callback=cb_captiveportal, help="run vendor emulated captiveportal tests") # --transhttp def cb_transhttp(option, opt, value, oparser): self.action = opt[2:] optparser.add_option("--transhttp", action="callback", callback=cb_transhttp, help="run Transparent HTTP tests") # --dns def cb_dnstests(option, opt, value, oparser): self.action = opt[2:] optparser.add_option("--dns", action="callback", callback=cb_dnstests, help="run fixed generic dns tests") # --dnsbulk def cb_dnsbulktests(option, opt, value, oparser): self.action = opt[2:] optparser.add_option( "--dnsbulk", action="callback", callback=cb_dnsbulktests, help="run bulk DNS tests in random.shuffle() order") # --dns-cc-check def cb_dnscccheck(option, opt, value, oparser): self.action = opt[2:] optparser.add_option( "--dnscccheck", action="callback", callback=cb_dnscccheck, help="run cc specific bulk DNS tests in random.shuffle() order") # --cc [country code] def cb_cc(option, opt, value, optparser): # XXX: We should check this against a list of supported county codes # and then return the matching value from the list into self.cc self.cc = str(value) optparser.add_option( "--cc", type="string", action="callback", callback=cb_cc, help="set a specific county code -- default is None", ) # --list [url/hostname/ip list in file] def cb_list(option, opt, value, optparser): self.listfile = os.path.expanduser(value) if not os.path.isfile(self.listfile): print "Wrong file '" + value + "' in --list." sys.exit(1) optparser.add_option( "--list", type="string", action="callback", callback=cb_list, help="file to read from -- default is None", ) # --url [url/hostname/ip] def cb_host(option, opt, value, optparser): self.hostname = str(value) optparser.add_option( "--url", type="string", action="callback", callback=cb_host, help="set URL/hostname/IP for use in tests -- default is None", ) # --controlproxy [scheme://host:port] def cb_controlproxy(option, opt, value, optparser): self.controlproxy = str(value) optparser.add_option( "--controlproxy", type="string", action="callback", callback=cb_controlproxy, help="proxy to be used as a control -- default is None", ) # --experimentproxy [scheme://host:port] def cb_experimentproxy(option, opt, value, optparser): self.experimentproxy = str(value) optparser.add_option( "--experimentproxy", type="string", action="callback", callback=cb_experimentproxy, help="proxy to be used for experiments -- default is None", ) # --randomize def cb_randomize(option, opt, value, optparser): self.randomize = bool(int(value)) optparser.add_option( "--randomize", type="choice", choices=['0', '1'], metavar="0|1", action="callback", callback=cb_randomize, help="randomize host order -- default is on", ) # XXX TODO: # pause/resume scans for dns_BULK_DNS_Tests() # setting of control/experiment resolver # setting of control/experiment proxy # def cb_version(option, opt, value, oparser): self.action = 'version' optparser.add_option("-v", "--version", action="callback", callback=cb_version, help="print ooni-probe version") # parse options (opts, args) = optparser.parse_args() # validate options try: if (args): raise optparse.OptionError('extra arguments found', args) if (not self.action): raise optparse.OptionError('RTFS', 'required arguments missing') except optparse.OptionError, err: sys.stderr.write(str(err) + '\n\n') optparser.print_help() sys.exit(1)
def _check_required(self): """Insures that 'required' option can accept a value.""" if self.required and (not self.takes_value()): raise optparse.OptionError( "'required' parameter set for option that does not take a value", self)