o
    )                     @   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ZddlmZ	 ddlm
Z
 dd	lmZ dd
lmZ d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G dd deZdd ZG dd deZdS )a  Resource printer base class.

Each printer has three main attributes, all accessible as strings in the
--format='NAME[ATTRIBUTES](PROJECTION)' option:

  NAME: str, The printer name.

  [ATTRIBUTES]: str, An optional [no-]name[=value] list of attributes. Unknown
    attributes are silently ignored. Attributes are added to a printer local
    dict indexed by name.

  (PROJECTION): str, List of resource names to be included in the output
    resource. Unknown names are silently ignored. Resource names are
    '.'-separated key identifiers with an implicit top level resource name.

Example:

  gcloud compute instances list       --format='table[box](name, networkInterfaces[0].networkIP)'
    )absolute_import)division)print_function)unicode_literalsN)
exceptions)log)
console_io)resource_property   c                   @      e Zd ZdZdS )ErrorzExceptions for this module.N__name__
__module____qualname____doc__ r   r   O/tmp/google-cloud-sdk/lib/googlecloudsdk/core/resource/resource_printer_base.pyr   6       r   c                   @   r   )ProjectionRequiredErrorz-Format missing required projection exception.Nr   r   r   r   r   r   :   r   r   c                   @      e Zd ZdZdd ZdS )_ResourceMarkerz2A marker that can be injected into resource lists.c                 C      dS )zYCalled by ResourcePrinter.Addrecord().

    Args:
      printer: The printer object.
    Nr   selfprinterr   r   r   ActA   s   z_ResourceMarker.ActNr   r   r   r   r   r   r   r   r   r   >       r   c                   @   r   )FinishMarkerzA resource list Finish marker.c                 C      |   d S N)Finishr   r   r   r   r   M      zFinishMarker.ActNr   r   r   r   r   r   J   r   r   c                   @   r   )
PageMarkerzA resource list Page marker.c                 C   r    r!   )Pager   r   r   r   r   T   r#   zPageMarker.ActNr   r   r   r   r   r$   Q   r   r$   c                 C   s
   t | tS )z.Returns True if resource is a _ResourceMarker.)
isinstancer   )resourcer   r   r   IsResourceMarkerX   s   
r(   c                   @   s   e Zd ZdZ				dddZdd Zdd	 Zd
d ZdddZdddZ	dd Z
dd Zdd Zdd ZdddZdd ZdS ) ResourcePrinterae  Base class for printing JSON-serializable Python objects.

  Attributes:
    attributes: Optional printer attribute dict indexed by attribute name.
    column_attributes: Projection column attributes.
    _console_attr: The console attributes. May be ignored by some printers.
    _empty: True if there are no records.
    _heading: The list of column heading label strings.
    _name: Format name.
    _non_empty_projection_required: True if the printer requires a non-empty
      projection.
    _out: Output stream.
    _process_record: The function called to process each record passed to
      AddRecord() before calling _AddRecord(). It is called like this:
        record = process_record(record)
    _printer: The resource_printer.Printer method for nested formats.
    _is_column_visible: List of Boolean values indicating if indexed column is
      visible
  NFc                 C   sJ  ddl m} |	| _d| _d| _|| _|| _|ptj| _	|| _
d| _d| _|s*| }|p.|j| _|| || | }|ra| pEi | _|| _d| jv r`tjd|  |tj ni | _d| _d| jv rnd}
||
 d	| jv rz| j	 | _	W n	 ty   Y nw d
| jv r|du r| j	| _t | _	d| _|   dS )a6  Constructor.

    Args:
      out: The output stream, log.out if None. If the 'private' attribute is set
        and the output stream is a log._ConsoleWriter then the underlying stream
        is used instead to disable output to the log file.
      name: The format name.
      projector: Optional resource Projector.
      by_columns: True if AddRecord() expects a list of columns.
      ignore_default_transforms: Ignore default projection transforms if True.
      process_record: The function called to process each record passed to
        AddRecord() before calling _AddRecord(). It is called like this:
          record = process_record(record)
      non_empty_projection_required: True if the printer requires a non-empty
        projection.
      printer: The resource_printer.Printer method for nested formats.
      console_attr: The console attributes for the output stream. Ignored by
        some printers. If None then printers that require it will initialize it
        to match out.
      retain_none_values: Retain resurce dict entries with None values.
    r   )resource_projectorTNFdebugz{0} format projection:zno-undefinedprivatepager) googlecloudsdk.core.resourcer*   _console_attr_empty_heading_name_non_empty_projection_requiredr   out_out_printer_pager
_pager_outCompileEvaluate_process_recordSetByColumnsSetIgnoreDefaultTransforms
Projection
Attributes
attributescolumn_attributesstatusPrintformatNameSetRetainNoneValuesGetConsoleWriterStreamAttributeErrorioStringIO_SetVisibleColumns)r   r4   name	projector
by_columnsignore_default_transformsprocess_recordnon_empty_projection_requiredr   console_attrretain_none_valuesr*   
projectionr   r   r   __init__r   sN   






zResourcePrinter.__init__c                 C   s*   | j rdd | j  D | _dS d| _dS )z@Sets visible columns list if column attributes have been loaded.c                 S   s   g | ]}|j j qS r   )	attributehidden).0columnr   r   r   
<listcomp>   s    z6ResourcePrinter._SetVisibleColumns.<locals>.<listcomp>N)rA   Columns_is_column_visibler   r   r   r   rK      s
   
z"ResourcePrinter._SetVisibleColumnsc                    s.    j s    j r fddt|D S |S )z.Returns a list of visible columns given a row.c                    s   g | ]\}} j | r|qS r   )r\   )rX   icolr]   r   r   rZ      s    z7ResourcePrinter.RemoveHiddenColumns.<locals>.<listcomp>)r\   rK   	enumerate)r   rowr   r]   r   RemoveHiddenColumns   s
   z#ResourcePrinter.RemoveHiddenColumnsc                 C   s
   || _ dS )zOverrides the default heading.

    If the printer does not support headings then this is a no-op.

    Args:
      heading: List of column heading strings that overrides the default
        heading.
    N)r1   )r   headingr   r   r   
AddHeading   s   
	zResourcePrinter.AddHeadingTc                 C   r   )zFormat specific AddRecord().

    Args:
      record: A JSON-serializable object.
      delimit: Prints resource delimiters if True.
    Nr   r   recorddelimitr   r   r   
_AddRecord   s   zResourcePrinter._AddRecordc                 C   s2   t |r||  dS d| _| | || dS )a_  Adds a record for printing.

    Streaming formats (e.g., YAML) can print results at each AddRecord() call.
    Non-streaming formats (e.g., JSON, table(...)) may cache data at each
    AddRecord() call and not print until Finish() is called.

    Args:
      record: A JSON-serializable object.
      delimit: Prints resource delimiters if True.
    FN)r(   r   r0   rh   r;   re   r   r   r   	AddRecord   s   zResourcePrinter.AddRecordc                 C   sF   | j r| jr!ztj| j | jd W dS  ty   Y dS w dS dS )z_Prints the results for non-streaming formats.

    Must be called via super if overridden.
    )r4   N)r7   r5   r   Moregetvaluer8   rH   r]   r   r   r   r"      s   zResourcePrinter.Finishc                 C   s   | j  S )zEReturns True if some resource items were printed or printer disabled.)r0   r]   r   r   r   ResourcesWerePrinted   s   z$ResourcePrinter.ResourcesWerePrintedc                 C   r   )z3Flushes intermediate results for streaming formats.Nr   r]   r   r   r   r%     s   zResourcePrinter.Pagec                 C   s   | j |dd |   dS )zUPrint one record by itself.

    Args:
      record: A JSON-serializable object.
    Frg   N)ri   r"   )r   rf   r   r   r   PrintSingleRecord  s   z!ResourcePrinter.PrintSingleRecordc                 C   s   d| j v r
d| _dS | jr| jr| j std| jz&|r9|s't	|s/| j
||d n
|D ]}| 
| q1W |sB|   dS dS |sK|   w w )a  Prints resources using printer.AddRecord() and printer.Finish().

    Args:
      resources: A singleton or list of JSON-serializable Python objects.
      single: If True then resources is a single item and not a list.
        For example, use this to print a single object as JSON.
      intermediate: This is an intermediate call, do not call Finish().

    Raises:
      ProjectionRequiredError: If the projection is empty and the format
        requires a non-empty projection.
    disableFNztFormat [{0}] requires a non-empty projection. Use key parameters to specify a projection like so `{0}(foo, bar.baz)`rm   )r@   r0   r3   rA   r[   r   rD   r2   r	   
IsListLikeri   r"   )r   	resourcessingleintermediater'   r   r   r   rC     s0   

zResourcePrinter.Printc                 O   s   | j |i |S )zBCalls the resource_printer.Printer() method (for nested printers).)r6   )r   argskwargsr   r   r   Printer3  s   zResourcePrinter.Printer)
NNNFFNFNNF)T)FF)r   r   r   r   rU   rK   rb   rd   rh   ri   r"   rl   r%   rn   rC   rv   r   r   r   r   r)   ]   s$    
G
	

	
	%r)   )r   
__future__r   r   r   r   rI   googlecloudsdk.corer   core_exceptionsr   googlecloudsdk.core.consoler   r.   r	   STRUCTURED_INDENTATIONr   r   objectr   r   r$   r(   r)   r   r   r   r   <module>   s$   