o inhin@sddlZddlZddlZddlmZddlmZmZmZm Z m Z m Z m Z ddl mZddlmZmZmZmZddlmZmZddlmZdd lmZmZmZmZejejej ej!ej"ej#ej$hZ%d d Z&Gd d d e'Z(Gddde(Z)dS)N)Mapping)CallableDictListOptionalSequenceTextIOUnion)io) BaseCompleterChoicesCompleterFilesCompleterSuppressCompleter)debug mute_stderr) split_line)IntrospectiveArgumentParseraction_is_greedyaction_is_openaction_is_satisfiedcCs ||SN startswith) completionprefixr>/usr/local/lib/python3.10/dist-packages/argcomplete/finders.pydefault_validators rc@sReZdZdZdddddedfddZdejdddddefdej de e e fd e d eed eee d ee d e dee deddfddZddZddZddZddZddZddZedd Zd!d"Zd#eej d$ejd%e dee fd&d'Zd(d)Zd*ee dee fd+d,Z d*ee d-e d.ee!dee fd/d0Z"d1d2Z#d3d4Z$dS)5CompletionFindera Inherit from this class if you wish to override any of the stages below. Otherwise, use ``argcomplete.autocomplete()`` directly (it's a convenience instance of this class). It has the same signature as :meth:`CompletionFinder.__call__()`. NTFcCs^||_||_||_|durt}||_||_d|_i|_||_|dur*t j ddk}||_ dS)NF_ARGCOMPLETE_SUPPRESS_SPACE1) _parseralways_complete_optionsexcluder validatorprint_suppressed completing_display_completionsdefault_completerosenvironget append_space)selfargument_parserr#r$r%r&r)r-rrr__init__(s  zCompletionFinder.__init__r/r# exit_method output_streamr$r%r&r-r)returnc  sZj||||||| ddtjvrdS|dur1tjd} | dur1td| t| d}|durOztdd}Wnt yNtd|d Ynw|dusUJtjd d t d krntd jd |d tjdrt d krtdjd |d tjd} t tjd} t | | \} }}}}t tjdd }||d}|r|dj jvrd|vr||dd dtd| d| d| d|d|d|||| |}rfddjDfdd|D}tjddkrfd d|D}td!||||tj|ddS)"a :param argument_parser: The argument parser to autocomplete on :param always_complete_options: Controls the autocompletion of option strings if an option string opening character (normally ``-``) has not been entered. If ``True`` (default), both short (``-x``) and long (``--x``) option strings will be suggested. If ``False``, no option strings will be suggested. If ``long``, long options and short options with no long variant will be suggested. If ``short``, short options and long options with no short variant will be suggested. :param exit_method: Method used to stop the program after printing completions. Defaults to :meth:`os._exit`. If you want to perform a normal exit that calls exit handlers, use :meth:`sys.exit`. :param exclude: List of strings representing options to be omitted from autocompletion :param validator: Function to filter all completions through before returning (called with two string arguments, completion and prefix; return value is evaluated as a boolean) :param print_suppressed: Whether or not to autocomplete options that have the ``help=argparse.SUPPRESS`` keyword argument set. :param append_space: Whether to append a space to unique matches. The default is ``True``. .. note:: If you are not subclassing CompletionFinder to override its behaviors, use :meth:`argcomplete.autocomplete()` directly. It has the same signature as this method. Produces tab completions for ``argument_parser``. See module docs for more info. Argcomplete only executes actions if their class is known not to have side effects. Custom action classes can be added to argcomplete.safe_actions, if their values are wanted in the ``parsed_args`` completer argument, or their execution is otherwise desirable. )r#r$r%r&r-r) _ARGCOMPLETEN_ARGCOMPLETE_STDOUT_FILENAMEzUsing output file {}wz)Unable to open fd 8 for writing, quittingr _ARGCOMPLETE_IFS z%Invalid value for IFS, quitting [{v}])v_ARGCOMPLETE_DFSz%Invalid value for DFS, quitting [{v}] COMP_LINE COMP_POINTr=z LINE: {!r}z POINT: {!r}z PREQUOTE: {!r}z PREFIX: {!r}z SUFFIX: {!r}z WORDS:cs&i|]\}}||r|dndqS) replace).0keyvalue)ifsrr sz-CompletionFinder.__call__..cs$g|]}||p dfqS)r@)joinr,)rCrD)dfsdisplay_completionsrr s$z-CompletionFinder.__call__.._ARGCOMPLETE_SHELLzshcs"g|] }|dj|qS):)r(r,rCcr.rrrKs"z Returning completions:)r0r*r+_init_debug_streamr,rformatopenfdopen Exceptionlenintrr" prefix_charsappendsplit_get_completionsr(itemswriterHflush_io debug_stream)r.r/r#r1r2r$r%r&r-r)filename comp_line comp_pointcword_prequote cword_prefix cword_suffix comp_wordslast_wordbreak_posstart completionsr)rIrJrFr.r__call__@s|*               zCompletionFinder.__call__cCs8z tddt_Wn tytjt_YnwtdS)a Initialize debug output stream By default, writes to file descriptor 9, or stderr if that fails. This can be overridden by derived classes, for example to avoid clashes with file descriptors being used elsewhere (such as in pytest). r6N)r*rUr`rarVsysstderrrrQrrrrRs    z#CompletionFinder._init_debug_streamc Cs|}t}d|_z/td|ddt|jj|dd|d}Wdn1s/wYtd|WntyW}ztdt |t |dWYd}~nd}~wwd|_d |vrbd|_ | |||} | | } || ||} | S) NTzinvoking parser withr ) namespacez parsed args:z exceptionzwhile parsing argsFz--)_patch_argument_parserargparse Namespacer'rrr"parse_known_args BaseExceptiontypestrr#collect_completionsfilter_completionsquote_completions) r.rhrfreriactive_parsers parsed_argsaerkrrrr\s(" z!CompletionFinder._get_completionscsFg|_g|_|fdd|jtd|jtd|j|jS)a Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser figure out which subparsers need to be activated (then recursively monkey-patch those). We save all active ArgumentParsers to extract all their possible option names later. csj|j|t|trdSd}t|t|jfi|_|jD]}t|dr*q"Gfddd|j}|j|_ |j |_ ||_q"dS)N(MonkeyPatchedIntrospectiveArgumentParser _orig_classcseZdZdfdd ZdS)zPCompletionFinder._patch_argument_parser..patch..IntrospectActionNcstd|td||||td|jtd|jjs'|j||||ddSt|jtjrFtd|j|d|j||||ddS|jtvr_|j sTj ||j||||ddSdS)NzAction stub called onz args:z orig class:z orig callable:) option_stringz:orig class is a subparsers action: patching and running itr) rr_orig_callabler' issubclassrr_SubParsersAction_name_parser_map safe_actionsoption_stringsvisited_positionalsrZ)r.parserrpvaluesr completerpatchrrrls     zYCompletionFinder._patch_argument_parser..patch..IntrospectAction.__call__r)__name__ __module__ __qualname__rlrrrrIntrospectActionsr) rrZr{ isinstancerrv __class___actionshasattrrrlr)r classnameactionrrrrrs     z6CompletionFinder._patch_argument_parser..patchzActive parsers:zVisited positionals:)r{rr"rrQrrrrqs '  z'CompletionFinder._patch_argument_parserc si}|jD]}|j|}||g|q|D]}||j|jD]}|r5|jp1d|j|<q&qfdd|jD}|S)Nr@cg|] }|r|qSrr)rCsubcmdrfrrrK)z?CompletionFinder._get_subparser_completions..) choiceskeys setdefaultrZ_get_subactionsdestrhelpr() r.rrfaliases_by_parserrDpraliasrkrrr_get_subparser_completionss   z+CompletionFinder._get_subparser_completionscsztdks |jdurfdd|jDSdd|jD}dd|jD}|jdkr0|r.|S|S|jdkr;|r9|S|SgS) NrTcrrrrCoptrrrrK.rz5CompletionFinder._include_options..cSsg|] }t|dkr|qSrWrrrrrK/cSsg|] }t|dkr|qSrrrrrrrK0rlongshort)rWr#r)r.rrf long_opts short_optsrrr_include_options,s    z!CompletionFinder._include_optionscCs|jD]}|jr|jD]}||r|jpd|j|<q qg}|jD]1}|js=t|dd}t|tr6| r6q!|jt j kr=q!| ||sDq!t|t j sR||||7}q!|S)Nr@r)rrrrr(r&getattrrrsuppressrrSUPPRESS_action_allowedrr)r.rrfrroption_completionsrrrr_get_option_completions7s(        z(CompletionFinder._get_option_completionscCs(|j|gD] }||jvrdSqdSNFT)_action_conflictsr,_seen_non_default_actions)rrconflict_actionrrrrLs  z CompletionFinder._action_allowedcsftdjt|j|jd|o|d|jvdfdd|jD}|r.r zexpect at most 1 greedy actionzResetting completions becausezmust consume the next argumentr>FTSkippingzActivating completion forr)rrrr|zICompleter is not callable, trying the readline completer protocol insteadi'csg|]}d|qS)r>r)rCr)optional_prefixrrrKz Completions:)rrSrWactive_actionsrYr( partitionrrrrrrrrrrr r)rrcallablerr]r%rZrrangecomplete)r.rnext_positionalrfr|rkgreedy_actions_complete_remaining_positionals active_actionrcompleter_outputr descriptioninext_completionr)rrr_complete_active_optionUs                  z(CompletionFinder._complete_active_optionr{r|rfcCsg}td||d}td||js t|dkr(|d|jvr(||||7}td||}td|t|tjrD|| ||7}| |||||}td|td|j |S) a0 Visits the active parsers and their actions, executes their completers or introspects them to collect their option strings. Returns the resulting completions as a list of strings. This method is exposed for overriding in subclasses; there is no need to use it directly. zall active parsers:zactive_parser:rzoptional options:znext_positional:zactive options:zdisplay completions:) rr#rWrYr_get_next_positionalrrrrrrr()r.r{r|rfrk active_parserrrrrrxs"         z$CompletionFinder.collect_completionscCsz|jd}|jd}|}|sdS||kr|dSd}tt|D] }|||kr,nq"|dt|kr;||dSdS)z> Get the next positional action if it exists. rNrr )r{r_get_positional_actionsrrW)r.rlast_positionalall_positionalsrrrrrs    z%CompletionFinder._get_next_positionalrkcCs:g}|D]}|jdur||jvrq||vr||q|S)z De-duplicates completions and excludes those specified by ``exclude``. Returns the filtered completions as a list. This method is exposed for overriding in subclasses; there is no need to use it directly. N)r$rZ)r.rkfiltered_completionsrrrrrys   z#CompletionFinder.filter_completionsreric s@d}|dkrdurfdd|D}|d7}n|dkr |d7}tjd d vr+d}n |d kr8d}d d|D}tjd d krId}|dd}nd}tjd dkrW|d7}g}|D]#}|}|D] } || || }qa||||jvr~|j||j|<q[|jrd} t|dkr|dd| vr|dkr|dd7<|S)a If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes occurrences of that quote character in the completions, and adds the quote to the beginning of each completion. Otherwise, escapes all characters that bash splits words on (``COMP_WORDBREAKS``), and removes portions of completions before the first colon if (``COMP_WORDBREAKS``) contains a colon. If there is only one completion, and it doesn't end with a **continuation character** (``/``, ``:``, or ``=``), adds a space after the completion. This method is exposed for overriding in subclasses; there is no need to use it directly. \r@Ncsg|] }|ddqS)r NrrOrirrrKrz6CompletionFinder.quote_completions..z();<>|&!`$* "'"z"`$!rL)tcshfish'cSsg|]}|ddqS)rz'\''rArOrrrrKr powershell`rMrNz=/:r rrr?)r*r+r,rBrZr(r-rW) r.rkreri special_chars escape_charescaped_completionsrescaped_completioncharcontinuation_charsrrrrzsB   z"CompletionFinder.quote_completionscsn|dkr)t\}}}}|dtjd||||}fdd|D|_|t|jkr5|j|SdS)ap Alternate entry point for using the argcomplete completer in a readline-based REPL. See also `rlcompleter `_. Usage: .. code-block:: python import argcomplete, argparse, readline parser = argparse.ArgumentParser() ... completer = argcomplete.CompletionFinder(parser) readline.set_completer_delims("") readline.set_completer(completer.rl_complete) readline.parse_and_bind("tab: complete") result = input("prompt> ") rcs g|] }|tdqSrr)rCmatchrftextrrrKHs z0CompletionFinder.rl_complete..N)rinsertrnargvr\ _rl_matchesrW)r.rstaterergrhfirst_colon_posmatchesrrr rl_complete3s zCompletionFinder.rl_completecCs|jS)zr This function returns a mapping of completions to their help strings for displaying to the user. )r(rQrrrget_display_completionsOsz(CompletionFinder.get_display_completions)%rrr__doc__rr0r*_exitrrArgumentParserr boolrwrrrrr rlrRr\rqrrr staticmethodrrrrsrxrryrXrzrrrrrrr!s       :  T   B rc@seZdZeddZdS)ExclusiveCompletionFindercCs<t||sdStjtjf}|j|vrdS||jvrdSdSr)rrrr _AppendAction_AppendConstActionrr)rrappend_classesrrrrWs    z)ExclusiveCompletionFinder._action_allowedN)rrrrrrrrrrVsr)*rrr*rncollections.abcrtypingrrrrrrr r@r r` completersr r rrrrlexersrpackages._argparserrrr _StoreAction_StoreConstAction_StoreTrueAction_StoreFalseActionrr _CountActionrrobjectrrrrrrs2 $   9