
    X                        S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKrSSKJr  SSKJ r   SSKJ!r!   " S S\RD                  5      r" " S S\"5      r# " S S\"5      r$ " S S\"5      r%\RL                  " 5       RO                  5       S   r(\RR                  " SSS\(S:  a  \(OSS9r*S r+\RX                  S 5       r-S r.S  r/SFS! jr0SGS" jr1S# r2S$ r3   SHS& jr4S' r5S( r6SIS) jr7SJS* jr8S+ r9S, r:SKS- jr;S.r<   SLS/ jr= SMS0 jr>S1 r?S2 r@\R                  S3S%S%S4S4 jrBS5 rCS6 rD " S7 S8\E5      rF " S9 S:\E5      rG " S; S<\E5      rH " S= S>\E5      rISNS? jrJ " S@ SA\E5      rKSB rL " SC SD\R                  5      rN   SOSE jrOg)Pz9General console printing utilities used by the Cloud SDK.    )absolute_import)division)unicode_literalsN)
exceptions)log)
properties)console_attr)console_pager)prompt_completer)encoding)files)	platformsinput)map)rangec                       \ rS rSrSrSrg)Error3   zBase exception for the module. N)__name__
__module____qualname____firstlineno____doc____static_attributes__r       -lib/googlecloudsdk/core/console/console_io.pyr   r   3   s    &r   r   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )RequiredPromptError8   zEAn exception for when a prompt cannot silenced with the --quiet flag.c                 ,   > [         [        U ]  S5        g )NzThis prompt could not be answered because you are not in an interactive session.  Please re-run the command without the --quiet flag to respond to the prompts.)superr    __init__self	__class__s    r   r$   RequiredPromptError.__init__;   s    	
t-	*+r   r   r   r   r   r   r   r$   r   __classcell__r'   s   @r   r    r    8   s    M+ +r   r    c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )UnattendedPromptErrorB   2An exception for when a prompt cannot be answered.c                 ,   > [         [        U ]  S5        g )NzThis prompt could not be answered because you are not in an interactive session.  You can re-run the command with the --quiet flag to accept default answers for all prompts.)r#   r-   r$   r%   s    r   r$   UnattendedPromptError.__init__E   s    	
/	:;r   r   r)   r+   s   @r   r-   r-   B   s    :; ;r   r-   c                   4   ^  \ rS rSrSrSrSU 4S jjrSrU =r$ )OperationCancelledErrorL   r/   zAborted by user.c                 R   > [         [        U ]  U=(       d    U R                  5        g N)r#   r3   r$   DEFAULT_MESSAGE)r&   messager'   s     r   r$    OperationCancelledError.__init__Q   s!    	
!41'4'')r   r   r6   )	r   r   r   r   r   r7   r$   r   r*   r+   s   @r   r3   r3   L   s    :&/) )r   r3   FP   )replace_whitespacedrop_whitespacebreak_on_hyphenswidthc                     SR                  U R                  5        Vs/ s H  n[        R                  U5      PM     sn5      $ s  snf )zText wrap the given message and correctly handle newlines in the middle.

Args:
  message: str, The message to wrap.  It may have newlines in the middle of
    it.

Returns:
  str, The wrapped message.

)join
splitlinesTEXTWRAPfill)r8   lines     r   _DoWraprF   `   s9     
G4F4F4HI4HDHMM$'4HI	JJIs   Ac              #      #    [         =R                  U -  sl        [         v   [         =R                  U -  sl        g7f)z'Temporarily narrows the global wrapper.N)rC   r>   )	narrow_bys    r   _NarrowWraprI   m   s(      ..I..
..I.s   <>c                  8     [        5       $ ! [         a     g f = fr6   )r   EOFErrorr   r   r   	_GetInputrL   u   s     7N	 s   	 
c                     U S:X  a	  [        US9$ U(       a  [        R                  " U 5      $ [        R                  " U 5      $ )a  Returns the contents of the specified file or stdin if path is '-'.

Args:
  path: str, The path of the file to read.
  binary: bool, True to open the file in binary mode.

Raises:
  Error: If the file cannot be read or is larger than max_bytes.

Returns:
  The contents of the file.
-)binary)	ReadStdinr   ReadBinaryFileContentsReadFileContents)pathrO   s     r   ReadFromFileOrStdinrT   |   s;     
S[F##''--				%%r   c                     U (       a  [         R                  " 5       $ [        R                  R	                  5       n[
        R                  (       a  [        R                  " U5      nU$ )a  Reads data from stdin, correctly accounting for encoding.

Anything that needs to read sys.stdin must go through this method.

Args:
  binary: bool, True to read raw bytes, False to read text.

Returns:
  A text string if binary is False, otherwise a byte string.
)	r   ReadStdinBytessysstdinreadsixPY2r	   Decode)rO   datas     r   rP   rP      sB     !!99>>D
ww  &dKr   c                     [         R                  R                  5       (       d  gU (       a$  [         R                  R                  5       (       d  gU(       a$  [         R                  R                  5       (       d  gU(       a_  [        R                  " [        R                  S5      n[        R                  " [        R                  S5      nU(       d  U(       a  US:X  a  gg! [
         a     gf = f)a  Determines if the current terminal session is interactive.

sys.stdin must be a terminal input stream.

Args:
  output: If True then sys.stdout must also be a terminal output stream.
  error: If True then sys.stderr must also be a terminal output stream.
  heuristic: If True then we also do some additional heuristics to check if
             we are in an interactive context. Checking home path for example.

Returns:
  True if the current terminal session is interactive.
FHOMEHOMEPATH/T)
rW   rX   isattystdoutstderrAttributeErrorr   GetEncodedValueosenviron)outputerror	heuristichomehomepaths        r   IsInteractivern      s    	99cjj''))SZZ&&((
  ##BJJ7D''

J?HTTS[	' 
 s   #C# *C# *C# #
C0/C0c                      [         R                  R                  5       [         R                  R                  :w  a-  [        R
                  " 5       [        R                  " 5       :X  a  gg)z<Check if command is being run from command line or a script.TF)r   OperatingSystemCurrentWINDOWSrg   getppidgetpgrpr   r   r   IsRunFromShellScriptru      sA     &&(I,E,E,M,MM	zz|rzz|#	r   c                      [        SS9=(       a7    [        R                  R                  R                  R                  5       (       + $ )zReturns true if we can prompt the user for information.

This combines all checks (IsInteractive(), disable_prompts is False) to
verify that we can prompt the user for information.

Returns:
  bool, True if we can prompt the user for information.
Trj   )rn   r   VALUEScoredisable_promptsGetBoolr   r   r   	CanPromptr|      s8     d
# ?$$44<<>
>@r   Tc           	        ^^ [         R                  R                  R                  R	                  5       (       a  T(       d  U(       a
  [        5       eT$ [         R                  R                  R                  R                  5       nU[         R                  R                  R                  R                  R                  :X  a  [        O[        nU" XTTUUS9u  pn
[        R                  R                  U5        UU4S jn U" U	5      nU
(       a  [        R                  R                  U
5        U(       d  U(       a  [        U5      eU$ ! U
(       a   [        R                  R                  U
5        f f = f)aV  Prompts the user a yes or no question and asks if they want to continue.

Args:
  message: str, The prompt to print before the question.
  prompt_string: str, An alternate yes/no prompt to display.  If None, it
    defaults to 'Do you want to continue'.
  default: bool, What the default answer should be.  True for yes, False for
    no.
  throw_if_unattended: bool, If True, this will throw if there was nothing
    to consume on stdin and stdin is not a tty.
  cancel_on_no: bool, If True and the user answers no, throw an exception to
    cancel the entire operation.  Useful if you know you don't want to
    continue doing anything and don't want to have to raise your own
    exception.
  cancel_string: str, An alternate error to display on No. If None, it
    defaults to 'Aborted by user.'.

Raises:
  UnattendedPromptError: If there is no input to consume and this is not
    running in an interactive terminal.
  OperationCancelledError: If the user answers no and cancel_on_no is True.

Returns:
  bool, False if the user said no, True if the user said anything else or if
  prompts are disabled.
r8   prompt_stringdefaultthrow_if_unattendedcancel_on_nocancel_stringc                 P  >  [        5       nUS:X  a  T$ Uc"  T(       a  [        5       (       d
  [        5       eT$ UR                  5       R	                  5       S;   a  gUR                  5       R	                  5       S;   a  gU (       a  [
        R                  R                  U 5        M  )zGet answer to input prompt.T )yyes)nnoF)rL   rn   r-   striplowerrW   rd   write)repromptanswerr   r   s     r   	GetAnswer!PromptContinue.<locals>.GetAnswer  s    
{f 
2>}%'
'.<<>!\1<<>![0

"% r   )r   rx   ry   rz   r{   r3   interactive_ux_styleGetInteractiveUXStylesTESTINGname"_TestPromptContinuePromptGenerator$_NormalPromptContinuePromptGeneratorrW   rd   r   )r8   r   r   r   r   r   styleprompt_generatorpromptr   endingr   r   s     ``         r   PromptContinuer      s   : ++3355|#%%N



 
 
5
5
9
9
;% 
*##((<<DDII	I )/ 
 .G-L!#&F **6#,x F	jjv	L
!-
00	- 	jjv s   E )E4c                 
   AAA[         R                  " 5       nU (       a  UR                  [        U 5      S-   5        U(       d  SnU(       a  US-  nOUS-  nUR                  [        U5      5        UR	                  5       SS4$ )z>Generates prompts for prompt continue under normal conditions.z

zDo you want to continuez	 (Y/n)?  z	 (y/N)?  zPlease enter 'y' or 'n':  r@   )ioStringIOr   rF   getvalue)r8   r   r   r   r   r   bufs          r   r   r   5  su     
#IIgg'(	-M[ M[ M))GM"#
,,.6	==r   c                 F    AAA[        [        R                  U XS9S-   SS4$ )z1Generates prompts for prompt continue under test.)r8   r   r   r@   N)
JsonUXStubUXElementTypePROMPT_CONTINUEr~   s         r   r   r   L  s>     
##W!@BFG 
 r   c                    [         R                  R                  R                  R	                  5       (       a  gU(       a0  [        SS9(       a"  [        R                  " XS9R                  5       $ [         R                  R                  R                  R                  5       [         R                  R                  R                  R                  R                  :X  a?  [        R                  R!                  [#        [$        R&                  U S95        [+        5       $ [        R                  R!                  [)        U 5      5        [+        5       $ )a-  Prompts the user for a string.

Args:
  message: str, The prompt to print before the question.
  choices: callable or list, A callable with no arguments that returns the
    list of all choices, or the list of choices.

Returns:
  str, The string entered by the user, or None if prompts are disabled.
NTrw   choicesr8   )r   rx   ry   rz   r{   rn   r   PromptCompleterInputr   r   r   r   r   rW   rd   r   r   r   PROMPT_RESPONSErF   rL   )r8   r   s     r   PromptResponser   Y  s     ++3355T*++GEKKMM115570088==>JJZ = =wOP 
 JJWW%&	r   c                     U =(       d    Sn U(       a  U (       a  U S-  n U SR                  US9-  n OU S-  n [        XS9=(       d    U$ )a  Prompts the user for a string, allowing a default.

Unlike PromptResponse, this also appends a ':  ' to the prompt.  If 'default'
is specified, the default is also written written into the prompt (e.g.
if message is "message" and default is "default", the prompt would be
"message (default): ").

The default is returned if the user simply presses enter (no input) or an
EOF is received.

Args:
  message: str, The prompt to print before the question.
  default: str, The default value (if any).
  choices: callable or list, A callable with no arguments that returns the
    list of all choices, or the list of choices.

Returns:
  str, The string entered by the user, or the default if no value was
  entered or prompts are disabled.
r    z({default}):  r   :  r   )formatr   )r8   r   r   s      r   PromptWithDefaultr   p  sO    * Mr'ng&&w&77GuG		1	<W<r   c                      [        U 5      $ ! [         a     Of = fU(       d  g [        [        [        U5      5      R                  U 5      S-   $ ! [         a     gf = f)a  Parses answer and returns 1-based index in options list.

Args:
  answer: str, The answer input by the user to be parsed as a choice.
  options: [object], A list of objects to select.  Their str()
        method will be used to select them via freeform text.
  allow_freeform: bool, A flag which, if defined, will allow the user to input
        the choice as a str, not just as a number. If not set, only numbers
        will be accepted.

Returns:
  int, The 1-indexed value in the options list that corresponds to the answer
        that was given, or None if the selection is invalid. Note that this
        function does not do any validation that the value is a valid index
        (in the case that an integer answer was given)
N   )int
ValueErrorlistr   strindex)r   optionsallow_freeforms      r   _ParseAnswerr     si    "	v;	 		 
	C!"((0144	 	 
	s   
 
*A 
AAc                 b    U R                  [        [        U5      5        U R                  U5      $ )a&  Checks if there is a suitable close choice to suggest.

Args:
  suggester: object, An object which has methods AddChoices and
    GetSuggestion which is used to detect if an answer which is not present
    in the options list is a likely typo, and to provide a suggestion
    accordingly.
  answer: str, The freeform answer input by the user as a choice.
  options: [object], A list of objects to select.  Their str()
        method will be used to compare them to answer.

Returns:
  str, the closest option in options to answer, or None otherwise.
)
AddChoicesr   r   GetSuggestion)	suggesterr   r   s      r   _SuggestFreeformAnswerr     s*     s3()		 	 	((r   c           	          Uc  U OU SU n[        U5       H2  u  pEU" SR                  US-   [        R                  " U5      S95        M4     g)a<  Prints the options provided to stderr.

Args:
  options:  [object], A list of objects to print as choices.  Their str()
    method will be used to display them.
  write: f(x)->None, A function to call to write the data.
  limit: int, If set, will only print the first number of options equal
    to the given limit.
Nz [{index}] {option}
r   )r   option)	enumerater   rZ   	text_type)r   r   limitlimited_optionsir   s         r   _PrintOptionsr     sS      %}G'&5//_-ia	
!
(
(!eCMM&1 ) 3 4 .r   2   c                 h  ^^^ U (       d  [        S5      eU(       a  U S/-   OU n [        U 5      nUb'  SUs=::  a  U:  d  O  [        SR                  XS95      e[        R                  R
                  R                  R                  5       (       a  U$ [        R                  R
                  R                  R                  5       nU[        R                  R
                  R                  R                  R                  :X  ac  S m[        R                  R                  [!        ["        R$                  UTU  V	s/ s H  n	[&        R(                  " U	5      PM     sn	S9S-   5        O[        R                  R                  mU(       a  T" [+        U5      S-   5        U[,        :  aC  [/        U T[,        S	9  U[,        -
  n
T" S
R                  U
S95        T" SR                  US95        O[/        U T5        T(       d  U(       a  SmOSmUc  SmOSR                  US-   S9mUUU4S jnU" 5          [1        5       nUb
  U(       d&  Ub#  T" S5        U(       a  XS-
  :X  a
  [3        5       eU$ US:X  a  [/        U T5        U" 5         MV  [5        XU5      nU(       a  X:X  a
  [3        5       eUb  US:  a  X::  a  T" S5        US-
  $ U(       a4  U(       a-  [7        UUU 5      nUb  T" SR                  XS95        T" S5        U(       a  T" SR                  US95        OT" SR                  US95        GM  s  sn	f )a7  Prompt the user to select a choice from a list of items.

Args:
  options:  [object], A list of objects to print as choices.  Their
    six.text_type() method will be used to display them.
  default: int, The default index to return if prompting is disabled or if
    they do not enter a choice.
  message: str, An optional message to print before the choices are displayed.
  prompt_string: str, A string to print when prompting the user to enter a
    choice.  If not given, a default prompt is used.
  allow_freeform: bool, A flag which, if defined, will allow the user to input
    the choice as a str, not just as a number. If not set, only numbers will
    be accepted.
  freeform_suggester: object, An object which has methods AddChoices and
    GetSuggestion which is used to detect if an answer which is not present
    in the options list is a likely typo, and to provide a suggestion
    accordingly.
  cancel_option: bool, A flag indicating whether an option to cancel the
    operation should be added to the end of the list of choices.

Raises:
  ValueError: If no options are given or if the default is not in the range of
    available options.
  OperationCancelledError: If a `cancel` option is selected by user.

Returns:
  The index of the item in the list that was chosen, or the default if prompts
  are disabled.
z%You must provide at least one option.cancelr   z^Default option [{default}] is not a valid index for the options list [{maximum} options given])r   maximumc                     g r6   r   xs    r   <lambda>PromptChoice.<locals>.<lambda>      dr   )r8   r   r   r@   )r   z%Did not print [{truncated}] options.
)	truncatedzMToo many options [{maximum}]. Enter "list" at prompt to print choices fully.
)r   zHPlease enter numeric choice or text value (must exactly match list item)z Please enter your numeric choicer   z ({default}):  r   r   c                  .   > T" [        T T-   5      5        g r6   )rF   )r   suffix_stringr   s   r   _PrintPrompt"PromptChoice.<locals>._PrintPrompt+  s    	'--/
01r   r   z4[{answer}] not in list. Did you mean [{suggestion}]?)r   
suggestionzOPlease enter a value between 1 and {maximum}, or a value present in the list:  z/Please enter a value between 1 and {maximum}:  )r   lenr   r   rx   ry   rz   r{   r   r   r   r   r   rW   rd   r   r   r   PROMPT_CHOICErZ   r   rF   PROMPT_OPTIONS_OVERFLOWr   rL   r3   r   r   )r   r   r8   r   r   freeform_suggestercancel_optionr   r   or   r   r   
num_choicer   r   r   s      `           @@r   PromptChoicer     s   @ 

<
==$1Gxj w'L'g!7!7
	$$*F7F$LN N ++3355N



 
 
5
5
9
9
;%
j$$88@@EEEEJJZ##W#+237aq!735 8<< =
 JJE	''
T
!"&&'5(?@11I	
2
9
9I
9
NO	 #VGV46 '5!	+m 9m_M%,,Wq[,AM2.[F~f)<
 Dk	7k1%''nGU#nf~>J.#%%*/j6KDk!^ ,)*<*0*13j 
	DvVv;	=d #VGV46 =VGV$&K 	? 4s   7 L/c           
         [         R                  R                  R                  R	                  5       (       a  g[         R                  R                  R
                  R                  5       nU[         R                  R                  R                  R                  R                  :X  a>  S n[        R                  R                  [        [        R                  UX#US9S-   5        O[        R                  R                  nU(       a  U" [!        U5      S-   5         U" [!        U5      5        [#        5       nU " U5      (       a  U$ U" [!        U5      S-   5        U(       a  [%        SS9(       a  U$ MW  )a  Prompts the user for a string that must pass a validator.

Args:
  validator: function, A validation function that accepts a string and returns
    a boolean value indicating whether or not the user input is valid.
  error_message: str, Error message to display when user input does not pass
    in a valid string.
  prompt_string: str, A string to print when prompting the user to enter a
    choice.  If not given, a default prompt is used.
  message: str, An optional message to print before prompting.
  allow_invalid: bool, Allow returning the answer if validation fails.

Returns:
  str, The string entered by the user, or the default if no value was
  entered or prompts are disabled.
Nc                     g r6   r   r   s    r   r   %PromptWithValidator.<locals>.<lambda>p  r   r   )error_messager   r8   allow_invalidr@   Fr   )r   rx   ry   rz   r{   r   r   r   r   r   rW   rd   r   r   r   PROMPT_WITH_VALIDATORrF   rL   r   )	validatorr   r   r8   r   r   r   r   s           r   PromptWithValidatorr   X  s   $ ++3355 


 
 
5
5
9
9
;%
j$$88@@EEEEJJZ++=##% (,, -
 JJE	''
T
!"	'-
 ![FmGM"T)*	>%8 	r   c                 >   ^ U4S jn[         R                  " SX 5      $ )a{  Expands {key} => value for key, value in kwargs.

Details:
  * {{<identifier>}} expands to {<identifier>}
  * {<unknown-key>} expands to {<unknown-key>}
  * {key} values are recursively expanded before substitution into the result

Args:
  s: str, The string to format.
  **kwargs: {str:str}, A dict of strings for named parameters.

Returns:
  str, The lazily-formatted string.
c                 <  > U R                  S5      SS nU R                  S5      nU R                  S5      SS nU(       a  U(       a  X-   U-   $ TR                  U5      nUc  U R                  S5      $ [        U5      (       a  U" 5       nU[        U40 TD6-   U-   $ )z7Returns one replacement string for LazyFormat re.sub().r   N      r   )groupgetcallable
LazyFormat)matchprefixr   suffixvaluekwargss        r   _Replacement LazyFormat.<locals>._Replacement  s    [[^ABF;;q>D[[^ABF&]V##JJtE}[[^geJu///&88r   z(\{+)(\w+)(\}+))resub)sr   r   s    ` r   r   r     s     9" 
"L	44r   c                    [        S5       nSnUn[        R                  R                  R                  R                  5       nU(       a  SnSnX2R                  UR                  U 5      5      -   S-   sSSS5        $ ! , (       d  f       g= f)a  Formats an action a user must initiate to complete a command.

Some actions can't be prompted or initiated by gcloud itself, but they must
be completed to accomplish the task requested of gcloud; the canonical example
is that after installation or update, the user must restart their shell for
all aspects of the update to take effect. Unlike most console output, such
instructions need to be highlighted in some way. Using this function ensures
that all such instances are highlighted the *same* way.

Args:
  s: str, The message to format. It shouldn't begin or end with newlines.

Returns:
  str, The formatted message. This should be printed starting on its own
    line, and followed by a newline.
   z
==> z
 r@   N)rI   r   rx   accessibilityscreen_readerr{   rA   wrap)r   wrapper	separatorr   r   s        r   FormatRequiredUserActionr    sj    " 1~IF%%33AAIIKMifNN7<<?33d: ~~s   A&A<<
B
<   c                 ,   [         R                  R                  R                  R	                  5       nU[         R                  R                  R
                  R                  R                  :X  a
  [        5       $ U[         R                  R                  R
                  R                  R                  :X  a  [        X5      $ U(       d7  [         R                  R                  R                  R                  5       (       a  [        X5      $ [        XX#U5      $ )a  A simple progress bar for tracking completion of an action.

This progress bar works without having to use any control characters.  It
prints the action that is being done, and then fills a progress bar below it.
You should not print anything else on the output stream during this time as it
will cause the progress bar to break on lines.

Progress bars can be stacked into a group. first=True marks the first bar in
the group and last=True marks the last bar in the group. The default assumes
a singleton bar with first=True and last=True.

This class can also be used in a context manager.

Args:
  label: str, The action that is being performed.
  stream: The output stream to write to, stderr by default.
  total_ticks: int, The number of ticks wide to make the progress bar.
  first: bool, True if this is the first bar in a stacked group.
  last: bool, True if this is the last bar in a stacked group.
  screen_reader: bool, override for screen reader accessibility property
    toggle.

Returns:
  The progress bar.
)r   rx   ry   r   r   r   OFFr   NoOpProgressBarr   _StubProgressBarr   r   r{   _TextPercentageProgressBar_NormalProgressBar)labelstreamtotal_ticksfirstlastr   r   s          r   ProgressBarr    s    6 


 
 
5
5
9
9
;%
j$$88<<AAA
!!&&::BBGGGE**
))77EEMMOO%e44e[FFr   c                   ^  T b
  T [         :X  a2  [        [        [        U5      5       Vs/ s H	  n[         PM     sn5      $ U 4S jn[	        U5      n/ nSnU H"  nXt-  nUR                  U" Xh5      5        Xh-  nM$     [        U5      $ s  snf )a  Splits a progress bar into logical sections.

Wraps the original callback so that each of the subsections can use the full
range of 0 to 1 to indicate its progress.  The overall progress bar will
display total progress based on the weights of the tasks.

Args:
  original_callback: f(float), The original callback for the progress bar.
  weights: [float], The weights of the tasks to create.  These can be any
    numbers you want and the split will be based on their proportions to
    each other.

Raises:
  ValueError: If the weights don't add up to 1.

Returns:
  (f(float), ), A tuple of callback functions, in order, for the subtasks.
c                    >^ ^ U UU4S jnU$ )Nc                 "   > T" TU T-  -   5        g r6   r   )done_fractionalready_doneoriginal_callbackweights    r   Callback8SplitProgressBar.<locals>.MakeCallback.<locals>.Callback  s    (>?@r   r   )r  r  r  r  s   `` r   MakeCallback&SplitProgressBar.<locals>.MakeCallback  s    AOr   r   )DefaultProgressBarCallbacktupler   r   sumappend)	r  weights_r  total	callbacksr  r  normalized_weights	   `        r   SplitProgressBarr&    s    & 55eCL6IJ6I,6IJKK
 g,%),f\,BC%L 
 
y	 Ks   B	c                     A g r6   r   )progress_factors    r   r  r    s    r   c                   B    \ rS rSrSrS rS rS rS rS r	S r
S	 rS
rg)r  i  aP  A simple progress bar for tracking completion of an action.

This progress bar works without having to use any control characters.  It
prints the action that is being done, and then fills a progress bar below it.
You should not print anything else on the output stream during this time as it
will cause the progress bar to break on lines.

Progress bars can be stacked into a group. first=True marks the first bar in
the group and last=True marks the last bar in the group. The default assumes
a singleton bar with first=True and last=True.

This class can also be used in a context manager.
c                 D   Xl         X l        SU l        X0l        X@l        XPl        [        R                  " 5       nUR                  5       U l	        U R                  R                  U R                  R                  :g  =(       d-    U R                  R                  U R                  R                  :g  U l        U R                  (       a  [        SS9(       d  SU l        SU l        U R                  S-
  n[!        U5      U:  a  USUS-
   S-   nO%[!        U5      U:  a  U[!        U5      -
  nUSU-  -  nU R                  R                  U R                  R"                  -   n	U R                  R"                  U R                  R                  -   n
S	R%                  XU
S
9U l        g)ai  Creates a progress bar for the given action.

Args:
  label: str, The action that is being performed.
  stream: The output stream to write to, stderr by default.
  total_ticks: int, The number of ticks wide to make the progress bar.
  first: bool, True if this is the first bar in a stacked group.
  last: bool, True if this is the last bar in a stacked group.
r   Trw   r   Nr   z...r   z{left} {label} {right})leftr  right)
_raw_label_stream_ticks_written_total_ticks_first_lastr	   ConsoleAttrGetBoxLineCharacters_boxd_drd_vrd_dld_vl_redrawrn   r   d_hr   _label)r&   r  r  r  r  r  attrmax_label_widthdiffr+  r,  s              r   r$   _NormalProgressBar.__init__%  sI    OLD#KJ##%D))+DIIINNdiinn4 5IINNdiinn4 	L ||M5dkdj''!+O
5zO#(_q()E1e	Uo	%s5z)dsTze99>>DIIMM)DIIMMDIINN*E*11e 2 -DKr   c                 T   U R                   (       d  U R                  (       a  U R                   (       a  U R                  R                  OU R                  R                  nU R                   (       a  U R                  R
                  OU R                  R                  nSR                  XR                  R                  U R                  -  US9nU R                  U5        U R                  U R                  S-   5        U R                  U R                  R                  5        SU l        g)z:Starts the progress bar by writing the top rule and label.z{left}{middle}{right}
)r+  middler,  r@   r   N)r1  r:  r5  r6  r7  r8  r9  r   r;  r0  _Writer<  d_urr/  )r&   r+  r,  rules       r   Start_NormalProgressBar.StartM  s    {{dll#{{TYY^^		d $diinne&--IIMMD,=,==U . Ld
kk$KKd"#KK		Dr   c                 
   [        U R                  U-  5      nX R                  -
  n[        X0R                  U R                  -
  5      nUS:  a  U R	                  U R
                  R                  U-  5        U =R                  U-  sl        X R                  :X  aN  U R                  (       d  U R                  (       d  SOSnU R	                  U R
                  R                  U-   5        U R                  R                  5         gg)a  Sets the current progress of the task.

This method has no effect if the progress bar has already progressed past
the progress you call it with (since the progress bar cannot back up).

Args:
  progress_factor: float, The current progress as a float between 0 and 1.
r   r@   N)r   r0  r/  minrC  r5  r;  r2  r:  d_ulr.  flush)r&   r(  expected_ticks	new_ticksends        r   SetProgress_NormalProgressBar.SetProgressY  s     **_<=N!4!44II0043F3FFGI1}
kk$))--)+,
Y&	,,	,jjd$DIINNS()
ll r   c                 &    U R                  S5        gMark the progress as done.r   NrP  r&   s    r   Finish_NormalProgressBar.Finisho      Qr   c                 :    U R                   R                  U5        g r6   r.  r   r&   msgs     r   rC  _NormalProgressBar._Writes  s    LLsr   c                 &    U R                  5         U $ r6   rF  rV  s    r   	__enter___NormalProgressBar.__enter__v      JJLKr   c                 $    U R                  5         g r6   rW  r&   argss     r   __exit___NormalProgressBar.__exit__z      KKMr   )	r5  r1  r<  r2  r-  r:  r.  r/  r0  Nr   r   r   r   r   r$   rF  rP  rW  rC  ra  rh  r   r   r   r   r  r    s+    &-P
,r   r  c                   F    \ rS rSrSrSS jrS rS rS rS r	S r
S	 rS
rg)r
  i~  +A progress bar that outputs nothing at all.c                 >    Xl         X l        SU l        US-  U l        g)zCreates a progress bar for the given action.

Args:
  label: str, The action that is being performed.
  stream: The output stream to write to, stderr by default.
  percentage_display_increments: Minimum change in percetnage to display new
    progress
r         Y@N)r<  r.  _last_percentage_percentage_display_increments)r&   r  r  percentage_display_incrementss       r   r$   #_TextPercentageProgressBar.__init__  s#     KLD*G%*OD'r   c                 :    U R                  U R                  5        g r6   )rC  r<  rV  s    r   rF   _TextPercentageProgressBar.Start  s    KKr   c                     [        US5      nUU R                  U R                  -   :  nU(       d  US:X  a*  U R                  SR	                  US-  5      5        Xl        g g )Ng      ?z{0:.0f}%ro  )rJ  rp  rq  rC  r   )r&   r(  should_update_progresss      r   rP  &_TextPercentageProgressBar.SetProgress  sc    /3/O C CC	D  	/S"8
kk*##Oe$;<=- #9r   c                 &    U R                  S5        grS  rU  rV  s    r   rW  !_TextPercentageProgressBar.Finish  rY  r   c                 @    U R                   R                  US-   5        g )Nr@   r[  r\  s     r   rC  !_TextPercentageProgressBar._Write  s    LLsTz"r   c                 &    U R                  5         U $ r6   r`  rV  s    r   ra  $_TextPercentageProgressBar.__enter__  rc  r   c                 $    U R                  5         g r6   re  rf  s     r   rh  #_TextPercentageProgressBar.__exit__  rj  r   )r<  rp  rq  r.  N)g      @rk  r   r   r   r
  r
  ~  s)    3P.#r   r
  c                   <    \ rS rSrSrS rS rS rS rS r	S r
S	rg
)r  i  rm  c                     g r6   r   rV  s    r   r$   NoOpProgressBar.__init__      r   c                     g r6   r   rV  s    r   rF  NoOpProgressBar.Start  r  r   c                     g r6   r   r&   r(  s     r   rP  NoOpProgressBar.SetProgress  r  r   c                 &    U R                  S5        grS  rU  rV  s    r   rW  NoOpProgressBar.Finish  rY  r   c                 &    U R                  5         U $ r6   r`  rV  s    r   ra  NoOpProgressBar.__enter__  rc  r   c                 $    U R                  5         g r6   re  rf  s     r   rh  NoOpProgressBar.__exit__  rj  r   r   Nr   r   r   r   r   r$   rF  rP  rW  ra  rh  r   r   r   r   r  r    s#    3			r   r  c                   <    \ rS rSrSrS rS rS rS rS r	S r
S	rg
)r	  i  zA progress bar that only prints deterministic start and end points.

No UX about progress should be exposed here. This is strictly for being able
to tell that the progress bar was invoked, not what it actually looks like.
c                     Xl         X l        g r6   r-  r.  )r&   r  r  s      r   r$   _StubProgressBar.__init__  s    OLr   c                 z    U R                   R                  [        [        R                  U R
                  S95        g )Nr   )r.  r   r   r   PROGRESS_BARr-  rV  s    r   rF  _StubProgressBar.Start  s)    LL=--tGIr   c                     g r6   r   r  s     r   rP  _StubProgressBar.SetProgress  r  r   c                 \    U R                  S5        U R                  R                  S5        g)rT  r   r@   N)rP  r.  r   rV  s    r   rW  _StubProgressBar.Finish  s"    QLLtr   c                 &    U R                  5         U $ r6   r`  rV  s    r   ra  _StubProgressBar.__enter__  rc  r   c                 $    U R                  5         g r6   re  rf  s     r   rh  _StubProgressBar.__exit__  rj  r   r  Nr  r   r   r   r	  r	    s&    I	
r   r	  c                    [        SS9(       d)  U(       d  [        R                  nUR                  U 5        gU(       d/  [        R                  R                  U 5        [        R                  nU(       Ga^  [        R                  " [        R                  SS5      nUS:X  a  SnO/U(       d(  S H"  n[        R                  " U5      (       d  M   Un  O   U(       a  [        R                  " [        R                  SS5      nSU=(       d    S	-   n[        R                  " [        R                  SU5        [        R                   " U[        R"                  SS
9n[$        R&                  " 5       R)                  5       n	UR+                  U R-                  U	5      S9  UR/                  5         Uc&  [        R                  " [        R                  SS5        g[0        R2                  " XU5      R5                  5         g)a  Run a user specified pager or fall back to the internal pager.

Args:
  contents: The entire contents of the text lines to page.
  out: The output stream, log.out (effectively) if None.
  prompt: The page break prompt.
  check_pager: Checks the PAGER env var and uses it if True.
T)ri   NPAGERrN   )lesspagerLESSz-Rr   )rX   shellr   )rn   r   outr   file_only_loggerinforW   rc   r   rf   rg   rh   r   FindExecutableOnPathSetEncodedValue
subprocessPopenPIPEr	   GetConsoleAttrGetEncodingcommunicateencodewaitr
   PagerRun)
contentsr  r   check_pagerr  command	less_origr  pencs
             r   Morer    s^    
d	#GGcIIh
	h'
**C$$RZZ$?E|e&'%%g..%
 '  **2::vtDiY_"%drzz648


5
t
Da'')557cmm(//#.m/ffh		  VT:hV,002r   c                   0    \ rS rSrSrS rS rS rS rSr	g)	TickableProgressBari  z;A thread safe progress bar with a discrete number of tasks.c                 r    SU l         Xl        [        U0 UD6U l        [        R
                  " 5       U l        g )Nr   )	completedr#  r  _progress_bar	threadingLock_lock)r&   r#  rg  r   s       r   r$   TickableProgressBar.__init__  s.    DNJ$d5f5D!DJr   c                 :    U R                   R                  5         U $ r6   )r  ra  rV  s    r   ra  TickableProgressBar.__enter__  s      "Kr   c                 <    U R                   R                  XU5        g r6   )r  rh  )r&   exc_type	exc_value	tracebacks       r   rh  TickableProgressBar.__exit__  s    Y?r   c                     U R                      U =R                  S-  sl        U R                  R                  U R                  U R                  -  5        S S S 5        g ! , (       d  f       g = f)Nr   )r  r  r  rP  r#  rV  s    r   TickTickableProgressBar.Tick   sB    	
nnn
$$T^^djj%@A 
s   AA
A,)r  r  r  r#  N)
r   r   r   r   r   r$   ra  rh  r  r   r   r   r   r  r    s    C"@Br   r  c                    [         R                  " 5       nU R                  US'   [        [	        U5      [	        U R                  5       5      -
  5      nU(       a%  [        SR                  U R                  U5      5      eU R                  5        H"  nUR                  US5      nU(       d  M  XRU'   M$     [        R                  " U5      $ )z/Generates a stub message for UX console output.uxz%Extraneous args for Ux Element {}: {}N)collectionsOrderedDictr   r   setGetDataFieldsr   r   r   jsondumps)ux_typer   ri   
extra_argsfieldvals         r   r   r   &  s    ""$&&,CK#g&;&;&=">>?*
<CCj" # #$$&e
**UD
!C
sUm ' 
F	r   c                   @    \ rS rSrSrSrSrSrSrSr	Sr
S	rS
 rS rSrg)r   i5  z#Describes the type of a ux element.)r   r8   )r   r8   aborted_messagestatus)r   r8   r  succeeded_stagesfailed_stage)r   r8   r   r   )r   r8   )   r8   r   r   )   r   r   r8   r   c                     AX l         g r6   _data_fields)r&   ordinaldata_fieldss      r   r$   UXElementType.__init__A  s     	#r   c                     U R                   $ )z@Returns the ordered list of additional fields in the UX Element.r  rV  s    r   r  UXElementType.GetDataFieldsH  s    r   r  N)r   r   r   r   r   r  PROGRESS_TRACKERSTAGED_PROGRESS_TRACKERr   r   r   r   r$   r  r   r   r   r   r   r   5  s:    +,@AD/"/<-,$r   r   c                    [         R                  R                  R                  R	                  5       (       a  g[
        R                  " U 5      n[        R                  " U5      n[        U5      (       a  UO[
        R                  n[        U5      (       a]  U" U5      (       dP  [        R                  R                  [        U5      S-   5        [        R                  " U5      nU" U5      (       d  MP  U" U5      $ )z2Prompt user for password with optional validation.Nr@   )r   rx   ry   rz   r{   rZ   
ensure_strgetpassr   rW   rd   r   rF   )r   r   validation_callableencoder_callable
str_promptpass_wdencoders          r   PromptPasswordr  M  s    
 ++3355~~f%*OOJ'' ()9 : :'!""!'**	jjw}-45
+g "'** 
	r   )F)FFF)NNTFFN)NN)NNNr6   )NNNFNF)NF)NNT)zInvalid PasswordNN)Pr   
__future__r   r   r   r  
contextlibenumr  r   r  rg   r   r  rW   textwrapr  googlecloudsdk.corer   r   r   googlecloudsdk.core.consoler	   r
   r   googlecloudsdk.core.utilr   r   r   rZ   	six.movesr   r   r   r   r    r-   r3   r  GetTermSize_CONSOLE_WIDTHTextWrapperrC   rF   contextmanagerrI   rL   rT   rP   rn   ru   r|   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r&  r  objectr  r
  r  r	  r  r  r   Enumr   r  r   r   r   <module>r     s    @ &  '     	  	 	  
   * # * 4 5 8 - * . 
   J 
+% +;E ;)e ) ,,.::<Q?*Q..B	8
K  &(*(V
@ >B;@!%L^>.
.=>$N)&4&   15498=v&t 5:+\!5H;6 "jjb#GL$Ne eP) )Xf 0v >,3^B& B,DII 2 "4'+$(r   