class ServerOptions(app.ServerOptions): synopsis = "Usage: twistd [options]" optFlags = [ ['nodaemon', 'n', "don't daemonize, don't use default umask of 0077"], ['originalname', None, "Don't try to change the process name"], ['syslog', None, "Log to syslog, not to file"], [ 'euid', '', "Set only effective user-id rather than real user-id. " "(This option has no effect unless the server is running as " "root, in which case it means not to shed all privileges " "after binding ports, retaining the option to regain " "privileges in cases such as spawning processes. " "Use with caution.)" ], ] optParameters = [ ['prefix', None, 'twisted', "use the given prefix when syslogging"], ['pidfile', '', 'twistd.pid', "Name of the pidfile"], [ 'chroot', None, None, 'Chroot to a supplied directory before running' ], ['uid', 'u', None, "The uid to run as.", uidFromString], ['gid', 'g', None, "The gid to run as.", gidFromString], [ 'umask', None, None, "The (octal) file creation mask to apply.", _umask ], ] compData = usage.Completions(optActions={ "pidfile": usage.CompleteFiles("*.pid"), "chroot": usage.CompleteDirs(descr="chroot directory"), "gid": usage.CompleteGroups(descr="gid to run as"), "uid": usage.CompleteUsernames(descr="uid to run as"), "prefix": usage.Completer(descr="syslog prefix"), }, ) def opt_version(self): """Print version information and exit. """ print('twistd (the Twisted daemon) %s' % copyright.version) print(copyright.copyright) sys.exit() def postOptions(self): app.ServerOptions.postOptions(self) if self['pidfile']: self['pidfile'] = os.path.abspath(self['pidfile'])
class Options(usage.Options): synopsis = "[options]" longdesc = "Port Forwarder." optParameters = [ ["port", "p", "6666", "Set the port number."], ["host", "h", "localhost", "Set the host."], ["dest_port", "d", 6665, "Set the destination port."], ] compData = usage.Completions(optActions={"host": usage.CompleteHostnames()})
class Options(usage.Options, app.ReactorSelectionMixin): synopsis = """%s [options] [path to test].py """ % (os.path.basename(sys.argv[0]), ) longdesc = ("ooniprobe loads and executes a suite or a set of suites of" " network tests. These are loaded from modules, packages and" " files listed on the command line") optFlags = [ ["help", "h"], [ 'debug-stacktraces', 'B', 'Report deferred creation and callback stack traces' ], ] optParameters = [ ["reportfile", "o", None, "report file name"], [ "collector", "c", None, "Address of the collector of test results. (example: http://127.0.0.1:8888)" ], ["logfile", "l", None, "log file name"], ["pcapfile", "p", None, "pcap file name"] ] compData = usage.Completions(extraActions=[ usage.CompleteFiles( "*.py", descr="file | module | package | TestCase | testMethod", repeat=True) ], ) tracer = None def __init__(self): self['test'] = None usage.Options.__init__(self) def opt_asciilulz(self): from ooni.utils import logo print logo.getlogo() def opt_spew(self): """ Print an insanely verbose log of everything that happens. Useful when debugging freezes or locks in complex code. """ sys.settrace(spewer) def parseArgs(self, *args): try: self['test'] = args[0] self['subArgs'] = args[1:] except: raise usage.UsageError("No test filename specified!")
class Options(usage.Options): synopsis = "[options]" longdesc = "Makes a telnet server to a Python shell." optParameters = [ ["username", "u", "admin", "set the login username"], ["password", "w", "changeme", "set the password"], ["port", "p", "4040", "port to listen on"], ] compData = usage.Completions( optActions={"username": usage.CompleteUsernames()})
class Options(usage.Options): synopsis = "[-i <interface>] [-p <port>] [-l <file>]" optParameters = [["interface", "i", "127.0.0.1", "local interface to which we listen"], ["port", "p", 1080, "Port on which to listen"], ["log", "l", None, "file to log connection data to"]] compData = usage.Completions( optActions={"log": usage.CompleteFiles("*.log"), "interface": usage.CompleteNetInterfaces()} ) longdesc = "Makes a SOCKSv4 server."
class MyOptions(usage.Options): optParameters = [("user", "u", "guest", "username"), ("password", "w", "guest"), ("service", "s", "twisted.manhole", "PB Service"), ("host", "h", "localhost"), ("port", "p", str(pbportno)), ("perspective", "P", "", "PB Perspective to ask for " "(if different than username)")] compData = usage.Completions(optActions={ "host": usage.CompleteHostnames(), "user": usage.CompleteUsernames() })
class Options(usage.Options): optParameters = [['rpc', 'r', '/etc/rpc', 'RPC procedure table file'], [ 'file', 'f', '/etc/inetd.conf', 'Service configuration file' ]] optFlags = [['nointernal', 'i', "Don't run internal services"]] compData = usage.Completions( optActions={"file": usage.CompleteFiles('*.conf')})
class Options(usage.Options): synopsis = """%s [options] source.py """ % (os.path.basename(sys.argv[0]), ) optParameters = [ ('stylesheet', 's', None, "URL of stylesheet to link to."), ] compData = usage.Completions( extraActions=[usage.CompleteFiles('*.py', descr='source python file')]) def parseArgs(self, filename): self['filename'] = filename
class Options(usage.Options): synopsis = """{} [options] source.py """.format(os.path.basename(sys.argv[0]), ) optParameters = [ ("stylesheet", "s", None, "URL of stylesheet to link to."), ] compData = usage.Completions( extraActions=[usage.CompleteFiles("*.py", descr="source python file")]) def parseArgs(self, filename): self["filename"] = filename
class MyOptions(usage.Options): optFlags = [['quiet', 'q']] optParameters = [ ["tapfile", "t", "twistd.tap"], ["maintainer", "m", "tap2rpm"], ["protocol", "p", None], ["description", "e", None], ["long_description", "l", "Automatically created by tap2rpm"], ["set-version", "V", "1.0"], ["rpmfile", "r", None], ["type", "y", "tap", "type of configuration: 'tap', 'xml, " "'source' or 'python'"], ] compData = usage.Completions( optActions={"type": usage.CompleteList(["tap", "xml", "source", "python"]), "rpmfile": usage.CompleteFiles("*.rpm")} ) def postOptions(self): """ Calculate the default values for certain command-line options. """ # Options whose defaults depend on other parameters. if self['protocol'] is None: base_tapfile = os.path.basename(self['tapfile']) self['protocol'] = os.path.splitext(base_tapfile)[0] if self['description'] is None: self['description'] = "A TCP server for %s" % (self['protocol'],) if self['rpmfile'] is None: self['rpmfile'] = 'twisted-%s' % (self['protocol'],) # Values that aren't options, but are calculated from options and are # handy to have around. self['twistd_option'] = type_dict[self['type']] self['release-name'] = '%s-%s' % (self['rpmfile'], self['set-version']) def opt_unsigned(self): """ Generate an unsigned rather than a signed RPM. (DEPRECATED; unsigned is the default) """ msg = deprecate.getDeprecationWarningString( self.opt_unsigned, versions.Version("Twisted", 12, 1, 0)) warnings.warn(msg, category=DeprecationWarning, stacklevel=2) # Maintain the -u short flag opt_u = opt_unsigned
class Options(usage.Options, strcred.AuthOptionMixin): synopsis = "[-i <interface>] [-p <port>] [-d <dir>] " longdesc = ( "Makes a Conch SSH server. If no authentication methods are " "specified, the default authentication methods are UNIX passwords, " "SSH public keys, and PAM if it is available. If --auth options are " "passed, only the measures specified will be used.") optParameters = [ ["interface", "i", "", "local interface to which we listen"], ["port", "p", "tcp:22", "Port on which to listen"], ["data", "d", "/etc", "directory to look for host keys in"], [ "moduli", "", None, "directory to look for moduli in " "(if different from --data)" ] ] compData = usage.Completions( optActions={ "data": usage.CompleteDirs(descr="data directory"), "moduli": usage.CompleteDirs(descr="moduli directory"), "interface": usage.CompleteNetInterfaces() }) def __init__(self, *a, **kw): usage.Options.__init__(self, *a, **kw) # call the default addCheckers (for backwards compatibility) that will # be used if no --auth option is provided - note that conch's # UNIXPasswordDatabase is used, instead of twisted.plugins.cred_unix's # checker super(Options, self).addChecker(conch_checkers.UNIXPasswordDatabase()) super(Options, self).addChecker( conch_checkers.SSHPublicKeyChecker( conch_checkers.UNIXAuthorizedKeysFiles())) if pamauth is not None: super(Options, self).addChecker( checkers.PluggableAuthenticationModulesChecker()) self._usingDefaultAuth = True def addChecker(self, checker): """ Add the checker specified. If any checkers are added, the default checkers are automatically cleared and the only checkers will be the specified one(s). """ if self._usingDefaultAuth: self['credCheckers'] = [] self['credInterfaces'] = {} self._usingDefaultAuth = False super(Options, self).addChecker(checker)
class ReactorSelectionMixin: """ Provides options for selecting a reactor to install. If a reactor is installed, the short name which was used to locate it is saved as the value for the C{"reactor"} key. """ compData = usage.Completions( optActions={"reactor": _reactorAction}) messageOutput = sys.stdout _getReactorTypes = staticmethod(reactors.getReactorTypes) def opt_help_reactors(self): """ Display a list of possibly available reactor names. """ rcts = sorted(self._getReactorTypes(), key=attrgetter('shortName')) for r in rcts: self.messageOutput.write(' %-4s\t%s\n' % (r.shortName, r.description)) raise SystemExit(0) def opt_reactor(self, shortName): """ Which reactor to use (see --help-reactors for a list of possibilities) """ # Actually actually actually install the reactor right at this very # moment, before any other code (for example, a sub-command plugin) # runs and accidentally imports and installs the default reactor. # # This could probably be improved somehow. try: installReactor(shortName) except NoSuchReactor: msg = ("The specified reactor does not exist: '%s'.\n" "See the list of available reactors with " "--help-reactors" % (shortName,)) raise usage.UsageError(msg) except Exception as e: msg = ("The specified reactor cannot be used, failed with error: " "%s.\nSee the list of available reactors with " "--help-reactors" % (e,)) raise usage.UsageError(msg) else: self["reactor"] = shortName opt_r = opt_reactor
class Options(usage.Options): longdesc = "lore converts documentation formats." optFlags = [ ["plain", 'p', "Report filenames without progress bar"], ["null", 'n', "Do not report filenames"], ["number", 'N', "Add chapter/section numbers to section headings"], ] optParameters = [ ["input", "i", 'lore'], [ "inputext", "e", ".xhtml", "The extension that your Lore input files have" ], ["docsdir", "d", None], ["linkrel", "l", ''], ["output", "o", 'html'], [ "index", "x", None, "The base filename you want to give your index file" ], ["book", "b", None, "The book file to generate a book from"], [ "prefixurl", None, "", "The prefix to stick on to relative links; only useful when processing directories" ], ] compData = usage.Completions( extraActions=[usage.CompleteFiles(descr="files", repeat=True)]) def __init__(self, *args, **kw): usage.Options.__init__(self, *args, **kw) self.config = {} def opt_config(self, s): if '=' in s: k, v = s.split('=', 1) self.config[k] = v else: self.config[s] = 1 def parseArgs(self, *files): self['files'] = files
class Options(usage.Options, strcred.AuthOptionMixin): supportedInterfaces = [credentials.IUsernamePassword] optParameters: List[Sequence[Optional[str]]] = [ ( "hostname", None, socket.gethostname(), "Name of this server; purely an informative", ) ] compData = usage.Completions(multiUse=["group"]) interfacePlugins = {} plg = None for plg in plugin.getPlugins(iwords.IProtocolPlugin): assert plg.name not in interfacePlugins interfacePlugins[plg.name] = plg optParameters.append( ( plg.name + "-port", None, None, "strports description of the port to bind for the " + plg.name + " server", ) ) del plg def __init__(self, *a, **kw): usage.Options.__init__(self, *a, **kw) self["groups"] = [] def opt_group(self, name): """Specify a group which should exist""" self["groups"].append(name.decode(sys.stdin.encoding)) def opt_passwd(self, filename): """ Name of a passwd-style file. (This is for backwards-compatibility only; you should use the --auth command instead.) """ self.addChecker(checkers.FilePasswordDB(filename))
class Options(usage.Options): synopsis = "[-i <interface>] [-p <port>] [-d <dir>] " longdesc = "Makes a Conch SSH server." optParameters = [ ["interface", "i", "", "local interface to which we listen"], ["port", "p", "tcp:22", "Port on which to listen"], ["data", "d", "/etc", "directory to look for host keys in"], [ "moduli", "", None, "directory to look for moduli in " "(if different from --data)" ] ] compData = usage.Completions( optActions={ "data": usage.CompleteDirs(descr="data directory"), "moduli": usage.CompleteDirs(descr="moduli directory"), "interface": usage.CompleteNetInterfaces() })
class Options(usage.Options): synopsis = "[options]" longdesc = 'Fix Client.' optParameters = [ ["hostname", "h", "localhost", "Set the host to connect to."], ["port", "p", 8443, "Set the destination port."], ['spec', 's', None, 'Fix xml spec file'], ['heartbeat_int', 'H', 30, 'Heartbeat Interval'], ['target_comp_id', 'T', None, 'TargetCompId'], ['sender_comp_id', 'S', None, 'SenderCompID'], ['password', 'P', None, 'Password'], ['instrument_id', 'i', None, 'Instrument/security id'], ['market_depth', 'd', 1, 'Market depth'], ['metrics_interval', 'm', 5, 'Interval to record metrics (sec)'], ['statsdir', 'o', os.getcwd(), 'irectory to stora stats output'], ] compData = usage.Completions( optActions={"hostname": usage.CompleteHostnames()})
class Options(usage.Options): synopsis = "[options]" groups = None servers = None subscriptions = None optParameters = [["port", "p", "119", "Listen port"], ["interface", "i", "", "Interface to which to bind"], ["datadir", "d", "news.db", "Root data storage path"], [ "mailhost", "m", "localhost", "Host of SMTP server to use" ]] compData = usage.Completions( optActions={ "datadir": usage.CompleteDirs(), "mailhost": usage.CompleteHostnames(), "interface": usage.CompleteNetInterfaces() }) def __init__(self): usage.Options.__init__(self) self.groups = [] self.servers = [] self.subscriptions = [] def opt_group(self, group): """The name of a newsgroup to carry.""" self.groups.append([group, None]) def opt_moderator(self, moderator): """The email of the moderator for the most recently passed group.""" self.groups[-1][1] = moderator def opt_subscription(self, group): """A newsgroup to list as a recommended subscription.""" self.subscriptions.append(group) def opt_server(self, server): """The address of a Usenet server to pass messages to and receive messages from.""" self.servers.append(server)
class ConvertOptions(usage.Options): synopsis = "Usage: tapconvert [options]" optParameters = [ ['in', 'i', None, "The filename of the tap to read from"], ['out', 'o', None, "A filename to write the tap to"], [ 'typein', 'f', 'guess', "The format to use; this can be 'guess', 'python', " "'pickle', 'xml', or 'source'." ], [ 'typeout', 't', 'source', "The output format to use; this can be 'pickle', 'xml', or 'source'." ], ] optFlags = [[ 'decrypt', 'd', "The specified tap/aos/xml file is encrypted." ], ['encrypt', 'e', "Encrypt file before writing"]] compData = usage.Completions( optActions={ "typein": usage.CompleteList(["guess", "python", "pickle", "xml", "source"]), "typeout": usage.CompleteList(["pickle", "xml", "source"]), "in": usage.CompleteFiles(descr="tap file to read from"), "out": usage.CompleteFiles(descr="tap file to write to"), }) def postOptions(self): if self['in'] is None: raise usage.UsageError("%s\nYou must specify the input filename." % self) if self["typein"] == "guess": try: self["typein"] = sob.guessType(self["in"]) except KeyError: raise usage.UsageError("Could not guess type for '%s'" % self["typein"])
class ClientOptions(options.ConchOptions): synopsis = """Usage: cftp [options] [user@]host cftp [options] [user@]host[:dir[/]] cftp [options] [user@]host[:file [localfile]] """ longdesc = ("cftp is a client for logging into a remote machine and " "executing commands to send and receive file information") optParameters = [ [ "buffersize", "B", 32768, "Size of the buffer to use for sending/receiving." ], [ "batchfile", "b", None, "File to read commands from, or '-' for stdin." ], [ "requests", "R", 5, "Number of requests to make before waiting for a reply." ], ["subsystem", "s", "sftp", "Subsystem/server program to connect to."], ] # type: List[List[Optional[Union[str, int]]]] # noqa compData = usage.Completions( descriptions={ "buffersize": "Size of send/receive buffer (default: 32768)" }, extraActions=[ usage.CompleteUserAtHost(), usage.CompleteFiles(descr="local file"), ], ) def parseArgs(self, host, localPath=None): self["remotePath"] = "" if ":" in host: host, self["remotePath"] = host.split(":", 1) self["remotePath"].rstrip("/") self["host"] = host self["localPath"] = localPath
class Options(usage.Options): """ To use it, create a file named `sample-inetd.conf` with: 8123 stream tcp wait some_user /bin/cat - You can then run it as in the following example and port 8123 became an echo server. twistd -n inetd -f sample-inetd.conf """ optParameters = [[ 'rpc', 'r', '/etc/rpc', 'DEPRECATED. RPC procedure table file' ], ['file', 'f', '/etc/inetd.conf', 'Service configuration file']] optFlags = [['nointernal', 'i', "Don't run internal services"]] compData = usage.Completions( optActions={"file": usage.CompleteFiles('*.conf')})
class Options(usage.Options): """ To use it, create a file named `sample-inetd.conf` with: 8123 stream tcp wait some_user /bin/cat - You can then run it as in the following example and port 8123 became an echo server. twistd -n inetd -f sample-inetd.conf """ optParameters = [ ["rpc", "r", "/etc/rpc", "DEPRECATED. RPC procedure table file"], ["file", "f", "/etc/inetd.conf", "Service configuration file"], ] optFlags = [["nointernal", "i", "Don't run internal services"]] compData = usage.Completions(optActions={"file": usage.CompleteFiles("*.conf")})
class CheckConfigOptions(base.SubcommandOptions): subcommandFunction = "buildbot.scripts.checkconfig.checkconfig" optFlags = [ ['quiet', 'q', "Don't display error messages or tracebacks"], ] # on tab completion, suggest files as first argument if hasattr(usage, 'Completions'): # only set completion suggestion if running with # twisted version (>=11.1.0) that supports it compData = usage.Completions(extraActions=[usage.CompleteFiles()]) def getSynopsis(self): return "Usage:\t\tbuildbot checkconfig [configFile]\n" + \ "\t\tIf not specified, the config file specified in " + \ "'buildbot.tac' from the current directory will be used" def parseArgs(self, *args): if len(args) >= 1: self['configFile'] = args[0]
class GeneralOptions(usage.Options): synopsis = """Usage: ckeygen [options] """ longdesc = "ckeygen manipulates public/private keys in various ways." optParameters = [['bits', 'b', 1024, 'Number of bits in the key to create.'], ['filename', 'f', None, 'Filename of the key file.'], ['type', 't', None, 'Specify type of key to create.'], ['comment', 'C', None, 'Provide new comment.'], ['newpass', 'N', None, 'Provide new passphrase.'], ['pass', 'P', None, 'Provide old passphrase']] optFlags = [['fingerprint', 'l', 'Show fingerprint of key file.'], ['changepass', 'p', 'Change passphrase of private key file.'], ['quiet', 'q', 'Quiet.'], ['showpub', 'y', 'Read private key file and print public key.']] compData = usage.Completions( optActions={"type": usage.CompleteList(["rsa", "dsa"])})
class ClientOptions(options.ConchOptions): synopsis = """Usage: cftp [options] [user@]host cftp [options] [user@]host[:dir[/]] cftp [options] [user@]host[:file [localfile]] """ longdesc = ("cftp is a client for logging into a remote machine and " "executing commands to send and receive file information") optParameters = [ [ 'buffersize', 'B', 32768, 'Size of the buffer to use for sending/receiving.' ], [ 'batchfile', 'b', None, 'File to read commands from, or \'-\' for stdin.' ], [ 'requests', 'R', 5, 'Number of requests to make before waiting for a reply.' ], ['subsystem', 's', 'sftp', 'Subsystem/server program to connect to.'] ] compData = usage.Completions(descriptions={ "buffersize": "Size of send/receive buffer (default: 32768)" }, extraActions=[ usage.CompleteUserAtHost(), usage.CompleteFiles(descr="local file") ]) def parseArgs(self, host, localPath=None): self['remotePath'] = '' if ':' in host: host, self['remotePath'] = host.split(':', 1) self['remotePath'].rstrip('/') self['host'] = host self['localPath'] = localPath
class MyOptions(usage.Options): optFlags = [["unsigned", "u"]] optParameters = [["tapfile", "t", "twistd.tap"], ["maintainer", "m", "", "The maintainer's name and email in a specific format: " "'John Doe <*****@*****.**>'"], ["protocol", "p", ""], ["description", "e", ""], ["long_description", "l", ""], ["set-version", "V", "1.0"], ["debfile", "d", None], ["type", "y", "tap", "type of configuration: 'tap', 'xml, 'source' or 'python' for .tac files"]] compData = usage.Completions( optActions={ "type": usage.CompleteList(["tap", "xml", "source", "python"]), "debfile": usage.CompleteFiles("*.deb")} ) def postOptions(self): if not self["maintainer"]: raise usage.UsageError, "maintainer must be specified."
class MyOptions(usage.Options): optFlags = [["unsigned", "u"], ['quiet', 'q']] optParameters = [ ["tapfile", "t", "twistd.tap"], ["maintainer", "m", "tap2rpm"], ["protocol", "p", None], ["description", "e", None], ["long_description", "l", "Automatically created by tap2rpm"], ["set-version", "V", "1.0"], ["rpmfile", "r", None], [ "type", "y", "tap", "type of configuration: 'tap', 'xml, " "'source' or 'python'" ], ] compData = usage.Completions( optActions={ "type": usage.CompleteList(["tap", "xml", "source", "python"]), "rpmfile": usage.CompleteFiles("*.rpm") }) def postOptions(self): """ Calculate the default values for certain command-line options. """ # Options whose defaults depend on other parameters. if self['protocol'] is None: base_tapfile = os.path.basename(self['tapfile']) self['protocol'] = os.path.splitext(base_tapfile)[0] if self['description'] is None: self['description'] = "A TCP server for %s" % (self['protocol'], ) if self['rpmfile'] is None: self['rpmfile'] = 'twisted-%s' % (self['protocol'], ) # Values that aren't options, but are calculated from options and are # handy to have around. self['twistd_option'] = type_dict[self['type']] self['release-name'] = '%s-%s' % (self['rpmfile'], self['set-version'])
class Options(usage.Options, strcred.AuthOptionMixin): synopsis = "[options]" longdesc = ( "Makes an EssFTP essftp. If --root is not passed as a " "parameter, uses the current working directory. If no auth service " "is specified, it will allow anyone in.") optParameters = [["root", "r", './', "Root directory, as seen by clients"], ["port", "p", "8888", "Port on which to listen"], [ "keyDirectory", "k", None, "Directory to look for host keys in. " "If this is not provided, fake keys will be used." ], [ "moduli", "", None, "Directory to look for moduli in " "(if different from --keyDirectory)" ]] compData = usage.Completions( optActions={ "root": usage.CompleteDirs(descr="root directory"), "keyDirectory": usage.CompleteDirs(descr="key directory"), "moduli": usage.CompleteDirs(descr="moduli directory") })
class GeneralOptions(usage.Options): synopsis = """Usage: ckeygen [options] """ longdesc = "ckeygen manipulates public/private keys in various ways." optParameters = [ ["bits", "b", None, "Number of bits in the key to create."], ["filename", "f", None, "Filename of the key file."], ["type", "t", None, "Specify type of key to create."], ["comment", "C", None, "Provide new comment."], ["newpass", "N", None, "Provide new passphrase."], ["pass", "P", None, "Provide old passphrase."], ["format", "o", "sha256-base64", "Fingerprint format of key file."], [ "private-key-subtype", None, None, 'OpenSSH private key subtype to write ("PEM" or "v1").', ], ] optFlags = [ ["fingerprint", "l", "Show fingerprint of key file."], ["changepass", "p", "Change passphrase of private key file."], ["quiet", "q", "Quiet."], ["no-passphrase", None, "Create the key with no passphrase."], ["showpub", "y", "Read private key file and print public key."], ] compData = usage.Completions( optActions={ "type": usage.CompleteList(list(supportedKeyTypes.keys())), "private-key-subtype": usage.CompleteList(["PEM", "v1"]), } )
class BasedirMixin(object): """SubcommandOptions Mixin to handle subcommands that take a basedir argument""" # on tab completion, suggest directories as first argument if hasattr(usage, 'Completions'): # only set completion suggestion if running with # twisted version (>=11.1.0) that supports it compData = usage.Completions( extraActions=[usage.CompleteDirs(descr="buildbot base directory")]) def parseArgs(self, *args): if len(args) > 0: self['basedir'] = args[0] else: # Use the current directory if no basedir was specified. self['basedir'] = os.getcwd() if len(args) > 1: raise usage.UsageError("I wasn't expecting so many arguments") def postOptions(self): # get an unambiguous, epxnaed basedir, including expanding '~', which # may be useful in a .buildbot/config file self['basedir'] = os.path.abspath(os.path.expanduser(self['basedir']))
class Options(_BasicOptions, usage.Options, app.ReactorSelectionMixin): """ Options to the trial command line tool. @ivar _workerFlags: List of flags which are accepted by trial distributed workers. This is used by C{_getWorkerArguments} to build the command line arguments. @type _workerFlags: C{list} @ivar _workerParameters: List of parameter which are accepted by trial distrubuted workers. This is used by C{_getWorkerArguments} to build the command line arguments. @type _workerParameters: C{list} """ optFlags = [ [ "debug", "b", "Run tests in a debugger. If that debugger is " "pdb, will load '.pdbrc' from current directory if it exists." ], [ "debug-stacktraces", "B", "Report Deferred creation and " "callback stack traces" ], [ "nopm", None, "don't automatically jump into debugger for " "postmorteming of exceptions" ], ["dry-run", 'n', "do everything but run the tests"], ["profile", None, "Run tests under the Python profiler"], ["until-failure", "u", "Repeat test until it fails"], ] optParameters = [[ "debugger", None, "pdb", "the fully qualified name of a debugger to " "use if --debug is passed" ], ["logfile", "l", "test.log", "log file name"], ["jobs", "j", None, "Number of local workers to run"]] compData = usage.Completions(optActions={ "tbformat": usage.CompleteList(["plain", "emacs", "cgitb"]), "reporter": _reporterAction, }, ) _workerFlags = ["disablegc", "force-gc", "coverage"] _workerParameters = ["recursionlimit", "reactor", "without-module"] fallbackReporter = reporter.TreeReporter extra = None tracer = None def opt_jobs(self, number): """ Number of local workers to run, a strictly positive integer. """ try: number = int(number) except ValueError: raise usage.UsageError( "Expecting integer argument to jobs, got '%s'" % number) if number <= 0: raise usage.UsageError( "Argument to jobs must be a strictly positive integer") self["jobs"] = number def _getWorkerArguments(self): """ Return a list of options to pass to distributed workers. """ args = [] for option in self._workerFlags: if self.get(option) is not None: if self[option]: args.append("--%s" % (option, )) for option in self._workerParameters: if self.get(option) is not None: args.extend(["--%s" % (option, ), str(self[option])]) return args def postOptions(self): _BasicOptions.postOptions(self) if self['jobs']: conflicts = ['debug', 'profile', 'debug-stacktraces', 'exitfirst'] for option in conflicts: if self[option]: raise usage.UsageError( "You can't specify --%s when using --jobs" % option) if self['nopm']: if not self['debug']: raise usage.UsageError("You must specify --debug when using " "--nopm ") failure.DO_POST_MORTEM = False