
                             d 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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*                        Z G d dej.                        Zy)z/The BigQuery CLI repl command and related code.    )absolute_import)division)print_functionN)ListOptional)flags)utils)bigquery_command)bq_cached_client)appcommands)bq_error_utilsc                       e Zd ZdZ G d de      ZddZedefd       Z	d Z
dd	Zdd
ZdefdZd ZdedefdZdedefdZdee   fdZdedefdZdedefdZdefdZdedefdZy)CommandLoopz?Instance of cmd.Cmd built to work with bigquery_command.NewCmd.c                       e Zd ZdZy)CommandLoop.TerminateSignalz2Exception type used for signaling loop completion.N)__name__
__module____qualname____doc__     $platform/bq/frontend/command_repl.pyTerminateSignalr      s    <r   r   Nc                    t         j                  j                  |        d|d   i| _        g d| _        |j                         D ]e  \  }}|| j                  vst        |t        j                        s0|j                  s=|| j                  |<   t        | d||j                         g |xs d| _        | j                          d| _        y )Nhelp)r   replEOFdo_z
BigQuery> r   )cmdCmd__init__	_commands_special_command_namesitems
isinstancer
   NewCmdsurface_in_shellsetattr
RunCmdLoop_default_prompt_set_prompt_last_return_code)selfcommandspromptnamecommands        r   r!   zCommandLoop.__init__#   s    GGThv./DN"9D!)g
d11
1"2"9"9:&&&t'););< * "1\DDr   returnc                     | j                   S N)r,   r-   s    r   last_return_codezCommandLoop.last_return_code3   s    !!!r   c                     t        j                         j                         }|j                  r*t	        t        j                  |            }|d| _        y | j                  | _        y )N)id_fallbacksz> )	r   ClientGet
project_idstrbq_client_utilsGetReferencer/   r*   )r-   clientpaths      r   r+   zCommandLoop._set_prompt7   sN    $$&**,F--6BCd"$dk((dkr   c                 *    t         j                         )zTerminate the running command loop.

    This function raises an exception to avoid the need to do
    potentially-error-prone string parsing inside onecmd.

    Returns:
      Never returns.

    Raises:
      CommandLoop.TerminateSignal: always.
    )r   r   )r-   unused_argss     r   do_EOFzCommandLoop.do_EOF?   s     
%
%
''r   c                     t        d       y )NzGoodbye.)printr5   s    r   postloopzCommandLoop.postloopM   s
    	*r   linec                 (   |sg S |j                  d      d   j                         }d}|| j                  v r| j                  |   j                  }n|dk(  rd}n|dk(  rd}|r0t	                t	        |       t	        | j
                  |d       g S )	N r    set"set (project_id|dataset_id) <name>unsetunset (project_id|dataset_id)end)	partitionlowerr"   usagerE   r/   )r-   unused_textrG   unused_begidxunused_endidxcommand_namerS   s          r   completedefaultzCommandLoop.completedefaultP   s     i^^C(+113le		'|,225 47"/	eT*4ir   c                 x    t        dd       t        dj                  t        | j                                     y )NzAvailable commands:rI   rO   )rE   joinlistr"   r5   s    r   	emptylinezCommandLoop.emptylined   s'    	
S)	#((4'
()r   c                 ^   |dk(  r|S |j                  d      s|j                  d      ry|j                         j                         }t        |      dkD  r.|d   j	                         dk(  rdt        j                  |      S t        |      dk(  r|d   dvrd	|j                         S |S )
zPreprocess the shell input.r   exitquit   r   selectzquery )r   lsversionzhelp )
startswithstripsplitlenrR   shlexquote)r-   rG   wordss      r   precmdzCommandLoop.precmdh   s    u}kv$//&"9JJL E
5zA~%(..*h6 ;;t,..
5zQ58+DD**,((Kr   c                    	 t         j                  j                  | |      | _        y# t        j
                  $ r Y yt        $ r<}|j                  d      d   }t        j                  ||       d| _        Y d}~yd}~ww xY w)a6  Process a single command.

    Runs a single command, and stores the return code in
    self._last_return_code. Always returns False unless the command
    was EOF.

    Args:
      line: (str) Command line to process.

    Returns:
      A bool signaling whether or not the command loop should terminate.
    TrI   r   )r0   r`   NF)
r   r    onecmdr,   r   r   BaseExceptionrf   r   process_error)r-   rG   er0   s       r   rm   zCommandLoop.onecmdu   sv    !"ww~~dD9d  &&  !ZZ_Qd""140 d	!s   %( BB2A<<Bc                      t               } fd j                  D        }|j                  d |D               |j                  d       |j	                  d       |S )Nc              3   >   K   | ]  }|j                   vr|  y wr4   r#   ).0r0   r-   s     r   	<genexpr>z(CommandLoop.get_names.<locals>.<genexpr>   s'      "Dt222 	"s   c              3   &   K   | ]	  }d |  yw)r   Nr   )rt   r0   s     r   ru   z(CommandLoop.get_names.<locals>.<genexpr>   s     8xtD"xs   	do_selectrC   )dirr"   extendappendremove)r-   namesr.   s   `  r   	get_nameszCommandLoop.get_names   sP    IENNH
 
LL8x88	LL	LLLr   c                 ^   t        j                         j                         }|j                  d      ddgz   dd \  }}|dvs%dt	        |j                  d            cxk  rdk  sn t        d       y
|dk(  r|j                  st        d	       y
t        |||       | j                          y
)z3Set the value of the project_id or dataset_id flag.rI   rJ   N   r;   
dataset_idr`   rL   r   z+Cannot set dataset_id with project_id unsetr   )	r   r9   r:   rf   rg   rE   r;   r(   r+   )r-   rG   r?   r0   values        r   do_setzCommandLoop.do_set   s    $$&**,F::c?b"X-r2KD%00C

3(-A-01  
	f&7&79:  fdE"
r   c                     |j                         }t        j                  j                         }|dvrt	        d       yt        ||d       |dk(  rd|_        | j                          y)z5Unset the value of the project_id or dataset_id flag.r   rN   rJ   r;   r   )re   r   r9   r:   rE   r(   r   r+   )r-   rG   r0   r?   s       r   do_unsetzCommandLoop.do_unset   se    ::<D$$((*F//+, 	 fdB		
r   rW   c                 D    d |sht        d       t         j                        t        dj                   fd j                  j	                         D                     t                y| j                  v r"t         | j                  |   |g             y)z=Print the help for command_name (if present) or general help.c                 p   t        j                         dz   }t        |      dkD  rad|z  }t        j                  |j                  d|      |d      }|j                  d      \  }}}d|| d	z   |fz  }	dj                  |	|f      S d
}
dt        j                  |j                  d|      |
|
      z   dz   S )N   r`   rI   rJ   )	cmd_names)indentfirstline_indent
z%-*s%s:z  )r   GetMaxCommandLengthrg   r   	text_wrapCommandGetHelprQ   rZ   )r0   r1   command_namesindent_sizer   command_helpfirst_help_line_rest
first_linedefault_indents              r   FormatOneCmdz)CommandLoop.do_help.<locals>.FormatOneCmd   s    3359k	]	a	{"""2"?

 $0#9#9$#? DdSj/ JJ
yy*d+,,oo&&r]&C%!/ 	
r   z
Help for Bigquery commands:
z

c              3   T   K   | ]  \  }}|j                   vr ||       ! y wr4   rs   )rt   r0   r1   r   r   r-   s      r   ru   z&CommandLoop.do_help.<locals>.<genexpr>   s4      #9-$T888 4-8#9s   %()r   r   )rE   r[   r"   rZ   r$   )r-   rW   r   r   s   ` @@r   do_helpzCommandLoop.do_help   s    
0 -.4>>*m
++ #'>>#7#7#9  g  
	'
nn\*)N r   c                 &    t        |      xs |dk(  S )Nr   )bool)r-   stoprG   s      r   postcmdzCommandLoop.postcmd   s    :&&r   r4   )r2   N)r   r   r   r   	Exceptionr   r!   propertyintr6   r+   rC   rF   r<   rX   r\   rk   r   rm   r   r}   r   r   r   r   r   r   r   r   r      s    G		 	
  " " ")("(*    .
c 
   3 3 /# /b' ' 'r   r   c                   R     e Zd ZdZdedej                  f fdZdee	   fdZ
 xZS )Repl Start an interactive bq session.r0   fvc                     t         t        |   ||       d| _        t	        j
                  ddd|       | j                  |       y )NFr/   rJ   z!Prompt to use for BigQuery shell.)flag_values)superr   r!   r'   r   DEFINE_string_ProcessCommandRc)r-   r0   r   	__class__s      r   r!   zRepl.__init__   sD    	$tR(!D	"9r 	2r   r2   c                     t        t        j                         | j                        }t	        d       	 	 |j                          	 |j                  S # t        $ r t	                Y nw xY w8)r   )r/   z6Welcome to BigQuery! (Type help for more information.))r   r   GetCommandListr/   rE   cmdloopKeyboardInterruptr6   )r-   r   s     r   RunWithArgszRepl.RunWithArgs   sa    {113DKKHD	
BC
      	 s   A A*)A*)r   r   r   r   r<   r   
FlagValuesr!   r   r   r   __classcell__)r   s   @r   r   r      s/    (3 E$4$4 
!8C= 
!r   r   )r   
__future__r   r   r   r   rh   typingr   r   abslr   clientsr	   r=   frontendr
   r   pyglibr   r   r    r   BigqueryCmdr   r   r   r   <module>r      sR    5 &  % 
  !  , % %   L'#'' L'd!'' !r   