
    =                        d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlZddlm	Z	 ddl
mZ dd	l
mZ dd
l
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ  ddlm!Z! ddlm"Z# ddlm$Z$ ddlm%Z% ddlm&Z& ddlm'Z( ddlm)Z) ddlm*Z* ddlm+Z+ ddl,m-Z.  G d d e)j^                        Z0 G d! d"e.jb                        Z2d(d#Z3d$ Z4 G d% d&e5      Z6d)d'Z7y)*z#The gcloud interactive application.    )absolute_import)division)print_function)unicode_literalsN)cli_tree)bindings)bindings_vi)	completer)coshell)debug)layout)parser)style)generate_cli_trees)config)
properties)named_configs)application)auto_suggest)buffer)document)enums)filters)history)	interface)	shortcuts)token)
processorsc                   >     e Zd ZdZ	 	 	 d fd	ZddZd fd	Z xZS )CLIa  Extends the prompt CLI object to include our state.

  Attributes:
    command_count: Command line serial number, incremented on ctrl-c and Run.
    completer: The interactive completer object.
    config: The interactive shell config object.
    coshell: The shell coprocess object.
    debug: The debugging object.
    parser: The interactive parser object.
    root: The root of the static CLI tree that contains all commands, flags,
      positionals and help doc snippets.
  c
                     t         t        |   |||	       d| _        || _        || _        || _        || _        || _        || _	        y )N)r   	eventloopoutputr   )
superr    __init__command_countr
   r   r   r   r   root)selfr   r   r   r'   interactive_parserinteractive_completerr   r"   r#   	__class__s             9lib/googlecloudsdk/command_lib/interactive/application.pyr%   zCLI.__init__F   sV     
#t   D*DNDKDLDJ$DKDI    c                    |r| j                   j                          | j                  j                  |       |rH| j                   j                  dd       | j                   j	                          | j                          yy)a  Runs the command line in text, optionally in an alternate screen.

    This should use an alternate screen but I haven't found the incantations
    to get that working. Currently alternate_screen=True clears the default
    screen so full screen commands, like editors and man or help, have a clean
    slate. Otherwise they may overwrite previous output and end up with a
    garbled mess. The downside is that on return the default screen is
    clobbered. Not too bad right now because this is only used as a fallback
    when the real web browser is inaccessible (for example when running in ssh).

    Args:
      text: The command line string to run.
      alternate_screen: Send output to an alternate screen and restore the
        original screen when done.
    F)leave_alternate_screenerase_titleN)renderereraser   Run request_absolute_cursor_position_redraw)r(   textalternate_screens      r,   r3   zCLI.RunU   sa      
mmLLT
mmEJ
mm446
lln r-   c                     t         t        |   ||       dfd	}j                         r=j                  |k7  r-| j
                  |   _        j                  _        |_        yyy)z?MONKEYPATCH! Calls the async completer on delete before cursor.c                 L    j                  |       }j                          |S )N)count)patch_real_delete_before_cursorpatch_completer_function)r:   deletedbufs     r,   DeleteBeforeCursorz*CLI.add_buffer.<locals>.DeleteBeforeCursorr   s)    33%3@g 
""$nr-   N)   )r$   r    
add_buffercomplete_while_typingdelete_before_cursor_async_completersr<   r;   )r(   namer>   focusr?   r+   s     `  r,   rA   zCLI.add_buffern   sk    	#tc51 	!!#  $66%)%;%;D%Ac",/,D,Dc)!3c 	7 	$r-   )	NNNNNNNNN)F)__name__
__module____qualname____doc__r%   r3   rA   __classcell__)r+   s   @r,   r    r    8   s)     BF>B8<24 4r-   r    c                        e Zd ZdZed        Zy)Contextz"Input processor that adds context.c                       j                   sU|j                  sId _          j                  j                  t	        j
                   j                  j                               t        j                  | fd      S )NTc                 B    t        j                  j                        S N)lenr   context)iclis    r,   <lambda>z.Context.apply_transformation.<locals>.<lambda>   s    C

0B0B,Cr-   )display_to_source)
context_was_setr6   current_bufferset_documentr   Documentr   rR   	pt_layoutTransformation)rT   doclinenosource_to_displaytokenss   `    r,   apply_transformationzContext.apply_transformation   s^    sxx c	%%h&7&7

8J8J&KL##"CE Er-   N)rG   rH   rI   rJ   staticmethodra    r-   r,   rM   rM      s    *E Er-   rM   c                    |rXd}d}| D ]  }||dz  }|t        |      z  } |sg S |dkD  r||z
  |dz
  z  }|dk  rd}nd}||z
  ||dz
  z  z
  }|dkD  r
|dz  }nd}d}g }| D ]  }||j                  t        j                  j                  j
                  |f       |j                  t        j                  j                  j                  d|z  f       |dz  }|dk(  s~|dz  } |dd S )z3Returns labels as left- and right-justified tokens.r   Nr@       )rQ   appendr   TokenToolbarHelp	Separator)	labelswidthjustify
used_widthlabel_countlabelseparator_widthseparator_remainderr`   s	            r,   _GetJustifiedTokensru      s6   JK	QkCJj	  i	q+qAo	1	o 	
_a@@ Q o O&e}
MM5;;&&++U34
MM5;;&&00#2GHI1ao  
r-   c                    t        j                  ddddddddd	g
      }d|t        j                  <   || t        j                     d<   dD ]S  }t        j                  |      }d|t        j                  <   d|t        j
                  <   || t        j                     |<   U dD ]@  }t        j                  |      }d|t        j                  <   || t        j                     |<   B y)z0Adds keywords and builtins to the CLI tree root.exitzExit the interactive shell.0zThe exit status.status?FSTATUS)defaultdescriptionrE   nargsrequiredvalue)commandr}   positionals)
!{doelifelseifthentimeuntilwhileT)breakcasecontinuedoneesacfiN)r   Noder   LOOKUP_IS_GROUPLOOKUP_COMMANDSLOOKUP_IS_SPECIAL)r'   noderE   s      r,   _AddCliTreeKeywordsAndBuiltinsr      s    
 
/ /	
$ "'$v)-$vv&!d==D#(D		 %)D	!	!")-D		 &! Bd==D#(D		 )-D		 & Br-   c                   N    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zy)Applicationad  The CLI application.

  Attributes:
    args: The parsed command line arguments.
    config: The interactive shell config object.
    coshell: The shell coprocess object.
    debug: The debugging object.
    key_bindings: The key_bindings object holding the key binding list and
      toggle states.
    key_bindings_registry: The key bindings registry.
  Nc                    || _         || _        || _        || _        t	        j
                         | _        | j                  j                         | _        t        j                  dd      | _        t        | j                         t        j                  d      }t        j                  d      }|| z  }t        j                   j#                  t%        j&                         j(                  d      }t        j                  d      }t+        j,                  | j                  |j.                  |j0                        }	t3        j4                  |||	||j0                  |j6                        }
t9        j:                  |||t=        j>                  |      d |
|j@                  rtC        jD                         nd t8        jF                  jH                        | _%        tM        |||| j                  |	|
| jO                  ||      t        jP                         t        jR                         		      | _*        | jT                  |
_*        | j                  jW                  | jT                         tY        jZ                  | j                         y )
NT)ignore_out_of_datewarn_on_exceptionsFshell_history)rR   hidden)r   r   r)   argsr   manpage_generator)enable_history_searchrB   is_multiliner   	validatorr
   r   accept_action)r   	multiline)	r   r   r   r'   r)   r*   r   r"   r#   ).r   r   r   r   r   KeyBindingskey_bindingsMakeRegistrykey_bindings_registryr   LoadAllr'   r   r   to_simple_filterospathjoincore_configPathsglobal_config_dirr   ParserrR   r   r
   InteractiveCliCompleterr   	pt_bufferBuffer
pt_historyFileHistorysuggestr   AutoSuggestFromHistoryAcceptActionRETURN_DOCUMENTdefault_bufferr    _CreatePromptApplicationcreate_eventloopcreate_outputrT   
Initializer	   LoadViBindings)r(   r   r   r   r   rB   r   history_filer   r)   r*   s              r,   r%   zApplication.__init__   s   DIDLDKDJ ,,.D!%!2!2!?!?!AD #**D:DI
 #499-
 &66t<%66u=33377<< 1 1 3 E E /1L**51I  		}} &==-}} 224 $**33&&|4' #99;-1,,<<
D YY-311<E 2 G,,.&&(DH !% 	  *t99:r-   c                 r    t        j                  t        j                  |t	               g j
                   j                  d j                  dddt        j                  fd      t        j                   fd      d       j                  ddd j                  ddt        j                         	      S )z#Creates a shell prompt Application.NFc                             S rP   rc   )rT   r   s    r,   rU   z6Application._CreatePromptApplication.<locals>.<lambda>N  s    IKr-   c                 D    j                   j                  j                  S rP   )r   help_keytoggle)_r(   s    r,   rU   z6Application._CreatePromptApplication.<locals>.<lambda>P  s    $++44;;r-   T)r   extra_input_processorsget_bottom_status_tokensget_bottom_toolbar_tokensget_continuation_tokensget_debug_tokensget_prompt_tokensis_passwordlexerr   	show_help
wrap_lines)	r   r   	clipboarderase_when_done	get_titler   mouse_supportreverse_vi_search_directionr   )pt_applicationr   r   CreatePromptLayoutrM   _GetBottomStatusTokens_GetBottomToolbarTokens_GetDebugTokensr   	Conditionr   r   interactive_styleGetDocumentStyle)r(   r   r   s   ` `r,   r   z$Application._CreatePromptApplication@  s     %%(($+I;%)%@%@&*&B&B$(!11"''(?@'';=
 """88$(002/ r-   c                    | j                   j                  ry| j                  j                  d      s"t	        j
                         j                          t        j                  j                  j                  j                         xs d}t        j                  j                  j                  j                         xs d}||fS )z-Returns the current (project, account) tuple.)mezmyself@iprojectz<NO PROJECT SET>z<NO ACCOUNT SET>)r   	obfuscater   IsSpecifiedr   ActivePropertiesFile
Invalidater   VALUEScorer   Getaccount)r(   r   r   s      r,   _GetProjectAndAccountz!Application._GetProjectAndAccount]  s    {{99  +((*557$$,,002H6HG$$,,002H6HGWr-   c                     | j                         \  }}t        d|z   d|z   g|j                  j                  |j                  j                         j                        S )z@Returns the bottom status tokens based on the key binding state.zProject:zAccount:ro   rn   )r   ru   r   justify_bottom_linesr#   get_sizecolumns)r(   rT   r   r   s       r,   r   z"Application._GetBottomStatusTokensg  sW    113GW	g	zG34

//jj!!#++- -r-   c                    | j                   j                  D cg c]  }|j                          }}|j                  j                  s5| j                         \  }}|j                  |       |j                  |       t        ||j                  j                  |j                  j                         j                        S c c}w )zAReturns the bottom toolbar tokens based on the key binding state.r   )r   r   GetLabelr   bottom_status_liner   rh   ru   r   r#   r   r   )r(   rT   bindingr`   r   r   s         r,   r   z#Application._GetBottomToolbarTokenso  s    040A0A0J0JK0JWg 0JFK::((335gwmmGmmG

//jj!!#++- - Ls   Cc                     |j                   j                         D cg c]!  }t        j                  j                  |dz   f# c}S c c}w )zReturns the debug frame tokens.rf   )r   contentsr   ri   Text)r(   rT   cs      r,   r   zApplication._GetDebugTokens{  s<    141C1C1EF1EAU[[q3w'1EFFFs   &Ac                     | j                   j                  j                   | j                   _        | j                   j	                         }|r|j
                  S dS )z%Prompts and returns one command line.N)rT   r   rR   rW   runr6   )r(   r]   s     r,   PromptzApplication.Prompt  s?    #'88??#:#::DHH
((,,.C388$$r-   c                     | j                   j                  dk(  r*t        j                  j                  | j
                  _        yt        j                  j                  | j
                  _        y)z+Called when coshell modes may have changed.emacsN)r   	edit_moder   EditingModeEMACSrT   editing_modeVI)r(   s    r,   SetModeszApplication.SetModes  sD    ||(#//55dhh#//22dhhr-   c                     | j                   xj                  dz  c_        | j                  j                  |      }|dkD  r
t	                |S )z;Runs the command(s) in text and waits for them to complete.r@      )rT   r&   r   r3   print)r(   r6   ry   s      r,   r3   zApplication.Run  s<    HHa\\d#F|gMr-   c                 $   | j                   j                  | j                         	 	 | j                         }|y| j	                  |       &# t
        $ r | j                   j                  sY yY $t        $ r Y .t        j                  $ r Y yw xY w)z(Loops Prompt-Run until ^D exit, or quit.N)
r   SetModesCallbackr  r   r3   EOFError
ignore_eofKeyboardInterruptinteractive_coshellCoshellExitError)r(   r6   s     r,   LoopzApplication.Loop  s    LL!!$--0
{{}<
   ||&&
 '  11 s"   A A B0B:BB)NNNN)rG   rH   rI   rJ   r%   r   r   r   r   r   r   r  r3   r  rc   r-   r,   r   r      s<    
M;^:-
-G%3r-   r   c                     t        j                         }	 t        | ||t        j                               j                          |j                         }t        j                  |       y# |j                         }w xY w)z!The interactive application loop.)r   r   r   r   N)	r  Coshellr   interactive_debugDebugr  Closesysrw   )r   r   r   ry   s       r,   mainr    sa    '')'%%'	
 df]]_F((6 ]]_Fs   /A+ +A=)P   T)NN)8rJ   
__future__r   r   r   r   r   r  googlecloudsdk.callioper   &googlecloudsdk.command_lib.interactiver   r	   r
   r   r  r   r  r   r   r   r   googlecloudsdk.command_lib.metar   googlecloudsdk.corer   r   r   "googlecloudsdk.core.configurationsr   prompt_toolkitr   r   r   r   r   r   r   r   r   r   r   r   r   prompt_toolkit.layoutr   r[   CommandLineInterfacer    	ProcessorrM   ru   r   objectr   r  rc   r-   r,   <module>r#     s     * &  % ' 	 
 , ; > < Q M 9 9 M > 5 * < 8 ' . #   " 0 $ $   9I4)
(
( I4X	Ei!! 	E*Z$.NB& BJr-   