o
    SF                     @   s  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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ZG dd dejZG dd deZG dd deZG dd deZdS )aH  Resource display for all calliope commands.

The print_format string passed to resource_printer.Print() is determined in this
order:
 (1) Display disabled and resources not consumed if user output is disabled.
 (2) The explicit --format flag format string.
 (3) The explicit Display() method.
 (4) The DisplayInfo format from the parser.
 (5) Otherwise no output but the resources are consumed.

Format expressions are left-to-right composable. Each format expression is a
string tuple

  < NAME [ATTRIBUTE...] (PROJECTION...) >

where only one of the three elements need be present.
    )absolute_import)division)unicode_literals)display_taps)
exceptions)log)module_util)
properties)cache_update_ops)resource_lex)resource_printer)resource_projection_spec)resource_property)resource_reference)resource_transform)peek_iterableNc                   @      e Zd ZdZdS )ErrorzBase exception for this module.N__name__
__module____qualname____doc__ r   r   </tmp/google-cloud-sdk/lib/googlecloudsdk/calliope/display.pyr   5       r   c                   @   r   )CommandNeedsAddCacheUpdaterz(Command needs an AddCacheUpdater() call.Nr   r   r   r   r   r   9   r   r   c                   @   r   )"CommandShouldntHaveAddCacheUpdaterz4Command has an AddCacheUpdater() call and shouldn't.Nr   r   r   r   r   r   =   r   r   c                   @   s   e Zd ZdZdZd.ddZdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- ZdS )/	Displayera  Implements the resource display method.

  Dispatches the global flags args by constructing a format string and letting
  resource_printer.Print() do the heavy lifting.

  Attributes:
    _args: The argparse.Namespace given to command.Run().
    _command: The Command object that generated the resources to display.
    _defaults: The resource format and filter default projection.
    _format: The printer format string.
    _info: The resource info or None if not registered.
    _printer: The printer object.
    _printer_is_initialized: True if self._printer has been initialized.
    _resources: The resources to display, returned by command.Run().
    _transform_uri: A transform function that returns the URI for a resource.
  )asyncfilterlimitNc                 C   s   || _ d| _|| _d| _d| _d| _d| _d| _d| _d| _	|| _
|s'| }|rE|j| _tj| j|j|jd| _|j| _|j| _|j| _| jjdtj| _|| jjtd< dS )ak  Constructor.

    Args:
      command: The Command object.
      args: The argparse.Namespace given to the command.Run().
      resources: The resources to display, returned by command.Run(). May be
        omitted if only GetFormat() will be called.
      display_info: The DisplayInfo object reaped from parser.AddDisplayInfo()
        in the command path.
    NF)defaultssymbolsaliasesuriconditionals)_args_cache_updater_command	_defaults_default_format_used_format_filter_info_printer_printer_is_initialized
_resourcesGetDisplayInfocache_updaterr   ProjectionSpec
transformsr$   formatflatten_flattenr    r#   getr   TransformUri_transform_uriGetTypeDataName)selfcommandargs	resourcesdisplay_infor   r   r   __init__V   s<   zDisplayer.__init__c                 C   s$   |dkrt | jddS t | j|dS )zReturns the value of flag_name in args, None if it is unknown or unset.

    Args:
      flag_name: The flag name string sans leading '--'.

    Returns:
      The flag value or None if it is unknown or unset.
    r   async_N)getattrr'   )r=   	flag_namer   r   r   _GetFlag   s   	zDisplayer._GetFlagc              	      sD  ddl m}  jtjkrdS  js;t j|j|j|j	|j
fs!dS dtjjj v r9tdd j  dS t fdd jD rIdS t j|j|j
frZt j}n7t j|jrht j}n)t j|j	rvt j}ntd	t jt j d j  t| j }t!" j#| _#dS )
z@Taps a resource Uri cache updater into self.resources if needed.r   )baseNAddCacheUpdaterz8`{}` needs a parser.display_info.AddCacheUpdater() call. c                    s   g | ]}  |qS r   )rF   ).0flagr=   r   r   
<listcomp>       z-Displayer._AddUriCacheTap.<locals>.<listcomp>z.Cache updater [{}] not expected for [{}] `{}`.)$googlecloudsdk.callioperG   r(   r
   NoCacheUpdater
isinstancer)   CreateCommandDeleteCommandListCommandRestoreCommandr	   VALUEScorelintGetr   r6   joinr'   _GetCommandGetPathany_CORRUPT_FLAGSAddToCacheOpDeleteFromCacheOpReplaceCacheOpr   r   GetModulePathr   	UriCacherr;   r   Tapperr1   )r=   rG   cache_update_optapr   rL   r   _AddUriCacheTap   sJ   	
zDisplayer._AddUriCacheTapc                 C   sf   |  dsdS g }| jjD ]#}|dr|d}d}nd}|dd}|t|	 |f q|S )zReturns the list of --sort-by [(key, reverse)] tuples.

    Returns:
      The list of --sort-by [(key, reverse)] tuples, None if --sort-by was not
      specified. The keys are ordered from highest to lowest precedence.
    sort_byN~TFz[]z[0])
rF   r'   rh   
startswithlstripreplaceappendr   LexerKey)r=   keysnamereverser   r   r   _GetSortKeys   s   


zDisplayer._GetSortKeysc                    s(   dd  t | j fdd|d| _dS )a   _AddSortByTap helper that sorts the resources by keys.

    Args:
      keys: The ordered list of parsed resource keys from highest to lowest
        precedence.
      reverse: Sort by the keys in descending order if True, otherwise
        ascending.
    c              	   S   sB   t | |d}z	d|k sJ |W S  ttfy    t| Y S w )z>Returns the value for key in r that can be compared with None.N)r   rY   AssertionError	TypeErrorsix	text_type)rkeyvaluer   r   r   _GetKey   s   z)Displayer._SortResources.<locals>._GetKeyc                    s    fddD S )Nc                    s   g | ]} |qS r   r   )rJ   k)r{   rx   r   r   rM      rN   z>Displayer._SortResources.<locals>.<lambda>.<locals>.<listcomp>r   rx   r{   rp   r}   r   <lambda>   s    z*Displayer._SortResources.<locals>.<lambda>)ry   rr   N)sortedr1   )r=   rp   rr   r   r~   r   _SortResources   s   
zDisplayer._SortResourcesc                 C   s   t | jsdS |  }|sdS d| j_g }g }d}|D ]\}}|s%|}n||kr5|d||f g }|}|| q|rE|d||f |D ]
\}}| || qGdS )z-Sorts the resources using the --sort-by keys.NFr   )	r   
IsListLiker1   rs   r'   rh   insertrm   r   )r=   	sort_keysgroups
group_keysgroup_reversery   rr   rp   r   r   r   _AddSortByTap   s,   zDisplayer._AddSortByTapc                 C   s2   |   }|sdS t|| j}t| j|| _dS )z5Taps a resource filter into self.resources if needed.N)
_GetFilterr   Filtererr*   r   rd   r1   )r=   
expressionrf   r   r   r   _AddFilterTap  s
   zDisplayer._AddFilterTapc                    sv    fdd}   }|sdS |D ](}g }d}t| D ]}|du r*d}|| qd}|| q|s8|| qdS )zCTaps one or more resource flatteners into self.resources if needed.c                    s   t | }t j| _dS )z&Helper to add one flattened slice tap.N)r   	Flattenerr   rd   r1   )ry   rf   rL   r   r   _Slice  s   
z(Displayer._AddFlattenTap.<locals>._SliceNFT)_GetFlattenr   rn   ro   rm   )r=   r   rp   ry   flattened_keyslicedr|   r   rL   r   _AddFlattenTap  s"   
zDisplayer._AddFlattenTapc                 C   s<   |  d}|du s|dk rdS t|}t| j|| _dS )z4Taps a resource limit into self.resources if needed.r!   Nr   )rF   r   Limiterr   rd   r1   )r=   r!   rf   r   r   r   _AddLimitTap6  
   

zDisplayer._AddLimitTapc                 C   s<   |  d}|du s|dkrdS t|}t| j|| _dS )z4Taps a resource pager into self.resources if needed.	page_sizeNr   )rF   r   Pagerr   rd   r1   )r=   r   rf   r   r   r   _AddPageTap>  r   zDisplayer._AddPageTapc                 C   s2   |  ddur	dS t| j}t| j|| _dS )z;Taps a resource Uri replacer into self.resources if needed.r%   TN)rF   r   UriReplacerr;   r   rd   r1   )r=   rf   r   r   r   _AddUriReplaceTapF  s   zDisplayer._AddUriReplaceTapc                 C   sF   | j s| jS | j  }|s| j js| jS tjt| j j| jg|dS )z6Returns the default symbols for --filter and --format.)r"   r#   )r.   r*   GetTransformsr"   r   r4   CombineDefaults)r=   r#   r   r   r   _GetResourceInfoDefaultsQ  s   
z"Displayer._GetResourceInfoDefaultsc                 C   s   | j jpdS )z~Determines the explicit format.

    Returns:
      format: The format string, '' if there is no explicit format, or None
     )r'   r6   rL   r   r   r   _GetExplicitFormat_  s   zDisplayer._GetExplicitFormatc                 C   s   t | jdrdS | jS )zxDetermines the default format.

    Returns:
      format: The format string, '' if there is an explicit Display().
    Displayr   )hasattrr)   r,   rL   r   r   r   _GetDefaultFormatg  s   zDisplayer._GetDefaultFormatc                 C   s6   |  d}|d u r| jrtdt| j | jS |S )Nr    zDisplay filter: "%s")rF   r-   r   inforv   rw   )r=   flag_filterr   r   r   r   q  s   
zDisplayer._GetFilterc                 C   s   |  d}|d u r| jS |S )Nr7   )rF   r8   )r=   flag_flattenr   r   r   r   z  s   
zDisplayer._GetFlattenc           	      C   s   |   }|  }|s| ddu rdS d| _|}n|r!|d | }|s%|S |  }|s-|S g }t|ddD ]\}\}}|r?dnd}|d	jt	|||d
 q5|djd
|d7 }|S )zZDetermines the display format.

    Returns:
      format: The display format string.
    r%   Tzvalue(.)rI      )startz:reverser   z{name}:sort={order}{attr})rq   orderattrz:({orders}),)orders)r   r   rF   r+   rs   	enumeraterm   r6   r   
GetKeyNamerZ   )	r=   default_fmtfmtr   r   r   ry   rr   r   r   r   r   	GetFormat  s0   zDisplayer.GetFormatc                 C   s^   | j rdS d| _ |  | _|  | _| jr+tj| j| jtjd| _	| j	r-| j	j
| _dS dS dS )z2Initializes the printer and associated attributes.NT)r"   out)r0   r   r,   r   r*   r   Printerr   r   r/   column_attributesrL   r   r   r   _InitPrinter  s   

zDisplayer._InitPrinterc                 C   s    |    tj|  | j| jdS )z7Returns the set of key names referenced by the command.)filter_stringprinterr"   )r   r   GetReferencedKeyNamesr   r/   r*   rL   r   r   r   r     s   zDisplayer.GetReferencedKeyNamesc                 C   s<   |    |   |   |   |   |   |   dS )a!  Adds each of the standard display taps, if needed.

    The taps must be included in this order in order to generate the correct
    results. For example, limiting should not happen until after filtering is
    complete, and pagination should only happen on the fully trimmed results.
    N)rg   r   r   r   r   r   r   rL   r   r   r   _AddDisplayTaps  s   zDisplayer._AddDisplayTapsc                 C   s   t  st d t| jrt| jS | jS |   |   d}| j	r8t d| j
 | j	| j | j	 }nt| jdrLt d | j| j| j t j  | jds]| j| | jS )zThe default display method.zDisplay disabled.TzDisplay format: "%s"r   zExplicit Display.r6   )r   IsUserOutputEnabledr   r   r   r1   listr   r   r/   r,   PrintResourcesWerePrintedr   r)   r   r'   r   flushIsSpecifiedEpilog)r=   resources_were_displayedr   r   r   r     s&   



zDisplayer.Display)NN)r   r   r   r   r^   rB   rF   rg   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   A   s0    
*3 
	7	r   )r   
__future__r   r   r   rO   r   googlecloudsdk.corer   r   r   r	   googlecloudsdk.core.cacher
   googlecloudsdk.core.resourcer   r   r   r   r   r   googlecloudsdk.core.utilr   rv   r   r   r   objectr   r   r   r   r   <module>   s,   