Ij} dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z mZddlmZddlmZddlmZmZmZmZmZmZddlmZdd lmZdd lmZm Z erddl!Z!e j"e#Z$ne j"Z$ed Z%d ed e&fdZ'GddZ(de#d e&fdZ)de*e%d e*e%fdZ+dee#d e*e#fdZ,de#d e-e#zfdZ.de#d e*e-e#zfdZ/dee#d e*e#fdZ0de*e#de*e#d dfdZ1de*e#de*e#d dfdZ2d e#d e#fd!Z3de*e#d dfd"Z4d e#dzfd#Z5ej6fd$e#d%e-d e*e#fd&Z7ej6fd'e*e#d%e-d e*e#fd(Z8d)e#d e*e#fd*Z9Gd+d,Z:Gd-d.Z;Gd/d0Z<Gd1d2Z=Gd3d4Z>d5e d6efee d6efzd7e#d dfd8Z?d9e d6efd e@edzfd:ZAGd;dZCd?e#d e#fd@ZDdAe#dBe#d eEfdCZFdDZG dKdEe#dFee#dGe e#e#geEfdzd e#dzfdHZHdIe d6efd eIeJe#efeffdJZKdS)LzShared utility functions.N)CallableIterable)SequenceMatcher)Enum) TYPE_CHECKINGAnyTextIOTypeVarUnioncast) constants) string_utils)ChoicesProviderFunc CompleterFunc_Tvalreturnc2t|tr]|tdkrdS|tdkrdStdt|tr|St |S)aConvert anything to a boolean based on its value. Strings like "True", "true", "False", and "false" return True, True, False, and False respectively. All other values are converted using bool() :param val: value being converted :return: boolean value expressed in the passed in value :raises ValueError: if the string does not contain a value corresponding to a boolean value TFz(must be True or False (case-insensitive)) isinstancestr capitalize ValueErrorbool)rs b/home/jenkins/jenkins/workspace/simtester-sanitize/venv/lib/python3.11/site-packages/cmd2/utils.pyto_boolr.s#sE >>  s4yy ( (4 >>  s5zz ) )5CDDD#t 99ceZdZdZdddddddedeeeegefzdedededzd eeeegefdzd e edzd e dzd e dzd dfdZ e d efdZejded dfdZdS)SettablezMUsed to configure an attribute to be settable via the set command in the CLI.N)settable_attrib_name onchange_cbchoiceschoices_provider completernameval_type descriptionsettable_objectr r!r"r#r$rc|tur9dtdttfd} t}t t | }||_||_||_||_ ||n||_ ||_ ||_ ||_ | |_dS)aSettable Initializer. :param name: The user-facing name for this setting in the CLI. :param val_type: A callable used to cast the string value from the CLI into its proper type and validate it. This function should raise an exception (like ValueError or TypeError) if the conversion or validation fails, which will be caught and displayed to the user by the set command. For example, setting this to int ensures the input is a valid integer. Specifying bool automatically provides tab completion for 'true' and 'false' and uses a built-in function for conversion and validation. :param description: A concise string that describes the purpose of this setting. :param settable_object: The object that owns the attribute being made settable (e.g. self). :param settable_attrib_name: The name of the attribute on the settable_object that will be modified. This defaults to the value of the name parameter if not specified. :param onchange_cb: An optional function or method to call when the value of this setting is altered by the set command. The callback is invoked only if the new value is different from the old one. It receives three arguments: param_name: str - name of the parameter old_value: Any - the parameter's old value new_value: Any - the parameter's new value The following optional settings provide tab completion for a parameter's values. They correspond to the same settings in argparse-based tab completion. A maximum of one of these should be provided. :param choices: iterable of accepted values :param choices_provider: function that provides choices for this argument :param completer: tab completion function that provides choices for this argument _rc ddgS)z&Tab complete lowercase boolean values.truefalse)r*s rget_bool_choicesz+Settable.__init__..get_bool_choicesvs ((rN)rrlistrr rr%r&r' settable_objr r!r"r#r$) selfr%r&r'r(r r!r"r#r$r/s r__init__zSettable.__init__Fs\ t   )C )DI ) ) ) )H#$79IJJ    &+ > > > > # " " "r)__name__ __module__ __qualname____doc__rtyperrobjectrrrr3propertyr7setterr.rrrrCsHWW,0=A(,7;*.?#?#?#?#s)hucz22?# ?#  ?#"Dj?#sCos23d:?##%?#.4?#!4'?# ?#?#?#?#BEsEEEXE \?3?4???\???rr file_pathcptjtj|}d} t |dd5}t d|Ddkrd}dddn #1swxYwYn#t$rt$rYnwxYw|S) zReturn if a file contains only ASCII or UTF-8 encoded text and isn't empty. :param file_path: path to the file being checked :return: True if the file is a non-empty text file, otherwise False :raises OSError: if file can't be read Futf-8strictencodingerrorsc3K|]}dVdS)r Nr.).0r*s r zis_text_file..s..1......rrTN) ospathabspath expanduserstripopensumOSErrorUnicodeDecodeError)rI expanded_pathvalid_text_filefs r is_text_filer_sGOOBG$6$6y7H7H$I$IJJMO  -'( C C C 'q..a...  1$$"& ' ' ' ' ' ' ' ' ' ' ' ' ' ' '        s6B$ B BBBBBB32B3 list_to_prunecxt|}t|S)zRemove duplicates from a list while preserving order of the items. :param list_to_prune: the list being pruned of duplicates :return: The pruned list )dictfromkeysr0keys)r` temp_dicts rremove_duplicatesrfs-  m,,I    ! !!r list_to_sortc8t|tjS)a)Sorts a list of strings alphabetically. For example: ['a1', 'A11', 'A2', 'a22', 'a3'] To sort a list in place, don't call this method, which makes a copy. Instead, do this: my_list.sort(key=norm_fold) :param list_to_sort: the list being sorted :return: the sorted list key)sortedsu norm_foldrgs ralphabetical_sortros ,BL 1 1 11r input_strcj t|S#t$rtj|cYSwxYw)zTry to convert the passed-in string to an integer. If that fails, it converts it to lower case using norm_fold. :param input_str: string to convert :return: the string as an integer or a lower case version of the string. )intrrlrmrps rtry_int_or_force_to_lower_casertsD '9~~ '''|I&&&&&'s 22c@dtjd|DS)zConvert a string into a list of integers and strings to support natural sorting (see natural_sort). For example: natural_keys('abc123def') -> ['abc', '123', 'def'] :param input_str: string to convert :return: list of strings and integers c,g|]}t|Sr.)rt)rQsubstrs r z natural_keys..s! _ _ _v *6 2 2 _ _ _rz(\d+))resplitrss r natural_keysr{s& ` _(T]A^A^ _ _ __rc.t|tS)aQSorts a list of strings case insensitively as well as numerically. For example: ['a1', 'A2', 'a3', 'A11', 'a22'] To sort a list in place, don't call this method, which makes a copy. Instead, do this: my_list.sort(key=natural_keys) :param list_to_sort: the list being sorted :return: the list sorted naturally ri)rkr{rns r natural_sortr}s ,L 1 1 11rtokenstokens_to_quotecft|D] \}}||vrtj|||<!dS)zQuote specific tokens in a list. :param tokens: token list being edited :param tokens_to_quote: the tokens, which if present in tokens, to quote N) enumeraterlquote)r~ritokens rquote_specific_tokensrsF f%%((5 O # #F1I((rtokens_to_unquotecjt|D]"\}}tj|}||vr|||<#dS)zUnquote specific tokens in a list. :param tokens: token list being edited :param tokens_to_unquote: the tokens, which if present in tokens, to unquote N)rrl strip_quotes)r~rrrunquoted_tokens runquote_specific_tokensrsN f%%''5// . . .&F1I''rrc|r\tj|r|d}tj|}nd}tj|}|r||z|z}|S)zkWrap os.expanduser() to support expanding ~ in quoted strings. :param token: the string to expand r)rl is_quotedrrSrTrV)r quote_chars r expand_userrsp  4 <   qJOE**EEJ""5))  4&3E Lrc`t|D]\}}t||||<dS)zaCall expand_user() on all tokens in a list of strings. :param tokens: tokens to expand. N)rr)r~indexr*s rexpand_user_in_tokensr&s@ f%%33q#F5M22u 33rctjd}|s$tjdddkrgd}ngd}tjd}|gn-d|tjjD}tj ||D]\}}tj ||}tj |ratj |tjrBtjdddkr&tj|d }n|}nd}|S) zSet cmd2.Cmd.DEFAULT_EDITOR. If EDITOR env variable is set, that will be used. Otherwise the function will look for a known editor in directories specified by PATH env variable. :return: Default editor or None. EDITORNwin)editzcode.cmdz notepad++.exez notepad.exe) vimviemacsnanopicojoecodesublgeditkatePATHcPg|]#}tj|!|$Sr.rSrTislinkrQps rrxzfind_editor..>s0,q,q,q1_a_f_m_mno_p_p,qQ,q,q,qrr)rSenvirongetsysplatformgetenvrzrTpathsep itertoolsproductr:isfileaccessX_OKsplitext)editoreditorsenv_pathpathspossible_editorrT editor_paths r find_editorr/s3 Z^^H % %F  < u $ $JJJGGdddG9V$$&,q,qrw8W8W,q,q,q%.%6w%F%F   !OT',,t_==Kw~~k** rybg/N/N <#u,,W--o>>qAFF,FF MrpatternrcDfdtj|DS)avReturn a list of file paths based on a glob pattern. Only files are returned, not directories, and optionally only files for which the user has a specified access to. :param pattern: file name or glob pattern :param access: file access type to verify (os.* where * is F_OK, R_OK, W_OK, or X_OK) :return: list of files matching the name or glob pattern c|g|]8}tj|!tj|6|9Sr.)rSrTrr)rQr^rs rrxz+files_from_glob_pattern..Xs> X X X!RW^^A->-> X29QPVCWCW XA X X Xr)glob)rrs `rfiles_from_glob_patternrOs* Y X X Xty)) X X XXrpatternsc`g}|D](}t||}||)|S)aReturn a list of file paths based on a list of glob patterns. Only files are returned, not directories, and optionally only files for which the user has a specified access to. :param patterns: list of file names and/or glob patterns :param access: file access type to verify (os.* where * is F_OK, R_OK, W_OK, or X_OK) :return: list of files matching the names and/or glob patterns r)rextend)rrfilesrmatchess rfiles_from_glob_patternsr[sD E)'&AAA W Lr starts_withcddg}|D] }||vrgcS tjd}|gn-d|tjjD}t }|D]w}tj||}t|dztj}|D]4} | tj | 5xt|S)zReturn names of executables in a user's path. :param starts_with: what the exes should start with. leave blank for all exes in path. :return: a list of matching exe names *?rNcPg|]#}tj|!|$Sr.rrs rrxz$get_exes_in_path..ys0(m(m(mq[][b[i[ijk[l[l(m(m(m(mrr) rSrrzrTrsetr:rraddbasenamer0) r wildcardswildcardrrexes_setrT full_pathrmatchs rget_exes_in_pathrksc I { " "III #y  H"BB(m(mHNN27?4S4S(m(m(mEuuH22GLL{33 ))c/"'JJJ 2 2E LL))%00 1 1 1 1 2 >>rc eZdZdZdddddeedfdeded ed d f d Zd ed d fdZ d efdZ d e fdZ dde d zd efdZd e fdZddZd efdZed efdZded efdZd S)StdSimzClass to simulate behavior of sys.stdout or sys.stderr. Stores contents in internal buffer and optionally echos to the inner stream it is simulating. FrKreplace)echorNrO inner_streamrrNrOrNct||_||_||_||_d|_t ||_dS)afStdSim Initializer. :param inner_stream: the wrapped stream. Should be a TextIO or StdSim instance. :param echo: if True, then all input will be echoed to inner_stream :param encoding: codec for encoding/decoding strings (defaults to utf-8) :param errors: how to handle encoding/decoding errors (defaults to replace) FN)rrrNrO pause_storageByteBufbuffer)r2rrrNrOs rr3zStdSim.__init__s:)    "dmm rsc*t|tstdt||js4|jxj||j|j z c_|j r|j |dSdS)zAdd str to internal bytes buffer and if echo is True, echo contents to inner stream. :param s: String to write to the stream z"write() argument must be str, not rMN) rr TypeErrorrErrbyte_bufencoderNrOrrwrite)r2rs rrz StdSim.writes !S!! LJaJJKK K! Y K AHHdmDKH$X$X X 9 '   # #A & & & & & ' 'rcX|jj|j|jS)z#Get the internal contents as a str.rM)rrdecoderNrOr6s rgetvaluezStdSim.getvalues${#**DM$+*VVVrc4t|jjS)z#Get the internal contents as bytes.)bytesrrr6s rgetbyteszStdSim.getbytessT[)***rsizec ||dkr)|}|nQ|jjd||j|j}|jj|d|j_|S)zRead from the internal contents as a str and then clear them out. :param size: Number of bytes to read from the stream NrrM)rclearrrrrNrO)r2rresults rreadz StdSim.readsv <42::]]__F JJLLLL[)%4%077W[Wb7ccF#';#7#>DK  rcV|}||S)zARead from the internal contents as bytes and then clear them out.)rr)r2rs r readbyteszStdSim.readbytess!  rcB|jjdS)zClear the internal contents.N)rrrr6s rrz StdSim.clears ""$$$$$rcF|jr|jSdS)z[StdSim only considered an interactive stream if `echo` is True and `inner_stream` is a tty.F)rrisattyr6s rrz StdSim.isattys& 9 .$++-- -urcX t|jjS#t$rYdSwxYw)zHandle when the inner stream doesn't have a line_buffering attribute. Which is the case when running unit tests because pytest sets stdout to a pytest EncodedFile object. F)rrline_bufferingAttributeErrorr6s rrzStdSim.line_bufferings=  )899 9   55 s  ))itemcX||jvr |j|St|j|S)zhWhen an attribute lookup fails to find the attribute in the usual places, this special method is called.)__dict__r5r)r2rs r __getattr__zStdSim.__getattr__s/ 4= =& &t($///r)rrN)rArBrCrDr r rrr3rrrrrrrrrrrGrrrr.rrrrs $$$FH,-$ $  $  $ $$$$, 's 't ' ' ' 'W#WWWW+%++++  t S    5 %%%% X00000000rrc6eZdZdZdZdeddfdZdeddfdZdS) rzHUsed by StdSim to write binary data and stores the actual bytes written.)  std_sim_instancerNc:t|_||_dS)z Initialize the ByteBuf instance.N) bytearrayrr)r2rs rr3zByteBuf.__init__s!  0rbcttstdt|jjs|xjz c_|jjrp|jjj |jj rBtfdtjDr|jdSdSdSdS)zVAdd bytes to internal bytes buffer and if echo is True, echo contents to inner stream.z%a bytes-like object is required, not c3 K|]}|vV dSNr.)rQnewliners rrRz ByteBuf.write..s';i;iWGqL;i;i;i;i;i;irN)rrrrErrrrrrrranyrNEWLINESflush)r2rs `rrz ByteBuf.writes!U## OMDGGMMNN N$2  MMQ MM  % .  ! . 5 ; ;A > > > $3 .;i;i;i;iX_Xh;i;i;i8i8i .%++----- . . . . . .r) rArBrCrDr rr3rrr.rrrrseRRH11D1111 .u.......rrceZdZdZdedeezdeezddfdZddZdd Z dd Z d e ddfd Z e d eezdeezddfdZdS) ProcReaderzUsed to capture stdout and stderr from a Popen process if any of those were set to subprocess.PIPE. If neither are pipes, then the process will run normally and no output will be captured. procstdoutstderrrNcT||_||_||_tjd|jddi|_tjd|jddi|_|jj|j |jj |j dSdS)zProcReader initializer. :param proc: the Popen process being read from :param stdout: the stream to write captured stdout :param stderr: the stream to write captured stderr. out_thread read_stdoutT)r%targetkwargs err_threadFN) _proc_stdout_stderr threadingThread_reader_thread_func _out_thread _err_threadrstartr)r2r rrs rr3zProcReader.__init__ s   $+dF^huw{g|}}}$+dF^huw|g}~~~ :  (   " " $ $ $ :  (   " " $ $ $ $ $ ) (rc"ddl}tjdr!|j|jdS tj|jj }tj ||j dS#t$rYdSwxYw)zASend a SIGINT to the process similar to if +C were pressed.rNr) signalrr startswithr send_signalCTRL_BREAK_EVENTrSgetpgidpidkillpgSIGINTProcessLookupError)r2r group_ids r send_sigintzProcReader.send_sigint!s < " "5 ) )  J " "6#: ; ; ; ; ; :djn55 (FM22222%    s8B B Bc8|jdS)zTerminate the process.N)r terminater6s rr,zProcReader.terminate2s rc~|jr|j|jr|j|j\}}|r||j||r||j|dSdS)zWait for the process to finish.N) ris_aliver:rr communicate _write_bytesrr)r2outerrs rwaitzProcReader.wait6s   $ $ & & $   ! ! # # #   $ $ & & $   ! ! # # #:))++S  1   dlC 0 0 0  1   dlC 0 0 0 0 0 1 1rrc~|r|jj}|j}n|jj}|j}|t d|ji|}|r8|t|| |||jgdSdS)zThread function that reads a stream from the process. :param read_stdout: if True, then this thread deals with stdout. Otherwise it deals with stderr. Nzread_stream is None) rrrrrrpollpeekrlenr0)r2r read_stream write_stream availables rrzProcReader._reader_thread_funcFs  (*+KeZdZdZd dZdefdZd dZdeddfdZ dS) ContextFlaga{A context manager which is also used as a boolean flag value within the default sigint handler. Its main use is as a flag to prevent the SIGINT handler in cmd2 from raising a KeyboardInterrupt while a critical code section has set the flag to True. Because signal handling is always done on the main thread, this class is not thread-safe since there is no need. rNcd|_dS)zWhen this flag has a positive value, it is considered set. When it is 0, it is not set. It should never go below 0. rN_ContextFlag__countr6s rr3zContextFlag.__init__ts  rc|jdkS)zIDefine the truth value of an object when it is used in a boolean context.rrFr6s r__bool__zContextFlag.__bool__{s|arc&|xjdz c_dS)zTWhen a with block is entered, the __enter__ method of the context manager is called.r NrFr6s r __enter__zContextFlag.__enter__s  rargscZ|xjdzc_|jdkrtddS)zqWhen the execution flow exits a with statement block this is called, regardless of whether an exception occurred.r rzcount has gone below 0N)rGr)r2rLs r__exit__zContextFlag.__exit__s6  r r. __objclass__N)r functoolspartialget_defining_classrYr]r^ isbuiltinhasattrrcgetmrordrArr5 isfunction getmodulerCrzrsplitrEr )raclss rririsV$ )**-!$),,,/$/$+D*$=$=/BI$-YdBeBe/>$-"9::  C} ,, -tZ..$g'--t/@/F/F{TU/V/VWX/Y/`/`adfg/h/hij/kll c4  J gdND99 : ::rceZdZdZdZdZdZdS)CompletionModezIEnum for what type of tab completion to perform in cmd2.Cmd.read_input().r rN)rArBrCrDNONECOMMANDSCUSTOMr.rrrrrrs)SS D H FFFrrrc6eZdZdZdddejdeddfdZdS) CustomCompletionSettingszQUsed by cmd2.Cmd.complete() to tab complete strings other than command arguments.F)preserve_quotesparserryrNc"||_||_dS)arCustomCompletionSettings initializer. :param parser: arg parser defining format of string being tab completed :param preserve_quotes: if True, then quoted tokens will keep their quotes when processed by ArgparseCompleter. This is helpful in cases when you're tab completing flag-like tokens (e.g. -o, --option) and you don't want them to be treated as argparse flags when quoted. Set this to True if you plan on passing the string to argparse with the tokens still quoted. N)rzry)r2rzrys rr3z!CustomCompletionSettings.__init__s .r)rArBrCrDargparseArgumentParserrr3r.rrrxrxsT[[SX / / /x6 /D /]a / / / / / /rrxdoccd}d}|D]E}|}|dr|rn0|r|r|dz }||z }d}A|rnF|S)zpStrip annotations from a docstring leaving only the text description. :param doc: documentation string rF: T) splitlinesrWr!)r~cmd_desc found_firstdoc_line stripped_lines rstrip_doc_annotationsrs HKNN$$   ((   # #C ( (      !D   %HKK   E  Ors1s2cttd||td||S)zRatio from s1,s2 may be different to s2,s1. We keep the max. See https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.ratio N)maxrratio)rrs rsimilarity_functionrsE tR,,2244odBPR6S6S6Y6Y6[6[ \ \\rgffffff?requested_commandoptionssimilarity_function_to_usecd}t}|}|pt}|D]*}|||}||kr|}|}+|S)aGiven a requested command and an iterable of possible options returns the most similar (if any is similar). :param requested_command: The command entered by the user :param options: The list of available commands to search for the most similar :param similarity_function_to_use: An optional callable to use to compare commands :return: The most similar command or None if no one is similar N)MIN_SIMIL_TO_CONSIDERlowerr)rrrproposed_command best_similrequested_command_to_compareeachsimils rsuggest_similarr&st&J#4#:#:#<#< !;!R?R$$**4::<<9UVV   J#  rfunc_or_methodc tj|d}n"#t$r}td|d}~wwxYw|dd}tj|r|dd||fS)a[Use inspect.get_annotations() to extract type hints for parameters and return value. This is a thin convenience wrapper around inspect.get_annotations() that treats the return value annotation separately. :param func_or_method: Function or method to return the type hints for :return: tuple with first element being dictionary mapping param names to type hints and second element being the return type hint or None if there is no return value type hint :raises ValueError: if the `func_or_method` argument is not a valid object to pass to `inspect.get_annotations` T)eval_strz;Argument passed to get_types should be a function or methodNrr2)r]get_annotationsrrpopr^)r type_hintsexcret_anns r get_typesr<sa,^dKKK aaaVWW]``annXt,,G''%vt$$$ w s 838r)LrDr|r>rgrr]rrSry subprocessrrcollections.abcrrdifflibrenumrtypingrrr r r r rrrrlargparse_customrrcmd2PopenrrArrrrr_r0rfrorrrtr{r}rrrrrF_OKrrrrrr rDrPr`rErirrrxrfloatrrrtuplerbrr.rrrs    $#####  #KKK"3'KK"K WT]]*]?]?]?]?]?]?]?]?@CD2"T"X"$r("""" 2HSM 2d3i 2 2 2 2 'c 'cCi ' ' ' '`C`DsO```` 2x} 2c 2 2 2 2($s)(d3i(D(((( 'DI '$s) 'PT ' ' ' 'ss*3$s)33333S4Z@9; Y YS Y# YDI Y Y Y YAC  tCy # DQTI     #$s)<^0^0^0^0^0^0^0^0B........8c*c*c*c*c*c*c*c*L77777777<33333333:BXc3h'(8CH3E*FFBRUBZ^BBBB>;Xc3h/;DI4D;;;;2T$////////"ss2]C]S]U]]]]vz%-c]PXZ]_bYcejYjPknrPr4Z,hsCx0U4S>3;N5Or