
    -                     x   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m	Z
 ddlmZ ddlmZ 	 ej                  Zd	Zd
ZdZ G d de
j(                        Z G d de
j(                        Z G d de      ZddZddZ G d dej4                        Z G d de      Z G d de      Zy# e$ r eZY xw xY w)z5Classes for reading and writing Anthos related files.    )absolute_import)division)unicode_literalsN)
exceptionsyaml)fileszauthentication.gke.io/v1alpha1zauthentication.gke.io/v2alpha1
apiVersionc                       e Zd ZdZy)YamlConfigObjectErrorz@Raised when an invalid Operation is invoked on YamlConfigObject.N__name__
__module____qualname____doc__     <lib/googlecloudsdk/command_lib/anthos/common/file_parsers.pyr   r   (   s    Hr   r   c                       e Zd ZdZy)YamlConfigFileErrorz%Base class for YamlConfigFile Errors.Nr   r   r   r   r   r   ,   s    -r   r   c                   $     e Zd ZdZd fd	Z xZS )YamlConfigObjectFieldErrorz<Raised when an invalid field is used on  a YamlConfigObject.c                 x    dj                  ||      }|rdj                  ||      }t        t        |   |       y )Nz1Invalid field [{}] for YamlConfigObject type [{}]z{}: {})formatsuperr   __init__)selffieldobject_typecustom_message	error_msg	__class__s        r   r   z#YamlConfigObjectFieldError.__init__3   s;    CJJ{I//)^<i	
$d4Y?r   N)r   r   r   r   r   __classcell__)r"   s   @r   r   r   0   s    D@ @r   r   c                    |st        |      |j                  |      }|j                          | }|r|j                         }||v r0t	        j
                  |      r|r|s|||<   |j                  |      }nb|rFt	        j
                  |      r1|r)t        j                         ||<   |j                  |      }n |||<   nt        dj                  |            |r|S )aU  Finds (potentially) nested value based on specified node_path.

  If set_value is passed will set the value at item_path,
  creating if needed.
  Args:
      item: Dict, Map like object to search.
      item_path: str, An item_sep separated path to nested item in map.
      item_sep: str, Path item separator, default is '.'.
      set_value: object, value to set at item_path. If path is not found
        create a new item at item_path with value of set_value.

  Returns:
      Object, data found in input item at item_path or None.

  Raises:
    KeyError: If item_path not found or empty.
  Path [{}] not found)
KeyErrorsplitreversepopr   	dict_likegetcollectionsOrderedDictr   )item	item_pathitem_sep	set_valuepartscontextparts          r   FindOrSetItemInDictr6   ;   s    $ 

9

//(
#%--/'99;Dw4>>'2 
5!D!g	t~~g.%113'$-KK%'#'$-,33I>??# 	$ 
.r   c                 b   |st        d      |j                  |      }|j                          | }|r}|j                         }||v rKt	        j
                  |      r6|j                  |      }|s |r||= n7t        dj                  |            |}nt        dj                  |            |r|yy)a?  Finds and deletes (potentially) nested value based on specified node_path.

  Args:
      item: Dict, Map like object to search.
      item_path: str, An item_sep separated path to nested item in map.
      item_sep: str, Path item separator, default is '.'.

  Raises:
    KeyError: If item_path not found or empty.
  zMissing Pathr&   N)r'   r(   r)   r*   r   r+   r,   r   )r/   r0   r1   r3   r4   r5   elems          r   DeleteItemInDictr9   g   s     

>
""
//(
#%--/'99;Dw4>>'2[[ddm.55i@A
A*11)<== 	r   c                   X    e Zd ZdZd Zed        ZddZd Zd Z	d Z
d	 Zd
 Zd Zd Zy)YamlConfigObjectzAbstraction for managing resource configuration Object.

  Attributes:
    content: YAMLObject, The parsed underlying config data.
  c                     || _         y r#   )_content)r   contents     r   r   zYamlConfigObject.__init__   s	    DMr   c                 @    t        j                  | j                        S r#   )copydeepcopyr=   r   s    r   r>   zYamlConfigObject.content   s    ==''r   Nc                 2    t        | j                  |||      S )a  Finds (potentially) nested value based on specified item_path.

    Args:
        item_path: str, An item_sep separated path to nested item in map.
        item_sep: str, Path item separator, default is '.'.
        set_value: object, value to set at item_path. If path is not found
          create a new item at item_path with value of set_value.

    Returns:
        Object, item found in map at item_path or None.
    )r6   r=   )r   r0   r1   r2   s       r   _FindOrSetItemzYamlConfigObject._FindOrSetItem   s     t}}i9MMr   c                     t        j                  | j                         t        j                  | j                  d      S )NT
round_trip)r   convert_to_block_textr=   dumprB   s    r   __str__zYamlConfigObject.__str__   s)    t}}-99T]]t44r   c                 *    | j                  ||       y )N)r2   rD   )r   keyvalues      r   __setitem__zYamlConfigObject.__setitem__   s    u-r   c                 $    | j                  |      S r#   rL   r   rM   s     r   __getitem__zYamlConfigObject.__getitem__   s    s##r   c                 0    t        | j                  |       y r#   )r9   r=   rQ   s     r   __delitem__zYamlConfigObject.__delitem__   s    T]]C(r   c                 ,    t        | j                        S r#   )iterr=   rB   s    r   __iter__zYamlConfigObject.__iter__   s    r   c                 ,    t        | j                        S r#   )lenr=   rB   s    r   __len__zYamlConfigObject.__len__   s    t}}r   c                 F    	 | j                  |       y# t        $ r Y yw xY w)NFT)rD   r'   )r   key_paths     r   __contains__zYamlConfigObject.__contains__   s.    
(#   s    	  .N)r   r   r   r   r   propertyr>   rD   rJ   rO   rR   rT   rW   rZ   r]   r   r   r   r;   r;      sI     ( (N5.$)r   r;   c                   L    e Zd ZdZdZdZdZed        Zd Z	d Z
d Zd	 Zdd
Zy)LoginConfigObjectz#Auth Login Config file abstraction.zspec.preferredAuthenticationzspec.authenticationz	spec.namec                     | t            S r#   )API_VERSIONrB   s    r   versionzLoginConfigObject.version   s    r   c                     | j                  d      }|D cg c]  }|d   |k(  r||   | }}|r|j                         S y c c}w )NF)	name_onlyname)GetAuthProvidersr*   )r   method_namemethod_type	providersxfounds         r   _FindMatchingAuthMethodz)LoginConfigObject._FindMatchingAuthMethod   sb    %%%6IaV9#+(B 	
9 
  YY[s   Ac                 |    	 | j                         }| j                  |d      }|ry	 y# t        t        f$ r Y yw xY w)z9Returns true is the current preferredAuth Method is ldap.ldapTF)GetPreferredAuthro   r   r'   )r   	auth_name
found_auths      r   IsLdapzLoginConfigObject.IsLdap   sS    '')i//	6Bj	 

  '1 
s   $) ;;c                     | j                   t        k(  r| | j                     S t        | j                  | j                  j
                  dj                  t                    Nzrequires config version [{}]re   AUTH_VERSION_2_ALPHAPREFERRED_AUTH_KEYr   r"   r   r   rB   s    r   rr   z"LoginConfigObject.GetPreferredAuth   sV    ||++$))**&t'>'>'+~~'>'>'E'L'L+?(AB Br   c                     | j                   t        k(  r|| | j                  <   y t        | j                  | j                  j
                  dj                  t                    rw   rx   )r   
auth_values     r   SetPreferredAuthz"LoginConfigObject.SetPreferredAuth   sU    ||++&0d4""#&t'>'>'+~~'>'>'E'L'L+?(AB Br   c                 ~    	 | | j                      }|sy |r|D cg c]  }|d   	 c}S |S # t        $ r Y y w xY wc c}w )Nrh   )AUTH_PROVIDERS_KEYr'   )r   rg   rl   providers       r   ri   z"LoginConfigObject.GetAuthProviders   sZ    t../i /89y8hvy99  
 :s   + :	77NT)r   r   r   r   rz   r   CLUSTER_NAME_KEYr`   re   ro   ru   rr   r}   ri   r   r   r   rb   rb      sD    +5,  
BB	r   rb   c                       e Zd ZdZddZed        Zed        Zed        Zed        Z	ed        Z
d	 Zd
 Zd Zd Z	 ddZd Zy)YamlConfigFilea  Utility class for searching and editing collections of YamlObjects.

  Attributes:
    item_type: class, YamlConfigObject class type of the items in file
    file_contents: str, YAML contents used to load YamlConfigObjects
    file_path: str, file path that YamlConfigObjects were loaded from
    data: [YamlObject], data loaded from file path. Could be 1 or more objects.
    yaml: str, yaml string representation of object.
  Nc                    || _         || _        || _        | j                   s| j                  st        d      | j                   r>	 t	        j
                  | j                   d      }|D cg c]
  } ||       c}| _        y | j                  r>	 t	        j                  | j                  d      }|D cg c]
  } ||       c}| _        y y c c}w # t        j                  $ r}t        dj                  |            d }~ww xY wc c}w # t        j                  $ r}t        dj                  |            d }~ww xY w)NzNCould Not Initialize YamlConfigFile:file_contents And file_path Are Both EmptyTrF   zError Parsing Config File: [{}]zError Loading Config File: [{}])_file_contents
_file_path
_item_typer   r   load_all_dataYAMLParseErrorr   load_all_pathFileLoadError)r   	item_typefile_contents	file_pathitemsrm   fes          r   r   zYamlConfigFile.__init__  s(   'DDODOt !M N N Pd11dC,12EqilE2
 
P""4??tD,12EqilE2
 
 3   P!"C"J"J2"NOOP
 3 P!"C"J"J2"NOOPsT   %C +C:C %D 5DD C D&D  DD D? D::D?c                     | j                   S r#   )r   rB   s    r   r   zYamlConfigFile.item_type      ??r   c                     | j                   S r#   )r   rB   s    r   datazYamlConfigFile.data!  s    ::r   c                     t        | j                        dk(  rt        | j                  d         S dj                  | j                  D cg c]  }t        |       c}      S c c}w )N   r   z---
)rY   r   strjoin)r   rm   s     r   r   zYamlConfigFile.yaml%  sN    
4::!A<<4AQ4554s   
A#c                     | j                   S r#   )r   rB   s    r   r   zYamlConfigFile.file_contents+  s    r   c                     | j                   S r#   )r   rB   s    r   r   zYamlConfigFile.file_path/  r   r   c                     | j                   S r#   r   rB   s    r   rJ   zYamlConfigFile.__str__3  s    99r   c                     t        |t              r]t        | j                        t        |j                        k(  xr0 t	        d t        | j                  |j                        D              S y)Nc              3   ,   K   | ]  \  }}||k(    y wr#   r   ).0rm   ys      r   	<genexpr>z(YamlConfigFile.__eq__.<locals>.<genexpr>9  s     @%?TQ!q&%?s   F)
isinstancer   rY   r   allzip)r   others     r   __eq__zYamlConfigFile.__eq__6  sP    %($))nEJJ/ A@SEJJ%?@@Br   c                 `    g }| j                   D ]  }||   |k(  s|j                  |        |S )z7Find all YamlObjects with matching data at search_path.r   append)r   search_pathrN   resultsobjs        r   FindMatchingItemzYamlConfigFile.FindMatchingItem<  s5    Gyy	[	U	"s  Nr   c                 ^    g }| j                   D ]  }||   }|s|j                  |        |S )z,Find all data in YamlObjects at search_path.r   )r   r   r   r   rN   s        r   FindMatchingItemDataz#YamlConfigFile.FindMatchingItemDataD  s5    Gyy+e	u  Nr   c                     g }| j                  ||      }|D ]  }|||<   |j                  |        |r| j                          |S )z-Find all matching YamlObjects and set values.)r   r   WriteToDisk)	r   object_pathobject_valuer0   
item_valuepersistr   found_items	ymlconfigs	            r   SetMatchingItemDataz"YamlConfigFile.SetMatchingItemDataM  sQ     G''\BK 	'i	nnY ! 
Nr   c                    | j                   st        d      t        j                         }t        j                  |dd      }t        j                  | j                  D cg c]  }|j                   c}|       t        j                  | j                         5 }|j                  d       |j                  |j                                ddd       yc c}w # 1 sw Y   yxY w)zOverwrite Original Yaml File.z-Could Not Write To Config File: Path Is Empty
zutf-8)newlineencoding)streamr   N)r   r   ioBytesIOTextIOWrapperr   dump_all_round_tripr   r>   r	   BinaryFileWriterseekwritegetvalue)r   out_file_buftmp_yaml_bufrm   fs        r   r   zYamlConfigFile.WriteToDiskY  s     >> OPP::<L##L$-46L;Aaii;$02				/1ggl##%& 
0	/ <	/	/s   !C1CC$)NNr   )r   r   r   r   r   r`   r   r   r   r   r   rJ   r   r   r   r   r   r   r   r   r   r      s    P,     6 6
     :>
'r   r   r^   )r_   )r   
__future__r   r   r   r-   r@   r   googlecloudsdk.corer   core_exceptionsr   googlecloudsdk.core.utilr	   abccollections_abcAttributeErrorAUTH_VERSION_1_ALPHAry   rd   Errorr   r   r   r6   r9   MutableMappingr;   rb   objectr   r   r   r   <module>r      s    < &  '   	 > $ * OO/ 8 7 IO11 I./// .@!6 @)X>>455 4n<( <~i'V i'y   / s   B/ /B98B9