o b@sddZddlZddlZddlZddlZddlZddlmZddlmZm Z ddl m Z m Z Gddde ZeZGdd d ZGd d d eZd Zd ZGdddZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGd d!d!eZGd"d#d#Zd,d%d&Z d-d'd(Z!d)d*Z"d+e"_#dS).a twisted.python.usage is a module for parsing/handling the command line of your program. For information on how to use it, see U{http://twistedmatrix.com/projects/core/documentation/howto/options.html}, or doc/core/howto/options.xhtml in your Twisted directory. N)path)Optionalcast)reflectutilc@s eZdZdS) UsageErrorN)__name__ __module__ __qualname__r r 6/usr/lib/python3/dist-packages/twisted/python/usage.pyrsrc@ eZdZdZddZddZdS)CoerceParameterzE Utility class that can corce a parameter before storing it. cCs ||_||_t|jdd|_dS)zq @param options: parent Options object @param coerce: callable used to coerce the value. coerceDocN)optionscoercegetattrdoc)selfrrr r r __init__*szCoerceParameter.__init__c Cs^|dur td|dz||}Wnty&}ztd|d}~ww||jj|<dS)zj When called in dispatch, do the coerce for C{value} and save the returned value. Nz Parameter 'z' requires an argument.z#Parameter type enforcement failed: )rr ValueErrorropts)r parameterNamevalueer r r dispatch3szCoerceParameter.dispatchN)rr r __doc__rrr r r r r%s rcseZdZUdZdZeeed<dZeeed<dZ ded<dZ e j Z fddZejZd d Zd d Zd#d dZddZddZd#ddZddZddZddZdefddZdefddZd#d eedefd!d"ZZS)$Optionsa5 An option list parser class C{optFlags} and C{optParameters} are lists of available parameters which your program can handle. The difference between the two is the 'flags' have an on(1) or off(0) state (off by default) whereas 'parameters' have an assigned value, with an optional default. (Compare '--verbose' and '--verbosity=2') optFlags is assigned a list of lists. Each list represents a flag parameter, as so:: optFlags = [['verbose', 'v', 'Makes it tell you what it doing.'], ['quiet', 'q', 'Be vewy vewy quiet.']] As you can see, the first item is the long option name (prefixed with '--' on the command line), followed by the short option name (prefixed with '-'), and the description. The description is used for the built-in handling of the --help switch, which prints a usage summary. C{optParameters} is much the same, except the list also contains a default value:: optParameters = [['outfile', 'O', 'outfile.log', 'Description...']] A coerce function can also be specified as the last element: it will be called with the argument and should return the value that will be stored for the option. This function can have a C{coerceDoc} attribute which will be appended to the documentation of the option. subCommands is a list of 4-tuples of (command name, command shortcut, parser class, documentation). If the first non-option argument found is one of the given command names, an instance of the given parser class is instantiated and given the remainder of the arguments to parse and self.opts[command] is set to the command name. For example:: subCommands = [ ['inquisition', 'inquest', InquisitionOptions, 'Perform an inquisition'], ['holyquest', 'quest', HolyQuestOptions, 'Embark upon a holy quest'] ] In this case, C{" holyquest --horseback --for-grail"} will cause C{HolyQuestOptions} to be instantiated and asked to parse C{['--horseback', '--for-grail']}. Currently, only the first sub-command is parsed, and all options following it are passed to its parser. If a subcommand is found, the subCommand attribute is set to its name and the subOptions attribute is set to the Option instance that parses the remaining options. If a subcommand is not given to parseOptions, the subCommand attribute will be None. You can also mark one of the subCommands to be the default:: defaultSubCommand = 'holyquest' In this case, the subCommand attribute will never be None, and the subOptions attribute will always be set. If you want to handle your own options, define a method named C{opt_paramname} that takes C{(self, option)} as arguments. C{option} will be whatever immediately follows the parameter on the command line. Options fully supports the mapping interface, so you can do things like C{'self["option"] = val'} in these methods. Shell tab-completion is supported by this class, for zsh only at present. Zsh ships with a stub file ("completion function") which, for Twisted commands, performs tab-completion on-the-fly using the support provided by this class. The stub file lives in our tree at C{twisted/python/twisted-completion.zsh}, and in the Zsh tree at C{Completion/Unix/Command/_twisted}. Tab-completion is based upon the contents of the optFlags and optParameters lists. And, optionally, additional metadata may be provided by assigning a special attribute, C{compData}, which should be an instance of C{Completions}. See that class for details of what can and should be included - and see the howto for additional help using these features - including how third-parties may take advantage of tab-completion for their own commands. Advanced functionality is covered in the howto documentation, available at U{http://twistedmatrix.com/projects/core/documentation/howto/options.html}, or doc/core/howto/options.xhtml in your Twisted directory. N subCommanddefaultSubCommandzOptional[Options]parentc st||_i|_g|_d|_i|_i|_i|_|j |j |j g}|D]5}|\}}}}}}|j ||j||_|j ||j ||j ||j ||j |q$dS)Nr)superrrdefaultslongOptshortOptdocssynonyms _dispatch _gather_flags_gather_parameters_gather_handlersextendupdate) r collectorscr$r%r&settingsr'r __class__r r rs,       zOptions.__init__cCst|tddS)z- Display this help and exit. rN)print__str__sysexitrr r r opt_helps zOptions.opt_helpcCs&ddlm}td|jtddS)z3 Display Twisted version and exit. r) copyrightzTwisted version:N)twistedr9r3versionr5r6)rr9r r r opt_versions  zOptions.opt_versionc Cs|dur tjdd}t|dkr3|ddkr3ddlm}ttjd}|||||jt dz t ||j |j \}}Wnt j yS}ztt|d}~ww|D]P\}}|ddkrg|dd}n|dd}|} | |jvr|dd } | |jvrtd |d |j| } t|j| tr|j| | |qV|j| | |qVt|d dr|s|jdur|s|jg}|d|dd} } |jD]!\} } }}| | ks| | kr| |_||_||j_|j| nqtd | nz|j|Wn tytdw|dS)z6 The guts of the command-line parser. Nz--_shell-completionr) _shellcomp-_zNo such option '' subCommandszUnknown command: %szWrong number of arguments.) r5argvlentwisted.pythonr?rbasename shellComplete_shellCompFiler6getoptr%r$errorrstrr'replace isinstancer(rrrr rDr subOptionsr! parseOptions parseArgs TypeError postOptions)rrr?cmdNamerargsroptarg optMangledsubrestcmdshortparserrr r r rQsb               zOptions.parseOptionscCdS)z I am called after the options are parsed. Override this method in your subclass to do something after the options have been parsed and assigned, like validate that all options are sane. Nr r7r r r rTzOptions.postOptionscCr_)a I am called with any leftover arguments which were not options. Override me to do something with the remaining arguments on the command line, those which were not flags or options. e.g. interpret them as a list of files to operate on. Note that if there more arguments on the command line than this method accepts, parseArgs will blow up with a getopt.error. This means if you don't override me, parseArgs will blow up if I am passed any arguments at all! Nr r7r r r rR"r`zOptions.parseArgscCs&|dvr td||fd|j|<dS)N)rNz+Flag '%s' takes no argument. Not even "%s".r=)rr)rflagNamerr r r _generic_flag1s  zOptions._generic_flagc Csgd}}iiiif\}}}}g}t|jd||D]1}td|\} } } | s,td| || <d|| <| r>|| }| || <|| | || <|j|| <q||||||fS)z3 Gather up boolean (flag) options. roptFlagsz A flag cannot be without a name.r)raccumulateClassListr2rpadTorappendrb) rr$r%r&r0r'rflagsflaglongr]rr r r r)9s"   zOptions._gather_flagscCsgd}}iiiif\}}}}g}t|jd|i}|D]E}td|\} } } } } | s0td| || <| || <| rD|| d}| || <|| d| || <| dur[t|| || <qt|t|| <q||||||fS)z4 Gather options which take a value. r optParametersz%A parameter cannot be without a name.:=N) rrer2rrfrrgrrM)rr$r%r&r0r'r parameters parameterrjr]defaultr paramTyper r r r*Ts(  zOptions._gather_parameterscCsgd}}iiiif\}}}}i}t|j|d|D]^}t|d|} t| | } |dd} t| dd} | r?| || <n|j| || <| || <| rT| fdd} nd| fd d} | || <t |d krp||}| ro|d }q| rv| d } | | qi}|D]}t|d|} | |vrg|| <||  |ddq| D]\} }t |d krqt |t d}|D]}|||<qq||||||fS)a Gather up options with their own handler methods. This returns a tuple of many values. Amongst those values is a synonyms dictionary, mapping all of the possible aliases (C{str}) for an option to the longest spelling of that option's name C({str}). Another element is a dispatch dictionary, mapping each user-facing option name (with - substituted for _) to a callable to handle that option. ropt_rBr@rNcSs||SNr namermr r r sz*Options._gather_handlers..cSs|Srtr rur r r rxsr=rmrnrAkey) raddMethodNamesToDictr2keysr flagFunctionrNr&getrFrgitemsmax)rr$r%r&r0r'rdctrvmethodtakesArg prettyNamerfn reverse_dctnameslongestr r r r+tsN            zOptions._gather_handlersreturncCs|d|jddS)N width) getSynopsisgetUsager7r r r r4szOptions.__str__cCsttjd}|drdtjtj | dd}|j dur-d||j r)dp*d}n d|j r3d p4d}t tt|d |}|}|j dur]|j jdusPJd |j |j j|f}|S) z Returns a string containing a description of these options and how to pass them to the executed file. rz .__main__z{} -m {}rNz Usage: {}{}z [options]z%sz [options]synopsis )rfilenameToModuleNamer5rEendswithformatosrrH executablerNr!r$rrMrrstriprjoinr)rexecutableNamerqrr r r rs(      zOptions.getSynopsisrc Cst|drtt|jj|dS|sttjdd}t|drCg}|j D]\}}}}| |||dddq$t ||}dd |}nd }i} |j D]\} } | } | | krat| d kra| | | <qL| | vrjd| | <qL qLg} |jD].}|d d krd }|dd }nd}| || ||j|||j|d|j|ddqqt|dddurtt|j}nddl}t|ddr|j}nd }|rdd t||d}| rt | |}dd |}nd}|||S)NrPrCOLUMNS80rDcommand)rjr]roptTyperqz Commands: rr=rnrpri)rjr]rrrqrlongdescrrrz Options: %szOptions: None )hasattrrrrPrintrenvironr~rDrg docMakeChunksrr'rrFr$r&r#r(rrMr__main__rtextwrapwrapstrip)rrcmdDictsr\r]r^descchunkscommands longToShortrzrlongnameoptDictsrWrrrsr r r rsl             zOptions.getUsagert)rr r rrrrM__annotations__r r!completionDatar5stdoutrJrobject__hash__r8r<rQrTrRrbr)r*r+r4rrr __classcell__r r r1r rBs* V  " D  J rzshbashc@sHeZdZUdZdZeeed<d ddZe ddZ d d Z d d Z dS) CompleteraQ A completion "action" - provides completion possibilities for a particular command-line option. For example we might provide the user a fixed list of choices, or files/dirs according to a glob. This class produces no completion matches itself - see the various subclasses for specific completion functionality. N_descrFcCs|dur||_||_dS)a" @type descr: C{str} @param descr: An optional descriptive string displayed above matches. @type repeat: C{bool} @param repeat: A flag, defaulting to False, indicating whether this C{Completer} should repeat - that is, be used to complete more than one command-line word. This may ONLY be set to True for actions in the C{extraActions} keyword argument to C{Completions}. And ONLY if it is the LAST (or only) action in the C{extraActions} list. N)r_repeat)rdescrrepeatr r r r>s  zCompleter.__init__cCs|jrdSdS)N*r)rr7r r r _repeatFlagOszCompleter._repeatFlagcCs|jdur|jS|Srt)rroptNamer r r _descriptionVs zCompleter._descriptioncCs.|tkr|jd||dStd|)a Fetch a fragment of shell code representing this action which is suitable for use by the completion system in _shellcomp.py @type optName: C{str} @param optName: The long name of the option this action is being used for. @type shellType: C{str} @param shellType: One of the supported shell constants e.g. C{twisted.python.usage._ZSH} rmUnknown shellType _ZSHrrNotImplementedErrorrr shellTyper r r _shellCode\s zCompleter._shellCode)NF) rr r rrrrMrrpropertyrrrr r r r r2s    rc@s*eZdZdZd ddZddZddZd S) CompleteFilesz6 Completes file names based on a glob pattern rcKtj|fi|||_dSrt)rr _globPattern)r globPatternkwr r r rs zCompleteFiles.__init__cCs0|jdur|jd|jdS|d|jdS)Nz ())rrrr r r rws zCompleteFiles._descriptioncCs.|tkrd|j|||jStd|)Nz{}:{}:_files -g "{}"r)rrrrrrrr r r r}szCompleteFiles._shellCodeN)r)rr r rrrrr r r r rns   rc@eZdZdZddZdS) CompleteDirsz# Completes directory names cC*|tkrd|j||Std|)Nz{}:{}:_directoriesrrrrrrrr r r rs  zCompleteDirs._shellCodeNrr r rrr r r r r rc@r ) CompleteListz2 Completes based on a fixed list of words cKrrtrr_itemsrrrr r r rrzCompleteList.__init__cCs4|tkrd|j||d|jStd|)Nz {}:{}:({})rrrrrrrrrrr r r rszCompleteList._shellCodeNrr r rrrr r r r r rc@r )CompleteMultiListzQ Completes multiple comma-separated items based on a fixed list of words cKrrtrrr r r rrzCompleteMultiList.__init__cCs<|tkrd|j||||d|jStd|)Nz{}:{}:_values -s , '{}' {}rrrrr r r rs zCompleteMultiList._shellCodeNrr r r r rrrc@r)CompleteUsernamesz Complete usernames cC.|tkr|jd||dStd|)Nrmz:_usersrrrr r r rzCompleteUsernames._shellCodeNrr r r r rrrc@eZdZdZdZddZdS)CompleteGroupsz% Complete system group names groupcCr)Nrmz:_groupsrrrr r r rrzCompleteGroups._shellCodeNrr r rrrr r r r rs rc@r)CompleteHostnamesz Complete hostnames cCr)Nrmz:_hostsrrrr r r rrzCompleteHostnames._shellCodeNrr r r r rrrc@r)CompleteUserAtHostz A completion action which produces matches in any of these forms:: @ zhost | user@hostcCs*|tkrd|j||fStd|)NaY%s:%s:{_ssh;if compset -P "*@"; then _wanted hosts expl "remote host name" _ssh_hosts && ret=0 elif compset -S "@*"; then _wanted users expl "login name" _ssh_users -S "" && ret=0 else if (( $+opt_args[-l] )); then tmp=() else tmp=( "users:login name:_ssh_users -qS@" ) fi; _alternative "hosts:remote host name:_ssh_hosts" "$tmp[@]" && ret=0 fi}rrrr r r rs  zCompleteUserAtHost._shellCodeNrr r r r rs rc@r)CompleteNetInterfacesz* Complete network interface names cCr)Nz{}:{}:_net_interfacesrrrr r r rs z CompleteNetInterfaces._shellCodeNrr r r r rrrc@s$eZdZdZiggigfddZdS) Completionsa: Extra metadata for the shell tab-completion system. @type descriptions: C{dict} @ivar descriptions: ex. C{{"foo" : "use this description for foo instead"}} A dict mapping long option names to alternate descriptions. When this variable is defined, the descriptions contained here will override those descriptions provided in the optFlags and optParameters variables. @type multiUse: C{list} @ivar multiUse: ex. C{ ["foo", "bar"] } An iterable containing those long option names which may appear on the command line more than once. By default, options will only be completed one time. @type mutuallyExclusive: C{list} of C{tuple} @ivar mutuallyExclusive: ex. C{ [("foo", "bar"), ("bar", "baz")] } A sequence of sequences, with each sub-sequence containing those long option names that are mutually exclusive. That is, those options that cannot appear on the command line together. @type optActions: C{dict} @ivar optActions: A dict mapping long option names to shell "actions". These actions define what may be completed as the argument to the given option. By default, all files/dirs will be completed if no action is given. For example:: {"foo" : CompleteFiles("*.py", descr="python files"), "bar" : CompleteList(["one", "two", "three"]), "colors" : CompleteMultiList(["red", "green", "blue"])} Callables may instead be given for the values in this dict. The callable should accept no arguments, and return a C{Completer} instance used as the action in the same way as the literal actions in the example above. As you can see in the example above. The "foo" option will have files that end in .py completed when the user presses Tab. The "bar" option will have either of the strings "one", "two", or "three" completed when the user presses Tab. "colors" will allow multiple arguments to be completed, separated by commas. The possible arguments are red, green, and blue. Examples:: my_command --foo some-file.foo --colors=red,green my_command --colors=green my_command --colors=green,blue Descriptions for the actions may be given with the optional C{descr} keyword argument. This is separate from the description of the option itself. Normally Zsh does not show these descriptions unless you have "verbose" completion turned on. Turn on verbosity with this in your ~/.zshrc:: zstyle ':completion:*' verbose yes zstyle ':completion:*:descriptions' format '%B%d%b' @type extraActions: C{list} @ivar extraActions: Extra arguments are those arguments typically appearing at the end of the command-line, which are not associated with any particular named option. That is, the arguments that are given to the parseArgs() method of your usage.Options subclass. For example:: [CompleteFiles(descr="file to read from"), Completer(descr="book title")] In the example above, the 1st non-option argument will be described as "file to read from" and all file/dir names will be completed (*). The 2nd non-option argument will be described as "book title", but no actual completion matches will be produced. See the various C{Completer} subclasses for other types of things which may be tab-completed (users, groups, network interfaces, etc). Also note the C{repeat=True} flag which may be passed to any of the C{Completer} classes. This is set to allow the C{Completer} instance to be re-used for subsequent command-line words. See the C{Completer} docstring for details. cCs"||_||_||_||_||_dSrt) descriptionsmultiUsemutuallyExclusive optActions extraActions)rrrrrrr r r r]s  zCompletions.__init__N)rr r rrr r r r r sUrPcCsz|jdddd}|D]}t|dd}|r)|ddd kr$|d }t||}q |td }||}d |}g}i} |D]}|d d| vsP|dd| vrQq>|d d|ddfD] } | durgd | | <q]g} d } |d drzd|d f} nd} |ddr|d}|ddd kr|d}d||f}| rd} nd |td}|dddkrd|}nd| | |f}|ddr|d}nd}|ddd kr|dddurd||d}|ddd kr|dddur|d}t|tr|jr|d|j}|rt ||}ndg}| || dd|D] }| ||dq$| d | q>|S)a" Makes doc chunks for option declarations. Takes a list of dictionaries, each of which may have one or more of the keys 'long', 'short', 'doc', 'default', 'optType'. Returns a list of strings. The strings may be multiple lines, all of them end with a newline. cSs|ddp |ddS)Nr]rj)r~)or r r rx{szdocMakeChunks..ryrrjrrNrpr=z -s, -- rr]z-%crnz%-*s,z--rz %s z %2s%c --%s rrqz{} [default: {}]rz. r)sortrFr~rrrrOrrrrrgpopr)optListr maxOptLenrWoptLen colWidth1 colWidth2 colFiller1 optChunksseenxoptLinescommar]rjcolumn1rd column2_lliner r r rlsx        rcCs:tt|j}|dkrtd|p|j|dkrdSdS)a Determine whether a function is an optional handler for a I{flag} or an I{option}. A I{flag} handler takes no additional arguments. It is used to handle command-line arguments like I{--nodaemon}. An I{option} handler takes one argument. It is used to handle command-line arguments like I{--path=/foo/bar}. @param method: The bound method object to inspect. @param name: The name of the option for which the function is a handle. @type name: L{str} @raise UsageError: If the method takes more than one argument. @return: If the method is a flag handler, return C{True}. Otherwise return C{False}. r=zInvalid Option function for %sFT)rFinspect signaturerorr)rrvreqArgsr r r r}s r}cCs*t|}|dks |dkrtd||S)zO Coerce a string value to an int port number, and checks the validity. rizPort number not in range: )rr)rr r r portCoercesrz#Must be an int between 0 and 65535.)rrt)$rrKrrr5rrtypingrrrGrr ExceptionrrLrdictrr_BASHrrrrrrrrrrrrr}rrr r r r sB  o<     c b