
    #                     6   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 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  ej(                  d      ZdZdZdZdZdZdZdZ G d dej:                        Zd Zd Z d Z!ddZ"ddZ#ddZ$d Z%y) zJModule containing the command utils for resource-config/terraform surface.    )absolute_import)division)unicode_literalsN)core_exceptions)log)
console_io)files)	platforms)times)runtime)templatez^#zterraform importzterraform_import_{ts}.{suffix}z%Y%m%d-%H-%M-%Sz;
module "{module_name}" {{
  source = "{module_source}"
}}
z=
#!/bin/sh
# Terraform Import Script generated by gcloud cli
zInvalid export Path {}. Path should point to an export Terraform(.tf) file or directotry of Terraform files.
Please see `gcloud alpha resource-config bulk-export` for more details.zgcloud-export-modules.tfc                       e Zd ZdZy)TerraformGenerationErrorzEBase Exception for errors that occur during import script generation.N)__name__
__module____qualname____doc__     Blib/googlecloudsdk/command_lib/util/declarative/terraform_utils.pyr   r   :   s    Mr   r   c                 (   t         j                  j                  |       r| j                  d      r| g}nHt         j                  j	                  |       rt        j                  | dd       }nt        t              g }g }|D ]  }t         j                  j                  |      }d|v s|d   j                         rt        j                  |       Ot        j                  |t              }	 t        |      j                         }t        j                   t         j                  j#                  |            |j%                  d      d   j'                         f}|j)                  |        |st/        dj1                  |             |r3t3        j4                  dj1                  dj7                  |                   |S # t*        $ r |j)                  |       Y [t
        j,                  $ r!}	t/        d	j1                  | |	
            d}	~	ww xY w)zDRead files from export path and parse out import command statements..tfFc                 $    | j                  d      S )Nr   )endswith)xs    r   <lambda>z"ParseExportFiles.<locals>.<lambda>G   s    E!2r   )include_dirsfile_predicatedefaultr   #   z0Could not parse Terrorm data from {path}:: {err})patherrNz-No Terraform importable data found in {path}.)r"   z=Error generating imports for the following resource files: {}
)osr"   isfiler   isdirr	   GetDirectoryTreeListing
ValueErrorINVALID_EXPORT_PATH_MSGbasenameisdigitremoveFilteredFileReaderIMPORT_REGEXlistpopExpandHomeAndVarsdirname	partitionstripappend
IndexErrorErrorr   formatr   warningjoin)
export_pathinput_filesimport_dataerror_filesin_filein_file_base_nameimport_readercommandimport_linees
             r   ParseExportFilesrF   >   s    WW^^K [%9%9%%@-K	ww}}[!//24K
 ,
--++g((1%%):1)=)E)E)Gii..wEm*}%))+..rwww/GH((-a0668:;' & 

"7>> 	? 	  KKGNNIIk"	$% 
  $7#[[ *&>EE a F )* 	**s   -A>GHH0HHc                      t         j                  j                         rdnd} t        j	                  t        j                  t        j                         t              |       S )z.Generate a default filename for import script.cmdsh)tssuffix)	r
   OperatingSystem	IsWindowsIMPORT_SCRIPT_DEFAULT_NAMEr9   r   FormatDateTimeNowIMPORT_DATE_FORMAT)rK   s    r   GenerateDefaultScriptFileNamerR   j   sM    --7795t&	#	*	*			eiik+=	>v 
+ 
O Or   c                    t         j                  j                  dt         j                  j                  | |            }dj                  t         j                  j	                  | j                  |d            j                  t         j                              j                  d      j                         }|d   j                         rdj                  |      }||fS )N.)start- r   zgcp-{})r%   r"   r;   relpathnormpathreplacesplitseplstriprstripr,   r9   )import_pathdest_dirmodule_sourcemodule_names       r   ConstructModuleParametersrc   q   s    '',,s!ww{(KM-gg{**8R89??
&&6#;vvx  ^//+.K		##r   c                     | r| j                         nd} |r-t        j                  j                  |j                               nd}d}d}| rt        j                  j	                  |       r+dj                  |       }t        j                  |dddd       t        j                  j                  |       }t        j                  j                  |       xs t        j                         }t        j                  j                  |      r/t        j                  |      st        dj                  |            |rRt        j                  j                  |      r/t        j                  |      st        dj                  |            d}|}||fS )	z9Helper function for generating output file and directory.Nz{} already exists.zDo you want to overwrite?TzAborted script generation.)prompt_stringr   cancel_stringcancel_on_noz-Error writing output file: {} is not writablez>Cannot write output to directory {}. Please check permissions.)r5   r%   r"   abspathr&   r9   r   PromptContinuer+   r3   r	   GetCWDr'   HasWriteAccessInDirr   r)   )output_file
output_dir	dest_filer`   overwrite_prompts        r   ProcessOutputParametersrp   |   sA   '2!!#+7A
 0 0 23t*)(	ww~~k".55kB
34   -Iww{+=u||~H	ww}}Xu'@'@'J$
9
@
@
JL L 
j!%%j1 3396*3EG GIH	H	r   c           	      ^   t         j                  j                  ||      }dg i}| D ]f  \  }}t        ||      \  }}|j	                  t
              dd }	|d   j                  dj                  |	d   ||	d   j                                      h t         j                  j                  |d         |d<   d}
t        j                  j                         rdnd}|dk(  rt        d	      }
n|dk(  rt        |d
<   t        d      }
	 t        j                   |d      5 }t#        j$                  |fi |}|
j'                  |       ddd       t        j(                  |d       |t/        |       fS # 1 sw Y   ,xY w# t        j*                  $ r}t-        dj                  |            d}~ww xY w)a  Generate Terraform import shell script from template.

  Args:
    import_data: string, Import data for each resource.
    dest_file: string, Filename path to write the generated script to. If
      dest_file is None, then a default filename will be generated.
    dest_dir: string, Directory path to write the generated script to. If
      dest_dir is None, then script will be written to CWD.

  Returns:
    tuple(string, int, [string])), the path to the generated script, number of
      import statements generated and list of files that could not be processed.

  Raises:
    TerraformGenerationError: If and error occurs writing to disk/stdout.
  data   Nz${cmd} module.{module_name}.{cmd_sfx}r   )rH   rb   cmd_sfxWINDOWSBASHzwindows_shell_template.tplbash_commentszbash_shell_template.tplTcreate_path  Error writing import script::{})r%   r"   r;   rc   r4   _IMPORT_CMD_PREFIXr6   r9   r5   linesepr
   rL   rM   _BuildTemplate_BASH_COMMENTSr	   
FileWriterr   Contextrender_contextchmodr8   r   len)r>   rn   r`   output_file_namecontextr_   import_statement_rb   import_cmd_dataoutput_templatetemplate_keyfctxrE   s                  r   GenerateImportScriptr      s   $ WW\\(I6RL''2#k#.{HENA{&001CDQRHOFOAHHA"((* I , - (3 JJOOGFO4'&//'77AAC,Y$%ABOv-GO$%>?O5			d
,/0OOA))c$$S)
, HHu% 
3{+	++
, 
,
 
 5
")0035 55s0   E: (E.E: .E73E: :F,F''F,c                    t         j                  j                  ||      }t        d      }t	               }| D ]'  \  }}t        ||      \  }	}
|j                  |
|	f       ) g }|D ].  }|j                  t        j                  |d   |d                0 d|i}t         j                  j                  |      |d<   	 t        j                  |d      5 }t        j                  |fi |}|j                  |       d	d	d	       t        j                   |d
       |t'        |      fS # 1 sw Y   ,xY w# t        j"                  $ r}t%        dj                  |            d	}~ww xY w)z.Generate terraform modules file from template.zterraform_module_template.tplr   rs   )rb   ra   projectmodulesTrx   Nrz   r{   )r%   r"   r;   r~   setrc   addr6   MODULE_TEMPLATEr9   r}   r	   r   r   r   r   r   r8   r   r   )r>   r   rn   r`   r   r   module_contentsr_   r   ra   rb   module_declarationsmoduler   r   r   rE   s                    r   GenerateModuleFiler      sX   WW\\(I6"#BC/E/#nk1!:X"M;m45 $ f6!9F1INP    'zz':;')5			*	=OOA))c$$S) 
> HHu% 
3/	// 
>	= 
 5
")0035 55s0   >D4 (D(=D4 (D1-D4 4E&E!!E&c                     t         j                  j                  t              }t         j                  j	                  |d|       }t        j                  |      }|S )Nterraform_templates)filename)r%   r"   r3   __file__r;   r   Template)template_file_namedir_nametemplate_pathfile_templates       r   r~   r~      sD    WW__X&('',,x)>13-##];-	r   )NN)&r   
__future__r   r   r   r%   re"googlecloudsdk.calliope.exceptionsr   googlecloudsdk.corer   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr	   r
   r   makor   r   compiler/   r|   rN   rQ   r   r   r*   TF_MODULES_FILENAMEr8   r   rF   rR   rc   rp   r   r   r~   r   r   r   <module>r      s    Q &  ' 	 	 > # 2 * . *   rzz% ' = & 
L 
 1 N44 N)XO$D/,d08r   