o
                      	   @   sP  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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Zdd
lmZ ddlmZ dd Zdd ZdddZdd ZdddZdddZdddZdd Z		ddd Zdd!d"Z	$	dd%d&Zdd'd(Zdd*d+Z dd,d-Z!d.d/ Z"dd0d1Z#d2d3 Z$d4d5 Z%dd7d8Z&dd:d;Z'd<d= Z(d>d? Z)d@dA Z*ddCdDZ+ddFdGZ,dHdI Z-ddJdKZ.dLdM Z/ddNdOZ0dPdQ Z1ddRdSZ2dTdU Z3ddWdXZ4		ddZd[Z5dd]d^Z6dd_d`Z7ddadbZ8ddcddZ9dedf Z:dgdh Z;ddjdkZ<ddmdnZ=ddodpZ>ddqdrZ?i dsedteduedvedwedxedyedzed{ed|e d}e!d~e"de#de$de%de&de'i de(de)de*de+de,de-de/de.de0de1de>de2de3de4de5de6de7e8e9e:e?e;e<e=dZ@ddddddddZAdddZBdddZCdS )a  Built-in resource transform functions.

A resource transform function converts a JSON-serializable resource to a string
value. This module contains built-in transform functions that may be used in
resource projection and filter expressions.

NOTICE: Each TransformFoo() method is the implementation of a foo() transform
function. Even though the implementation here is in Python the usage in resource
projection and filter expressions is language agnostic. This affects the
Pythonicness of the Transform*() methods:
  (1) The docstrings are used to generate external user documentation.
  (2) The method prototypes are included in the documentation. In particular the
      prototype formal parameter names are stylized for the documentation.
  (3) The 'r', 'kwargs', and 'projection' args are not included in the external
      documentation. Docstring descriptions, other than the Args: line for the
      arg itself, should not mention these args. Assume the reader knows the
      specific item the transform is being applied to. When in doubt refer to
      the output of $ gcloud topic projections.
  (4) The types of some args, like r, are not fixed until runtime. Other args
      may have either a base type value or string representation of that type.
      It is up to the transform implementation to silently do the string=>type
      conversions. That's why you may see e.g. int(arg) in some of the methods.
  (5) Unless it is documented to do so, a transform function must not raise any
      exceptions related to the resource r. The `undefined' arg is used to
      handle all unusual conditions, including ones that would raise exceptions.
      Exceptions for arguments explicitly under the caller's control are OK.
    )absolute_import)division)unicode_literalsN)console_attr)resource_exceptions)resource_property)times)map)urllibc                 C   sb   | dv r| S | s
dS z|   dkrW dS W n	 ty   Y nw ztt| W S  ty0   Y dS w )z"Returns the Boolean value for arg.)TFFfalseT)lowerAttributeErrorboolfloat
ValueError)arg r   L/tmp/google-cloud-sdk/lib/googlecloudsdk/core/resource/resource_transform.pyGetBooleanArgValue?   s"   r   c                 C   s   ddl m} ||  S )z.Returns a parsed key from a dotted key string.r   )resource_lex)googlecloudsdk.core.resourcer   LexerKey)keyr   r   r   r   _GetParsedKeyQ   s   r   c                 C   s   t | t||S )zReturns the value for key in r.

  Args:
    r: The resource object.
    key: The dotted attribute name string.
    undefined: This is returned if key is not in r.

  Returns:
    The value for key in r.
  )r   Getr   )rr   	undefinedr   r   r   GetKeyValueX   s   r   c                 C   s   | S )aD  Marks a transform sequence to always be applied.

  In some cases transforms are disabled. Prepending always() to a transform
  sequence causes the sequence to always be evaluated.

  Example:
    `some_field.always().foo().bar()`:::
    Always applies foo() and then bar().

  Args:
    r: A resource.

  Returns:
    r.
  r   r   r   r   r   TransformAlwaysf   s   r     c                 C   sb   | s|S t | trdd | D S t| }dD ]}||}|dkr,||d d   S q|p0|S )zReturns the last path component.

  Args:
    r: A URI or unix/windows file path.
    undefined: Returns this value if the resource or basename is empty.

  Returns:
    The last path component.
  c                 S      g | ]}t |qS r   )TransformBaseName.0ir   r   r   
<listcomp>       z%TransformBaseName.<locals>.<listcomp>)/\r      N)
isinstancelistsix	text_typerfind)r   r   s	separatorr&   r   r   r   r#   {   s   



r#   c                 C   s   |S )zReturns the current resource collection.

  Args:
    r: A JSON-serializable object.
    undefined: This value is returned if r or the collection is empty.

  Returns:
    The current resource collection, undefined if unknown.
  r   r   r   r   r   r   TransformCollection   s   r4   c           	      K   s\   t | }d|fd|fd|fd|ffD ]\}}|r+t||r+tj||fi |  S q|S )a<  Colorizes the resource string value.

  The *red*, *yellow*, *green* and *blue* args are RE patterns, matched against
  the resource in order. The first pattern that matches colorizes the matched
  substring with that color, and the other patterns are skipped.

  Args:
    r: A JSON-serializable object.
    red: The substring pattern for the color red.
    yellow: The substring pattern for the color yellow.
    green: The substring pattern for the color green.
    blue: The substring pattern for the color blue.
    **kwargs: console_attr.Colorizer() kwargs.

  Returns:
    A console_attr.Colorizer() object if any color substring matches, r
    otherwise.

  Example:
    `color(red=STOP,yellow=CAUTION,green=GO)`:::
    For the resource string "CAUTION means GO FASTER" displays the
    substring "CAUTION" in yellow.
  redyellowgreenblue)r.   r/   researchr   	Colorizer)	r   r5   r6   r7   r8   kwargsstringcolorpatternr   r   r   TransformColor   s   
r@   c                 C   sL   | si S zi }| D ]}| |d}|d ||< q	|W S  ty%   i  Y S w )a2  Counts the number of each item in the list.

  A string resource is treated as a list of characters.

  Args:
    r: A string or list.

  Returns:
    A dictionary mapping list elements to the number of them in the input list.

  Example:
    `"b/a/b/c".split("/").count()` returns `{a: 1, b: 2, c: 1}`.
  r   r+   )get	TypeError)r   countitemcr   r   r   TransformCount   s   rF   %Y-%m-%dT%H:%M:%Sr+   c           
   
      s>  z  W n tttfy   Y nw |rt|ndz
tt| }W n ttfy3   d}Y nw |durPzt|}t| W S  tj	yO   Y nw t
dgd}|rbt|tjrb||rit|ndztjd}t| W S  tj	y   Y nw  fdd}	z|	 W S  ttfy   Y |S w )a#  Formats the resource as a strftime() format.

  Args:
    r: A timestamp number or an object with 3 or more of these fields: year,
      month, day, hour, minute, second, millisecond, microsecond, nanosecond.
    format: The strftime(3) format.
    unit: If the resource is a Timestamp then divide by _unit_ to yield seconds.
    undefined: Returns this value if the resource is not a valid time.
    tz: Return the time relative to the tz timezone if specified, the explicit
      timezone in the resource if it has one, otherwise the local timezone.
      For example: `date(tz=EST5EDT, tz_default=UTC)`.
    tz_default: The default timezone if the resource does not have a timezone
      suffix.

  Returns:
    The strftime() date format for r or undefined if r does not contain a valid
    time.
  Ndatetimetzinfoc               	      s   d} g }t j }dD ] }t|gd}|du r!t||d}n| d7 } |t| q|d tg dD ]"\}}t|gd}|durZ|d  tt|d|d   7  < q8| dk rat| t j | }t	
| S )	a  Returns the formatted time from broken down time parts in r.

    Raises:
      TypeError: For invalid time part errors.
      ValueError: For time conversion errors or not enough valid time parts.

    Returns:
      The formatted time from broken down time parts in r.
    r   )yearmonthdayhourminutesecondNr+   )
nanosecondmicrosecondmillisecondi     )rH   nowr   r   getattrappendint	enumerater   r   FormatDateTime)validpartsrV   partvaluer&   dtformatr   tz_intz_outr   r   _FormatFromParts  s(   

$

z'TransformDate.<locals>._FormatFromParts)	isoformatr   rB   r   r   GetTimeZoner   GetDateTimeFromTimeStampr[   Errorr   r   r,   r.   string_typesParseDateTime)
r   rb   unitr   tz
tz_default	timestampr`   original_reprre   r   ra   r   TransformDate   sF   $rq   c                 C   sL   |dkrzt t| W S    Y dD ]}z	| ||W   S    Y q|S )a  Returns the decoded value of the resource that was encoded by encoding.

  Args:
    r: A JSON-serializable object.
    encoding: The encoding name. *base64* and *utf-8* are supported.
    undefined: Returns this value if the decoding fails.

  Returns:
    The decoded resource.
  base64)replacestrict)rr   urlsafe_b64decodestrdecode)r   encodingr   errorsr   r   r   TransformDecode<  s   rz   rU   Tc              	   C   s  z
t |}t |}W n ty   | Y S w t|}|r[z"tt| |}|r,t| |nd}	|	r6t|	}
ntj|jd}
W n tjyJ   | Y S w |
| }tj	||dj
||dS z
t| t| }W n ttfyr   d}Y nw |durztjd||d}|j
||dW S  tjy   Y nw zt| }|j
||dW S  tjy   Y nw zt| }W n tjy   | Y S w tj|jd}
|
| }tj	||dj
||dS )a`  Formats the resource as an ISO 8601 duration string.

  The [ISO 8601 Duration](https://en.wikipedia.org/wiki/ISO_8601#Durations)
  format is: "[-]P[nY][nM][nD][T[nH][nM][n[.m]S]]". The 0 duration is "P0".
  Otherwise at least one part will always be displayed. Negative durations are
  prefixed by "-". "T" disambiguates months "P2M" to the left of "T" and minutes
  "PT5M" to the right.

  If the resource is a datetime then the duration of `resource - current_time`
  is returned.

  Args:
    r: A JSON-serializable object.
    start: The name of a start time attribute in the resource. The duration of
      the `end - start` time attributes in resource is returned. If `end` is
      not specified then the current time is used.
    end: The name of an end time attribute in the resource. Defaults to
      the current time if omitted. Ignored if `start` is not specified.
    parts: Format at most this many duration parts starting with largest
      non-zero part.
    precision: Format the last duration part with precision digits after the
      decimal point. Trailing "0" and "." are always stripped.
    calendar: Allow time units larger than hours in formatted durations if true.
      Durations specifying hours or smaller units are exact across daylight
      savings time boundaries. On by default. Use calendar=false to disable.
      For example, if `calendar=true` then at the daylight savings boundary
      2016-03-13T01:00:00 + P1D => 2016-03-14T01:00:00 but 2016-03-13T01:00:00 +
      PT24H => 2016-03-14T03:00:00. Similarly, a +P1Y duration will be inexact
      but "calendar correct", yielding the same month and day number next year,
      even in leap years.
    unit: Divide the resource numeric value by _unit_ to yield seconds.
    undefined: Returns this value if the resource is not a valid timestamp.

  Returns:
    The ISO 8601 duration string for r or undefined if r is not a duration.

  Example:
    `duration(start=createTime,end=updateTime)`:::
    The duration from resource creation to the most recent update.
    `updateTime.duration()`:::
    The duration since the most recent resource update.
  NrI   )deltacalendar)r]   	precisionzPT{0}S)r|   )rY   r   r   r   rk   r   NowrJ   ri   GetDurationFromTimeDeltaFormatr   rB   ParseDurationrb   )r   startendr]   r}   r|   rl   r   start_datetime	end_valueend_datetimer{   secondsdurationr   r   r   TransformDurationc  sl   ,
r   c                 C   sX   |dkrzt t| }t|dW S    | Y S zt| |W S    | Y S )a  Returns the encoded value of the resource using encoding.

  Args:
    r: A JSON-serializable object.
    encoding: The encoding name. *base64* and *utf-8* are supported.
    undefined: Returns this value if the encoding fails.

  Returns:
    The encoded resource.
  rr   
)rr   	b64encoder   EncodeToBytesSafeTextrstrip)r   rx   r   br   r   r   TransformEncode  s   r   Fc           
      C   s   t |}t||r
dnd}|j|}|s7|r7|jt|d}|r7i }t|D ]\}}	|||	< q)||j|< |r?|| |S |S )a}  Returns the enums dictionary description for the resource.

  Args:
    r: A JSON-serializable object.
    projection: The parent ProjectionSpec.
    enums: The name of a message enum dictionary.
    inverse: Do inverse lookup if true.
    undefined: Returns this value if there is no matching enum description.

  Returns:
    The enums dictionary description for the resource.
  zinverse-enumenum)r   GetTypeDataNamesymbolsrA   r.   	iteritems)
r   
projectionenumsinverser   	type_namedescriptionsnormalkvr   r   r   TransformEnum  s   

r   c                 C   s   |du r	t | }t|)a  Raises an Error exception that does not generate a stack trace.

  Args:
    r: A JSON-serializable object.
    message: An error message. If not specified then the resource is formatted
      as the error message.

  Raises:
    Error: This will not generate a stack trace.
  N)r.   r/   r   ri   r   messager   r   r   TransformError  s   

r   c                    s:   z fdd|D }dd |D W S  t y   g  Y S w )a,  Extract a list of non-empty values for the specified resource keys.

  Args:
    r: A JSON-serializable object.
    *keys: The list of keys in the resource whose non-empty values will be
        included in the result.

  Returns:
    The list of extracted values with empty / null values omitted.
  c                    s   g | ]}t  |d qS Nr   r%   r   r   r   r   r'         z$TransformExtract.<locals>.<listcomp>c                 S   s   g | ]}|r|qS r   r   r%   r   r   r   r   r'     r(   rB   )r   keysvaluesr   r   r   TransformExtract  s   r   c                 C   s   t |dur	|t| )a  Raises an InternalError exception that generates a stack trace.

  Args:
    r: A JSON-serializable object.
    message: An error message. If not specified then the resource is formatted
      as the error message.

  Raises:
    InternalError: This generates a stack trace.
  N)r   InternalErrorr.   r/   r   r   r   r   TransformFatal  s
   
r   c                 C   s^   ddl m} | s
| S ||j}t| s|| r| S dS g }| D ]}||r,|| q!|S )aH  Selects elements of x that match the filter expression.

  Args:
    r: A JSON-serializable object.
    expression: The filter expression to apply to r.

  Returns:
    The elements of r that match the filter expression.

  Example:
    `x.filter("key:val")` selects elements of x that have 'key' fields containing
    'val'.
  r   )resource_filterr!   )r   r   CompileEvaluater   
IsListLikerX   )r   
expressionr   selecttransformedrD   r   r   r   TransformFilter-  s   

r   c                 G   s(   |D ]}t | |}|dur|  S qdS )a  Returns the first non-empty attribute value for key in keys.

  Args:
    r: A JSON-serializable object.
    *keys: Keys to check for resource attribute values,

  Returns:
    The first non-empty r.key value for key in keys, '' otherwise.

  Example:
    `x.firstof(bar_foo, barFoo, BarFoo, BAR_FOO)`:::
    Checks x.bar_foo, x.barFoo, x.BarFoo, and x.BAR_FOO in order for the first
    non-empty value.
  Nr!   r   )r   r   r   r   r   r   r   TransformFirstOfK  s   
r   ,c                    s   fdd t | trEdkrdd t| D } n'dkr4 fddtt| D } n fddtt| D } | rgt | trgt | d	 ttfr^ fd
d| D } ttj| S | pjS )a  Formats nested dicts and/or lists into a compact comma separated list.

  Args:
    r: A JSON-serializable object.
    show: If show=*keys* then list dict keys; if show=*values* then list dict
      values; otherwise list dict key=value pairs.
    undefined: Return this if the resource is empty.
    separator: The list item separator string.

  Returns:
    The key=value pairs for a dict or list values for a list, separated by
    separator. Returns undefined if r is empty, or r if it is not a dict or
    list.

  Example:
    `--format="table(field.map(2).list().map().list().list()"`:::
    Expression with explicit flattening.
    `--format="table(field.flatten()"`:::
    Equivalent expression using .flatten().
  c                    s   t |  dS )N)showr   r2   )TransformFlatten)x)r2   r   r   r   r   Flattenw  s   z!TransformFlatten.<locals>.Flattenr   c                 S      g | ]}t |qS r   r.   r/   r   r   r   r   r'   ~      z$TransformFlatten.<locals>.<listcomp>r   c                    s   g | ]\}}t  |qS r   r   r%   _r   r   r   r   r'     s    c                    s"   g | ]\}}d j | |dqS z{k}={v})r   r   rb   r%   r   r   r   r   r   r'     s    r   c                    s   g | ]} |qS r   r   r   r   r   r   r'     r(   	r,   dictjoinsortedr.   r   r-   r	   r/   r   r   r   r2   r   )r   r2   r   r   r   r   a  s(   

r      c           	   	   C   s   zt | }W n ttfy   | Y S w |dur%dj||d}|j|dS dj|d}|j|d}|d}|dkrNt||d	 d }|d
k rNdj|dS |S )a7  Returns the string representation of a floating point number.

  One of these formats is used (1) ". _precision_ _spec_" if _spec_ is specified
  (2) ". _precision_" unless 1e-04 <= abs(number) < 1e+09 (3) ".1f" otherwise.

  Args:
    r: A JSON-serializable object.
    precision: The maximum number of digits before and after the decimal point.
    spec: The printf(3) floating point format "e", "f" or "g" spec character.
    undefined: Returns this value if the resource is not a float.

  Returns:
    The string representation of the floating point number r.
  Nz{{number:.{precision}{spec}}})r}   spec)numberz{{number:.{precision}}}r}   ze+r      	   z{number:.1f})r   rB   r   rb   findrY   )	r   r}   r   r   r   fmtrepresentationexponent_indexexponentr   r   r   TransformFloat  s    
r   c                 G   sL   |r|j dd|d|d| }nt| tr| }n| pdg}|j| S )a  Formats resource key values.

  Args:
    r: A JSON-serializable object.
    projection: The parent ProjectionSpec.
    fmt: The format string with {0} ... {nargs-1} references to the resource
      attribute name arg values.
    *args: The resource attribute key expression to format. The printer
      projection symbols and aliases may be used in key expressions. If no args
      are specified then the resource is used as the arg list if it is a list,
      otherwise the resource is used as the only arg.

  Returns:
    The formatted string.

  Example:
    `--format='value(format("{0:f.1}/{1:f.1}", q.CPU.default, q.CPU.limit))'`:::
    Formats q.CPU.default and q.CPU.limit as floating point numbers.
  z({0})r   T)
by_columnsdefaultsr!   )compilerrb   r   r   r,   r-   )r   r   r   argscolumnsr   r   r   TransformFormat  s   


r   c           	      G   s   | sdS t  }d}dd |D }| D ]J}|r|| nd}|s-|dt| q|d d}|D ]!}|rB|| d}nd	}t||d}|durW|t| q6|d
 q| S )a  Formats a [...] grouped list.

  Each group is enclosed in [...]. The first item separator is ':', subsequent
  separators are ','.
    [item1] [item1] ...
    [item1: item2] ... [item1: item2]
    [item1: item2, item3] ... [item1: item2, item3]

  Args:
    r: A JSON-serializable object.
    *keys: Optional attribute keys to select from the list. Otherwise
      the string value of each list item is selected.

  Returns:
    The [...] grouped formatted list, [] if r is empty.
  z[]Nc                 S   r"   r   )r   )r%   r   r   r   r   r'     r(   z"TransformGroup.<locals>.<listcomp> z[{0}][z, z: ])	ioStringIOwriterb   r.   r/   r   r   getvalue)	r   r   bufsepparsed_keysrD   subr   r_   r   r   r   TransformGroup  s0   

r   c                 C      |}| S )a   Disables the projection key if the flag name filter expr is false.

  Args:
    r: A JSON-serializable object.
    expr: A command flag filter name expression. See `gcloud topic filters` for
      details on filter expressions. The expression variables are flag names
      without the leading *--* prefix and dashes replaced by underscores.

  Example:
    `table(name, value.if(NOT short_format))`:::
    Lists a value column if the *--short-format* command line flag is not
    specified.

  Returns:
    r
  r   )r   exprr   r   r   r   TransformIf  s   r   Tc                 C   s   t | d|dS )a  Formats the resource to numeric ISO time format.

  Args:
    r: A JSON-serializable object.
    undefined: Returns this value if the resource does not have an isoformat()
      attribute.

  Returns:
    The numeric ISO time format for r or undefined if r is not a time.
  z%Y-%m-%dT%H:%M:%S.%3f%Oz)rb   r   )rq   r3   r   r   r   TransformIso  s   r   r)   c              	   C   s:   zdd | D }| |p|W S  ttfy   | Y S w )a  Joins the elements of the resource list by the value of sep.

  A string resource is treated as a list of characters.

  Args:
    r: A string or list.
    sep: The separator value to use when joining.
    undefined: Returns this value if the result after joining is empty.

  Returns:
    A new string containing the resource values joined by sep.

  Example:
    `"a/b/c/d".split("/").join("!")` returns `"a!b!c!d"`.
  c                 S   r   r   r   r$   r   r   r   r'   =  r   z!TransformJoin.<locals>.<listcomp>)r   r   rB   )r   r   r   r]   r   r   r   TransformJoin,  s   r   c                 C   s    zt | W S  ty   Y dS w )zReturns the length of the resource if it is non-empty, 0 otherwise.

  Args:
    r: A JSON-serializable object.

  Returns:
    The length of r if r is non-empty, 0 otherwise.
  r   )lenrB   r   r   r   r   TransformLenC  s
   	
r   c                 C   s   t | tr7|dkr|dd t| D S |dkr(|dd tt| D S |dd tt| D S t | trE|ttj| S | pH|S )a  Formats a dict or list into a compact comma separated list.

  Args:
    r: A JSON-serializable object.
    show: If show=*keys* then list dict keys; if show=*values* then list dict
      values; otherwise list dict key=value pairs.
    undefined: Return this if the resource is empty.
    separator: The list item separator string.

  Returns:
    The key=value pairs for a dict or list values for a list, separated by
    separator. Returns undefined if r is empty, or r if it is not a dict or
    list.
  r   c                 S   r   r   r   r   r   r   r   r'   c  r   z!TransformList.<locals>.<listcomp>r   c                 S   s   g | ]	\}}t |qS r   r   r   r   r   r   r'   f  s    c                 S   s   g | ]\}}d j ||dqS r   r   r   r   r   r   r'   h  s    r   r   r   r   r   TransformListR  s   


r   c                 C      | rt | tjr|  S | S )z_Returns r in lowercase.

  Args:
    r: A resource key value.

  Returns:
    r in lowercase
  )r,   r.   rj   r   r   r   r   r   TransformLowero     	r   c                 C   r   )a  Applies the next transform in the sequence to each resource list item.

  Example:
    ```list_field.map().foo().list()```:::
    Applies foo() to each item in list_field and then list() to the resulting
    value to return a compact comma-separated list.
    ```list_field.*foo().list()```:::
    ```*``` is shorthand for map().
    ```list_field.map().foo().map().bar()```:::
    Applies foo() to each item in list_field and then bar() to each item in the
    resulting list.
    ```abc.xyz.map(2).foo()```:::
    Applies foo() to each item in xyz[] for all items in abc[].
    ```abc.xyz.**foo()```:::
    ```**``` is shorthand for map(2).

  Args:
    r: A resource.
    depth: The list nesting depth.

  Returns:
    r.
  r   )r   depthr   r   r   r   TransformMap}  s   r   c                 C   s(   zdd | D W S  t y   g  Y S w )zRemove null values from the resource list.

  Args:
    r: A resource list.

  Returns:
    The resource list with None values removed.
  c                 S   s   g | ]}|d ur|qS r   r   )r%   r   r   r   r   r'     r   z$TransformNotNull.<locals>.<listcomp>r   r   r   r   r   TransformNotNull  s
   	r   c           
         s   d}i  t trntD ]}|ds!|ds!| | < q fdd}|D ]+\}}||}|du r8q+||}	|	du rAq+t|rNdj||	d  S dj||	d  S |S )	a  Formats a human readable XY resolution.

  Args:
    r: object, A JSON-serializable object containing an x/y resolution.
    undefined: Returns this value if a recognizable resolution was not found.
    transpose: Returns the y/x resolution if true.

  Returns:
    The human readable x/y resolution for r if it contains members that
      specify width/height, col/row, col/line, or x/y resolution. Returns
      undefined if no resolution found.
  ))widthheight)screenxscreeny)colrow)r   liner   y__c                    s.    D ]}| |v rt  |  gd  S qdS )zGets the resolution dimension for d.

    Args:
      d: The dimension name substring to get.

    Returns:
      The resolution dimension matching d or None.
    N)r   r   )dmmemr   r   r   
_Dimension  s
   	z'TransformResolution.<locals>._DimensionNz	{y} x {x}r   z	{x} x {y})r,   r   dir
startswithendswithr   r   rb   )
r   r   	transposenamesr   r  name_xname_yr   r   r   r  r   TransformResolution  s$   	r  c                 G   sv   | sdS t jt| } d| vr| S |pdD ]}d| d }|| v r,| |d   S q| dr9| dd S | S )a  Gets the /args/ suffix from a URI.

  Args:
    r: A URI.
    *args: Optional URI segment names. If not specified then 'regions', 'zones'
      is assumed.

  Returns:
    The URI segment after the first /*args/ in r, the last /-separated
      component in r if none found.

  Example:
    `"http://abc/foo/projects/bar/xyz".scope("projects")` returns `"bar/xyz"`.

    `"http://xyz/foo/regions/abc".scope()` returns `"abc"`.
  r!   r)   )regionszonesrT   https://)r
   parseunquoter.   r/   splitr  )r   r   scopesegmentr   r   r   TransformScope  s   
r  rT   c                 C   sN   | s|S t jt| } | d}z	|t| p|W S  ty&   | Y S w )a  Returns the index-th URI path segment.

  Args:
    r: A URI path.
    index: The path segment index to return counting from 0.
    undefined: Returns this value if the resource or segment index is empty.

  Returns:
    The index-th URI path segment in r
  r)   )r
   r  r  r.   r/   r  rY   
IndexError)r   indexr   segmentsr   r   r   TransformSegment  s   
r  0c              	   C   s
  dd }| s|dur|S zt | }W n ttfy   d}Y nw t |}||k r-|}d}	nd}	||\}
}||9 }||\}}|rP|| }dj|d}||S d	}d
D ]}|dk r^|} n|d }qT|rid| }|t|krxd|	t||S dj|d}||	||S )aC  Formats a human readable size in bytes.

  Args:
    r: A size in bytes.
    zero: Returns this if size==0. Ignored if None.
    precision: The number of digits displayed after the decimal point.
    units_in: A unit suffix (only the first character is checked) or unit size.
      The size is multiplied by this. The default is 1.0.
    units_out: A unit suffix (only the first character is checked) or unit size.
      The size is divided by this. The default is 1.0.
    min: Sizes < _min_ will be listed as "< _min_".

  Returns:
    A human readable scaled size in bytes.
  c              
   S   sp   dddddd}z	dt | pdfW S  ttfy   Y nw z| d	  }||| fW S  tttfy7   Y d
S w )zReturns the unit size for unit, 1.0 for unknown units.

    Args:
      unit: The unit suffix (only the first character is checked), the unit
        size in bytes, or None.

    Returns:
      A (unit_suffix, unit_size) tuple.
    i   i   i   @l        l           )KMGr   Pr!         ?r   )r!   r  )r   rB   r   upperr  KeyError)rl   	unit_sizeunit_suffixr   r   r   _UnitSuffixAndSize-  s$   z)TransformSize.<locals>._UnitSuffixAndSizeNr   z< r!   z{{0:.{precision}f}}r   PiB)bytesKiBMiBGiBTiBr$  g      @r   z	{0}{1}{2}z{{0}}{{1:.{precision}f}}{{2}})r   rB   r   rb   rY   )r   zeror}   units_in	units_outminr#  sizemin_sizeprefixr   units_in_sizeunits_out_suffixunits_out_sizer   the_unitrl   r   r   r   TransformSize  s@   

r5  :c              
   C   s   |  }|s|S zdd dd |dD D }W n tttfy'   | Y S w t|dkr9||d d p7d zt| t|  pC|W S  ttt	fyR   | Y S w )	a  Returns a list slice specified by op.

  The op parameter consists of up to three colon-delimeted integers: start, end,
  and step. The parameter supports half-open ranges: start and end values can
  be omitted, representing the first and last positions of the resource
  respectively.

  The step value represents the increment between items in the resource included
  in the slice. A step of 2 results in a slice that contains every other item in
  the resource.

  Negative values for start and end indicate that the positons should start from
  the last position of the resource. A negative value for step indicates that
  the slice should contain items in reverse order.

  If op contains no colons, the slice consists of the single item at the
  specified position in the resource.

  Args:
    r: A JSON-serializable string or array.
    op: The slice operation.
    undefined: Returns this value if the slice cannot be created, or the
        resulting slice is empty.

  Returns:
    A new array containing the specified slice of the resource.

  Example:
    `[1,2,3].slice(1:)` returns `[2,3]`.

    `[1,2,3].slice(:2)` returns `[1,2]`.

    `[1,2,3].slice(-1:)` returns `[3]`.

    `[1,2,3].slice(: :-1)` returns `[3,2,1]`.

    `[1,2,3].slice(1)` returns `[2]`.
  c                 S   s   g | ]
}|r
t |nd qS r   )rY   )r%   spr   r   r   r'     s    z"TransformSlice.<locals>.<listcomp>c                 s   s    | ]}|  V  qd S r   )strip)r%   pr   r   r   	<genexpr>  s    z!TransformSlice.<locals>.<genexpr>r6  r+   r   N)
r8  r  r   rB   r   r   rX   r-   slicer   )r   opr   opsr   r   r   TransformSlicel  s   '"r>  c                    s    | sg S  fdd}t | |dS )ao  Sorts the elements of the resource list by a given attribute (or itself).

  A string resource is treated as a list of characters.

  Args:
    r: A string or list.
    attr: The optional field of an object or dict by which to sort.

  Returns:
    A resource list ordered by the specified key.

  Example:
    `"b/a/d/c".split("/").sort()` returns `[a, b, c, d]`.
  c                    s    s| S t |  S r   r   )rD   attrr   r   SortKey  s   
zTransformSort.<locals>.SortKey)r   )r   )r   r@  rA  r   r?  r   TransformSort  s   rB  c              
   C   s2   | s|S z|  |W S  tttfy   | Y S w )aP  Splits a string by the value of sep.

  Args:
    r: A string.
    sep: The separator value to use when splitting.
    undefined: Returns this value if the result after splitting is empty.

  Returns:
    A new array containing the split components of the resource.

  Example:
    `"a/b/c/d".split()` returns `["a", "b", "c", "d"]`.
  )r  r   rB   r   )r   r   r   r   r   r   TransformSplit  s   rC  c                 C   st   zt |}W n ty   |  Y S w zt|rtjnd}tjtjB |B }t||| ||W S  tjy9   |  Y S w )ae  Replaces a pattern matched in a string with the given replacement.

  Return the string obtained by replacing the leftmost non-overlapping
  occurrences of pattern in the string by replacement. If the pattern isn't
  found, then the original string is returned unchanged.

  Args:
    r: A string
    pattern: The regular expression pattern to match in r that we want to
      replace with something.
    replacement: The value to substitute into whatever pattern is matched.
    count: The max number of pattern occurrences to be replaced. Must be
      non-negative. If omitted or zero, all occurrences will be replaces.
    ignorecase: Whether to perform case-insensitive matching.

  Returns:
    A new string with the replacements applied.

  Example:
    `table(field.sub(" there", ""))`:::
    If the field string is "hey there" it will be displayed as "hey".
  r   )	rY   r   r   r9   
IGNORECASE	MULTILINEDOTALLr   error)r   r?   replacementrC   
ignorecaseflagsr   r   r   TransformSub  s   rK  c                 G   r   )a:  Synthesizes a new resource from the schema arguments.

  A list of tuple arguments controls the resource synthesis. Each tuple is a
  schema that defines the synthesis of one resource list item. Each schema
  item defines the synthesis of one synthesized_resource attribute from an
  original_resource attribute.

  There are three kinds of schema items:

  *name:literal*:::
  The value for the name attribute in the synthesized resource is the literal
  value.
  *name=key*:::
  The value for the name attribute in the synthesized_resource is the
  value of key in the original_resource.
  *key*:::
  All the attributes of the value of key in the original_resource are
  added to the attributes in the synthesized_resource.
  :::

  Args:
    r: A resource list.
    *args: The list of schema tuples.

  Example:
    This returns a list of two resource items:::
    `synthesize((name:up, upInfo), (name:down, downInfo))`
    If upInfo and downInfo serialize to:::
    `{"foo": 1, "bar": "yes"}`
    and:::
    `{"foo": 0, "bar": "no"}`
    then the synthesized resource list is:::
    `[{"name": "up", "foo": 1, "bar": "yes"},
      {"name": "down", "foo": 0, "bar": "no"}]`
    This could then be displayed by a nested table using:::
    `synthesize(...):format="table(name, foo, bar)"`


  Returns:
    A synthesized resource list.
  r   )r   r   r   r   r   r   TransformSynthesize  s   ,rL  c                 C   r   )z_Returns r in uppercase.

  Args:
    r: A resource key value.

  Returns:
    r in uppercase
  )r,   r.   rj   r  r   r   r   r   TransformUpper/  r   rM  .c                 C   sX   dd }t | tjr| dr| S |S | r*dD ]}|t| |gd}|r)|  S q|S )zGets the resource URI.

  Args:
    r: A JSON-serializable object.
    undefined: Returns this if a the URI for r cannot be determined.

  Returns:
    The URI for r or undefined if not defined.
  c                 S   s2   z|  } W n	 t y   Y nw t| tjr| S dS )zReturns the string value for attr or None if the value is not a string.

    Args:
      attr: The attribute object to get the value from.

    Returns:
      The string value for attr or None if the value is not a string.
    N)rB   r,   r.   rj   r?  r   r   r   _GetAttrH  s   	
zTransformUri.<locals>._GetAttrr  )selfLinkSelfLinkN)r,   r.   rj   r  r   r   )r   r   rO  nameurir   r   r   TransformUri=  s   
rT  Noc                 C   s   | r
|du r| S |S |S )aW  Returns no if the resource is empty, yes or the resource itself otherwise.

  Args:
    r: A JSON-serializable object.
    yes: If the resource is not empty then returns _yes_ or the resource itself
      if _yes_ is not defined.
    no: Returns this value if the resource is empty.

  Returns:
    yes or r if r is not empty, no otherwise.
  Nr   )r   yesnor   r   r   TransformYesNob  s   rX  c              
   C   sR   | s|S z|rt |}|| r|p| W S W |S W |S  tttfy(   Y |S w )a  Returns does_match or r itself if r matches expression, nomatch otherwise.

  Args:
    r: A String.
    expression: expression to apply to r.
    does_match: If the string matches expression then return _does_match_
      otherwise return the string itself if _does_match_ is not defined.
    nomatch: Returns this value if the string does not match expression.

  Returns:
    does_match or r if r matches expression, nomatch otherwise.
  )r9   compilematchr   rB   r   )r   r   
does_matchnomatchmatch_rer   r   r   TransformRegexq  s   


r^  c              
   C   sZ   zt |}W n tttfy   | Y S w |dkr|S t| |k r#| S | d|d  d S )a  Returns r if less than limit, else abbreviated r followed by ellipsis.

  Args:
    r: A string.
    character_limit: An int. Max length of return string. Must be greater than 3
      because ellipsis (3 chars) is appended to abridged strings.
    undefined: A string. Return if r or character_limit is invalid.

  Returns:
    r if below character_limit or invalid character_limit
      (non-int or not greater than 3), else abridged r.
  rU   Nz...)rY   r   rB   r   r   )r   character_limitr   character_limit_intr   r   r   TransformTrailOff  s   ra  alwaysbasename
collectionr>   rC   daterw   r   encoder   rG  extractfatalfilterfirstofflattenr   rb   groupifisor   r   r   r-   r	   notnullregex
resolutionr  r  r.  r;  sort)r  r   
synthesizetrailoffr  rS  yesno)z,googlecloudsdk.api_lib.cloudbuild.transformsGetTransforms)z)googlecloudsdk.api_lib.compute.transformsrv  )z+googlecloudsdk.api_lib.container.transformsrv  )z'googlecloudsdk.api_lib.debug.transformsrv  )z+googlecloudsdk.api_lib.functions.transformsrv  )z0googlecloudsdk.api_lib.runtime_config.transformsrv  )z'googlecloudsdk.command_lib.dns.dns_keysrv  )
cloudbuildcompute	containerdebug	functionsruntimeconfigdnsc                 C   sP   | dv rt S | dd }t|d\}}|sdS t||gd}t||}| S )aP  Returns the builtin or collection specific transform symbols dict.

  Args:
    collection: A collection, None or 'builtin' for the builtin transforms.

  Raises:
    ImportError: module_path __import__ error.
    AttributeError: module does not contain method_name.

  Returns:
    The transform symbols dict, None if there is none.
  )NbuiltinrN  r   )NNN)fromlist)_BUILTIN_TRANSFORMSr  _API_TO_TRANSFORMSrA   
__import__rW   )rd  apimodule_pathmethod_namemodulemethodr   r   r   rv    s   
rv  objectc                 C   s   dj | |dS )zReturns the data name for name of type type_name.

  Args:
    name: The data name.
    type_name: The data type name.

  Returns:
    The data name for name of type type_name.
  z{name}::{type_name}rR  r   r   r  r   r   r   r     s   
r   r   )r!   )NNNN)rG   r+   r!   NN)r!   r!   rU   rU   Tr+   r!   )Fr!   )r!   r!   r   )r   Nr!   )r   )r)   r!   )r+   )r!   F)rT   r!   )r  r+   NNr   )r6  r!   )r   T)rN  )NrU  )Nr!   )r  )D__doc__
__future__r   r   r   rr   rH   r   r9   googlecloudsdk.core.consoler   r   r   r   googlecloudsdk.core.utilr   r.   	six.movesr	   r
   r   r   r   r    r#   r4   r@   rF   rq   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r5  r>  rB  rC  rK  rL  rM  rT  rX  r^  ra  r  r  rv  r   r   r   r   r   <module>   s0  



 

a'

g




,/-




7
"

Q
?

$0

%

	
 !"#1
