Ϫf&dZddlmZddlZddlZddlZddlZddlZddlmZddl m Z m Z m Z m Z ddlmZmZGddeZeZGd d ZGd d e ee fZd ZdZGddZGddeZGddeZGddeZGddeZGddeZGddeZGddeZ Gdd eZ!Gd!d"eZ"Gd#d$Z#d)d%Z$d*d&Z%d'Z&d(e&_'y)+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. ) annotationsN)path)AnyDictOptionalcast)reflectutilc eZdZy) UsageErrorN)__name__ __module__ __qualname__6/usr/lib/python3/dist-packages/twisted/python/usage.pyr r srr ceZdZdZdZdZy)CoerceParameterzE Utility class that can corce a parameter before storing it. cX||_||_t|jdd|_y)zq @param options: parent Options object @param coerce: callable used to coerce the value. coerceDocN)optionscoercegetattrdoc)selfrrs r__init__zCoerceParameter.__init__*s&   4;; R8rc|td|d |j|}||jj|<y#t$r}td|d}~wwxYw)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: )r r ValueErrorropts)r parameterNamevaluees rdispatchzCoerceParameter.dispatch3so ={=/9PQR R HKK&E,1 -( HB1#FG G Hs> AAAN)r rr__doc__rr$rrrrr%s9 1rrceZdZUdZdZded<dZded<dZded<dZe jZ fdZ e jZd Zd Zdd Zd Zd ZddZdZdZdZddZddZdddZxZS)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 Optional[str] subCommanddefaultSubCommandz'Optional[Options]'parentc`t |||_i|_g|_d|_i|_i|_i|_|j|j|jg}|D]}|\}}}}}}|jj||j |z|_|j j||jj||jj||jj||jj|y)Nr)superrr defaultslongOptshortOptdocssynonyms _dispatch _gather_flags_gather_parameters_gather_handlersextendupdate) r collectorscr/r0r1settingsr2r$ __class__s rrzOptions.__init__s            # #  ! !  ,AFGc CWhh( LL   ( MMH4DM II  T " II  X & MM  * MM  * NN ! !( + ,rc`t|jtjdy)z- Display this help and exit. rN)print__str__sysexitrs ropt_helpzOptions.opt_helps dlln  rcfddlm}td|jt j dy)z3 Display Twisted version and exit. r) copyrightzTwisted version:N)twistedrEr>versionr@rA)rrEs r opt_versionzOptions.opt_versions# &  )"3"34  rc|tjdd}t|dkDrg|ddk(r_ddlm}t j tjd}|j||||jtjd tj||j|j\}}|D]\}}|ddk(r|dd}n|dd}|} | |j vr/|j#dd } | |j vrtd |d |j | } t%|j&| t(r |j&| j+| ||j&| | |t-|d dr|s |j.|s |j.g}|d|dd} } |j0D]R\} } }}| | k(s| | k(s| |_||_||j4_|j4j9| ntd | z |j:||j?y#tj$r}tt|d}~wwxYw#t<$r tdwxYw)z6 The guts of the command-line parser. Nz--_shell-completionr) _shellcomp-_zNo such option '' subCommandszUnknown command: %szWrong number of arguments.) r@argvlentwisted.pythonrLrbasename shellComplete_shellCompFilerAgetoptr0r/errorr strr2replace isinstancer3rr$rr*rQr) subOptionsr+ parseOptions parseArgs TypeError postOptions)rrrLcmdNamer argsr#optarg optMangledsubrestcmdshortparserrs rr^zOptions.parseOptionssm ?hhqrlG w??z2J$..4oFz*33JD*z*:s;! <$ 4 - D**6../QabC+/+;+; >'UFC#:&)DO&,hDO-1DOO*OO006  >!!6!<== ?% U|| %SV$ $ %N ? !=>> ?s$ .H<I+<I(I##I(+Jcy)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. NrrBs rrazOptions.postOptionsrcy)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! NrrBs rr_zOptions.parseArgs"rmrcN|dvrtd|d|dd|j|<y)N)rNzFlag 'z' takes no argument. Not even "z".rJ)r r )rflagNamer"s r _generic_flagzOptions._generic_flag1s/  "DLeT   (rcHgd}}iiiif\}}}}g}tj|jd||D]d}tjd|\} } } | s t d| || <d|| <| r || z}| || <|j | | || <|j|| <f||||||fS)z3 Gather up boolean (flag) options. roptFlagsz A flag cannot be without a name.r)r accumulateClassListr<r padTorappendrq) rr/r0r1r;r2r$flagsflaglongrjrs rr4zOptions._gather_flags9s -/R^*h(##DNNJF 0D#zz!T2 D% !CDDDJHTN#e+"& NN4 !HTN!//HTN 0$(HDDrcgd}}iiiif\}}}}g}tj|jd|i}|D]}tjd|\} } } } } | s t d| || <| || <| r || zdz}| || <|j | dz| || <| t|| || <pt|t|| <||||||fS)z4 Gather options which take a value. r optParametersz%A parameter cannot be without a name.:=) r rur<r rvrrwrrZ)rr/r0r1r;r2r$ parameters parameterrzrjdefaultr paramTypes rr5zOptions._gather_parametersTs-/R^*h( ##DNNOZP# }t |d|z} | |vrg|| <|| j|j dd@|jD]1\} }t|d krt|t }|D]}|||< 3||||||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_rOrMr%Nc||SNrnamer"ms rz*Options._gather_handlers..s 1U8rc|Srrrs rrz*Options._gather_handlers..srrJr~rrNkey) r addMethodNamesToDictr<keysr flagFunctionr[r1getrSrwitemsmax)rr/r0r1r;r2r$dctrmethodtakesArg prettyNamerfn reverse_dctnameslongests rr6zOptions._gather_handlersts-/R^*h($$T^^S&AHHJ# +DT6D=1F'55Hc3/J&)T2C$'Z #'99==#<Z #-HZ +1;)-;#%HZ 4yA~#d?'#~H!+c!1Jz*G# +J HHJ ?DT6D=1F[(&( F#   & &t||C'= >  ? )..0 )MFE5zA~%S)G )!( )  )$(HDDrcN|jdz|jdzS)N width) getSynopsisgetUsagerBs rr?zOptions.__str__s&!D(4==t=+DDDrctjtjd}|j drMdj t jjtj|jdd}|j%dj ||jxrdxsd}nd|jxrdxsdz}ttt|d |}|j!}|jX|jj"Jd j%|jj'|jj"|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 {}rz Usage: {}{}z [options]z%sz [options]synopsis )r filenameToModuleNamer@rRendswithformatosrrU executabler[r+r/rrZrrstripr)joinr)rexecutableNamerrs rrzOptions.getSynopsiss! !55chhqkB  " "; /'..  0&&{B7N ;; #**.,52G t||; BCGWT:w?@??$ ;; ";;))5 55xx((*DKK,B,BHMHrc tt|dr*tt|jj |S|s)t t jjdd}t|drPg}|jD]\}}}}|j|||ddd t||}dd j|z}nd }i} |jjD]*\} } | } | | k7rt| d k(r| | | <!| | vrd| | <+,g} |j D]p}|d d k(rd }|dd }nd}| j|| ||j"|||j$j|d|j&j|ddrt)|ddtt*|j,}n ddl}t)|ddr |j0}nd }|r9ddjt3j4||j7zdz}| r!t| |}dd j|z}nd}||z|zS)Nr]rCOLUMNS80rQcommand)rzrjroptTyperz Commands: rrJrrry)rzrjrrrr$longdescrr%rz Options: %szOptions: None )hasattrrr'r]rintrenvironrrQrw docMakeChunksrr2rrSr/r1r.r3rrZr__main__r%textwrapwrapstrip)rrcmdDictsrirjrkdescchunkscommands longToShortrr"longnameoptDictsrdrrrss rrzOptions.getUsagesF 4 &1:::G G y$78E 4 'H,0,<,< (UFD #!&##,#'  #8U3F$rwwv6HH ----/ JCHxc#h!m(+ H%;.,0K) << C2w#~%#2h  OO(-99S>&#}}00d; $ 2 23 =   $j$/7C/H xD1#++ dii h(FGMMOORVVH "8U3F"''&/2A!A8|h&&rr)returnrZ)rz Optional[int]rrZ)r rrr%r)__annotations__r*r+completionDatar@stdoutrWrobject__hash__rCrHr^rar_rqr4r5r6r?rr __classcell__)r<s@rr'r'BsTl!%J $'+}+"&F &NZZN,DHBH    E6E@HETE>K'K'rr'zshbashcDeZdZUdZdZded<d dZedZdZ dZ y) 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. Nr(_descrc$|||_||_y)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)rdescrrepeats rrzCompleter.__init__>s  DK rc|jryy)N*r)rrBs r _repeatFlagzCompleter._repeatFlagOs <<rc6|j |jS|Sr)rroptNames r _descriptionzCompleter._descriptionVs ;; ";; Nrcr|tk(r!|jd|j|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} r~Unknown shellType _ZSHrrNotImplementedErrorrr shellTypes r _shellCodezCompleter._shellCode\sE  &&'q):):7)C(DAF F!$6ym"DEEr)NF) r rrr%rrrpropertyrrrrrrrr2s7!FM "  Frrc$eZdZdZddZdZdZy) CompleteFilesz6 Completes file names based on a glob pattern c >tj|fi|||_yr)rr _globPattern)r globPatternkws rrzCompleteFiles.__init__ss4&2&'rcv|j|jd|jdS|d|jdS)Nz ())rrrs rrzCompleteFiles._descriptionwsD ;; "kk]"T%6%6$7q9 9Yb!2!2 315 5rc|tk(r6dj|j|j||jSt d|)Nz{}:{}:_files -g "{}"r)rrrrrrrs rrzCompleteFiles._shellCode}sR  )00  !!'*!!  "$6ym"DEErN)r)r rrr%rrrrrrrrns(6 FrrceZdZdZdZy) CompleteDirsz# Completes directory names c|tk(r+dj|j|j|St d|)Nz{}:{}:_directoriesrrrrrrrs rrzCompleteDirs._shellCodesH  '..  $"3"3G"< "$6ym"DEErNr rrr%rrrrrrs FrrceZdZdZdZdZy) CompleteListz2 Completes based on a fixed list of words c >tj|fi|||_yrrr_itemsrrrs rrzCompleteList.__init__4&2& rc|tk(rEdj|j|j|dj |j St d|)Nz {}:{}:({})rrrrrrrrrrs rrzCompleteList._shellCodes\  &&  !!'*KK "$6ym"DEErNr rrr%rrrrrrrs FrrceZdZdZdZdZy)CompleteMultiListzQ Completes multiple comma-separated items based on a fixed list of words c >tj|fi|||_yrrrs rrzCompleteMultiList.__init__rrc|tk(rUdj|j|j||j|dj |j St d|)Nz{}:{}:_values -s , '{}' {}rrrrs rrzCompleteMultiList._shellCodesg  /66  !!'*!!'*%   "$6ym"DEErNrrrrrrsFrrceZdZdZdZy)CompleteUsernamesz Complete usernames cr|tk(r!|jd|j|dStd|)Nr~z:_usersrrrs rrzCompleteUsernames._shellCodeC  &&'q):):7)C(DGL L!$6ym"DEErNrrrrrr FrrceZdZdZdZdZy)CompleteGroupsz% Complete system group names groupcr|tk(r!|jd|j|dStd|)Nr~z:_groupsrrrs rrzCompleteGroups._shellCodesC  &&'q):):7)C(DHM M!$6ym"DEErNr rrr%rrrrrrrsFFrrceZdZdZdZy)CompleteHostnamesz Complete hostnames cr|tk(r!|jd|j|dStd|)Nr~z:_hostsrrrs rrzCompleteHostnames._shellCoderrNrrrrr r rrr ceZdZdZdZdZy)CompleteUserAtHostz A completion action which produces matches in any of these forms:: @ zhost | user@hostcr|tk(r!|jd|j|dStd|)Nr~aT:{_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}rrrs rrzCompleteUserAtHost._shellCodesB  $(#3#3T5F5Fw5OQ "$6ym"DEErNr rrrrrs FFrrceZdZdZdZy)CompleteNetInterfacesz* Complete network interface names c|tk(r+dj|j|j|St d|)Nz{}:{}:_net_interfacesrrrs rrz CompleteNetInterfaces._shellCodesI  *11  !!'* "$6ym"DEErNrrrrrrs Frrc"eZdZdZiggigfdZy) 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. cJ||_||_||_||_||_yr) descriptionsmultiUsemutuallyExclusive optActions extraActions)rrrrrrs rrzCompletions.__init__]s*)  !2$(rN)r rrr%rrrrrr sQj )rrcb|jdd}|D]F}t|jdd}|s!|jdddk(r|d z}t||}H|td z}||z }d |z}g}i} |D],}|jd d| vs|jdd| vr-|jd d|jddfD] } | d | | < g} d } |jd dr d |d fz} nd} |jddr+|d}|jdddk(r|dz}d||fz}| rd} nd |tdzz}|jdddk(rd|z}nd| | |fz}|jddr|dj }nd}|jdddk(r'|jdddj ||d}|jdddk(rE|jdd 2|d}t |tr|jr|d|j}|rtj||}ndg}| j||jdd|D]}| j||d|jdj| /|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. cN|jddxs|jddS)Nrjrz)r)os rrzdocMakeChunks..{s!quuWd3JquuVT7JrrrrzrrNrrJz -s, -- rrjz-%crz%-*s,z--rz %s z %2s%c --%s rrz{} [default: {}]r$z. r)sortrSrrrrr\rrrrrwpopr)optListr maxOptLenrdoptLen colWidth1 colWidth2 colFiller1 optChunksseenxoptLinescommarjrzcolumn1rd column2_llines rrrls LLJLKI/SWWVR() wwy$';6!FI.I /C --I !I yJI D9, 777D !T )SWWVT-Bd-J $')>> A}Q  777D !S\O+EE 7764 v;Dwwy$';6czY--D)c$i/0D 779d #y 0$t+G&%)==G 775" e*""$CC GGIt $ 3 GGIt $ ,$++CY@C GGIt $ 3 : :JA!_-!%%Rw'  c95II7)IMM!$4#5R89 5D OOzl4&3 4 5 *+s9,v rcttj|j}|dkDrt d|xs |j z|dk(ryy)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}. rJzInvalid Option function for %sFT)rSinspect signaturerr r )rrreqArgss rrrsM*'##F+667G{9T=TV__UVV!| rcLt|}|dks|dkDrtd||S)zO Coerce a string value to an int port number, and checks the validity. rizPort number not in range: )rr)r"s r portCoercer6s2 JE qyEEM5eW=>> Lrz#Must be an int between 0 and 65535.)Pr)(r% __future__rrXr2rr@rrtypingrrrrrTr r Exceptionr rYrrZr'r_BASHrrrrrrrr rrrrrr6rrrrr<s! #  ,,)   11:i'd38ni'X 9F9FxFIF2 F9 FF9F*F F(F F FY FF FFF6 FI F`)`)F_D:= r