
    \?                        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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 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Z)dZ*dZ+dZ,dZ-dZ.e)e*j_                  d      z   e+j_                  d      z   dz   Z0d e,z   e-z   e.z   Z1 ee0e1      Z2 ee*e,      Z3 ee)e-      Z4 ee+e.      Z5 G d! d"e      Z6y)#z<Implementation of label command for cloud storage providers.    )absolute_import)print_function)division)unicode_literalsN)metrics)PreconditionException)Preconditions)Command)CommandArgument)ApiSelector)CommandException)NO_URLS_MATCHED_TARGET)CreateHelpText)storage_v1_messages)	shim_util)NO_MAX)UTF8)Retry)GcloudStorageFlag)GcloudStorageMap)LabelTranslationz<
  gsutil label set <label-json-file> gs://<bucket_name>...
z'
  gsutil label get gs://<bucket_name>
z
  gsutil label ch <label_modifier>... gs://<bucket_name>...

  where each <label_modifier> is one of the following forms:

    -l <key>:<value>
    -d <key>
z
<B>GET</B>
  The "label get" command gets the `labels
  <https://cloud.google.com/storage/docs/tags-and-labels#bucket-labels>`_
  applied to a bucket, which you can save and edit for use with the "label set"
  command.
ah  
<B>SET</B>
  The "label set" command allows you to set the labels on one or more
  buckets. You can retrieve a bucket's labels using the "label get" command,
  save the output to a file, edit the file, and then use the "label set"
  command to apply those labels to the specified bucket(s). For
  example:

    gsutil label get gs://bucket > labels.json

  Make changes to labels.json, such as adding an additional label, then:

    gsutil label set labels.json gs://example-bucket

  Note that you can set these labels on multiple buckets at once:

    gsutil label set labels.json gs://bucket-foo gs://bucket-bar
al  
<B>CH</B>
  The "label ch" command updates a bucket's label configuration, applying the
  label changes specified by the -l and -d flags. You can specify multiple
  label changes in a single command run; all changes will be made atomically to
  each bucket.

<B>CH EXAMPLES</B>
  Examples for "ch" sub-command:

  Add the label "key-foo:value-bar" to the bucket "example-bucket":

    gsutil label ch -l key-foo:value-bar gs://example-bucket

  Change the above label to have a new value:

    gsutil label ch -l key-foo:other-value gs://example-bucket

  Add a new label and delete the old one from above:

    gsutil label ch -l new-key:new-value -d key-foo gs://example-bucket

<B>CH OPTIONS</B>
  The "ch" sub-command has the following options

  -l          Add or update a label with the specified key and value.

  -d          Remove the label with the specified key.

z

ag  
  Gets, sets, or changes the label configuration (also called the tagging
  configuration by other storage providers) of one or more buckets. An example
  label JSON document looks like the following:

    {
      "your_label_key": "your_label_value",
      "your_other_label_key": "your_other_label_value"
    }

  The label command has three sub-commands:
c                   :   e Zd ZdZ ej
                  dededdddej                  ej                  gej                   ej                  d       ej                         g ej                  d      g ej                         gd      Z ej                   dg d	d
eeeed      Z e eg di        eg di        eg d edej2                  j4                         edej2                  j6                        d      di       Zd Zd Zd Zd Z d Z!y)LabelCommandz'Implementation of gsutil label command.label   zl:d:F   )setgetch)
usage_synopsismin_argsmax_argssupported_sub_argsfile_url_okprovider_url_okurls_start_arggs_api_supportgs_default_apiargparse_argumentscommand_helpz8Get, set, or change the label configuration of a bucket.)r   r   r    )	help_namehelp_name_aliases	help_typehelp_one_line_summary	help_textsubcommand_help_text)storagebucketsdescribezj--format=gsutiljson[key=labels,empty=' has no label configuration.',empty_prefix_key=storage_url,indent=2])gcloud_commandflag_map)r2   r3   updatez--labels-file)r2   r3   r7   z--remove-labels)repeat_typez--update-labels)-d-lc                 ~    | j                   s| j                          | j                   d   j                         dk(  ryy)Nr   r   r   r   )args$RaiseWrongNumberOfArgumentsExceptionlower)selfs    'platform/gsutil/gslib/commands/label.py_CalculateUrlsStartArgz#LabelCommand._CalculateUrlsStartArg   s4    99
//1yy|u$    c                 :   	 t         j                        dk  r j                           j                  d   }t        j                  j                  |      st        d|z        t        j                  |dt              5 }|j                         	ddd       t        t        dd      	 fd	       }d
} j                  dd }|D ]'  } j                  |dg      }|D ]  }d} ||        ) |st        t        t        |      z        y# 1 sw Y   xY w)z8Parses options and sets labels on the specified buckets.r   r   zCould not find the file "%s".rN   r   triestimeout_secsc                    | j                   }j                  j                  d|        |j                  dk(  r)j                  j                  
||j                         y d }d }t        j                  
      }j                  j                  |j                        t        j                  k(  rj                  |j                  ddg      \  }}|j                  }i }|j                  r2t        j                  t        j                   |j                              }t#        d t%        j&                  |      D              }|j)                  |       t        j*                  |      }nt        j*                  |      }t-        |      }	t/        j0                  |	      }j                  j3                  |j4                  ||	|j                  d
g       y )N$Setting label configuration on %s...s3providerlabelsmetagenerationbucket_fieldsc              3   *   K   | ]  \  }}|d f  y wN ).0key_s      r@   	<genexpr>zELabelCommand._SetLabel.<locals>._SetLabelForBucket.<locals>.<genexpr>  s      C(Afc1sDk(As   meta_gen_matchrN   idpreconditionsrM   fields)storage_urlloggerinfoscheme
gsutil_apiXmlPassThroughSetTaggingjsonloadsGetApiSelectorr   JSONGetSingleBucketUrlFromArg
url_stringrO   rN   r   JsonFromMessagedictsix	iteritemsr7   DictToMessager	   apitools_messagesBucketPatchBucketbucket_name)blrurllabels_messagerO   new_label_jsonrW   bucket_metadata
label_jsonmerged_labelsr^   
label_textr?   s             r@   _SetLabelForBucketz2LabelCommand._SetLabel.<locals>._SetLabelForBucket   s   OOc
kk=sC	t	0014:=** 	1 	F  J/OO**3::6+:J:JJ  $==nnX7G,H  >  J
!_*99.*## 001G1GHJJ  C(+j(AC C-


~
.+99-H. ,99.I.%^D+22.I##COO$32?-0ZZ,06	 	$ 	3rB   Fr\   rP   T)lenr<   r=   ospathisfiler   codecsopenr   readr   r   GetBucketUrlIterFromArgr   list)
r?   label_filename
label_filer}   some_matchedurl_argsurl_strbucket_iterbucket_listing_refr|   s
   `        @r@   	_SetLabelzLabelCommand._SetLabel   s
    499~
//1YYq\N77>>.)<~MNN	^S$	/:??$j 
0  :(3 ;(3T Lyy}H000Ok +
-. !,  3d8nDEE o 
0	/s   DDc                     i  _         d _         j                  rÉ j                  D ]  \  }}|dk(  rC|j                  d      }t	        |      dk7  rt        d|z        |d    j                   |d   <   N|dk(  rR|j                  d      }t	        |      dk7  rt        d|z        d	 j                   |<    xj                  dz  c_         j                            j                   st        d
      t        t        dd       fd       }d} j                  }|s j                          |D ]$  } j                  |      }	|	D ]  }
d} ||
        & |st        t        t        |      z        y	)z;Parses options and changes labels on the specified buckets.r   r:   :r   zrFound incorrectly formatted option for "gsutil label ch": "%s". To add a label, please use the form <key>:<value>.r   r9   zhFound incorrectly formatted option for "gsutil label ch": "%s". To delete a label, provide only its key.NzAPlease specify at least one label change with the -l or -d flags.rE   rF   c                    | j                   }j                  j                  d|        d }d }j                  j	                  |j
                        t        j                  k(  rj                  }j                  rij                  |j                  ddg      \  }}|j                  s;|j                  }t        d t        j                   j                        D              }t#        j$                  |      }nj                  |j                  ddg      \  }}|j                  }i }|j                  r2t'        j(                  t#        j*                  |j                              }t        j                   j                        D ]  \  }}	|	s||v r||= |	||<    t#        j$                  |      }t-        |      }
t/        j0                  |      }j                  j3                  |j4                  ||
|j
                  dg	       y )
NrJ   rN   rO   rP   c              3   0   K   | ]  \  }}|s	||f  y wrS   rT   )rU   kvs      r@   rX   zCLabelCommand._ChLabel.<locals>._ChLabelForBucket.<locals>.<genexpr>Q  s       %K#D41aA#Ds   
	rY   r[   r\   r]   )r`   ra   rb   rd   rh   rc   r   ri   label_changesnum_deletionsrj   rk   rN   rO   rm   rn   ro   r   rp   rf   rg   rl   r	   rq   rr   rs   rt   )ru   rv   rw   rO   corrected_changesrW   ry   rz   rV   valuer^   r?   s              r@   _ChLabelForBucketz0LabelCommand._ChLabel.<locals>._ChLabelForBucket=  s   OOc
kk=sCn n
//
(
(
48H8H
H !..!%!?!?nnX7G,H "@ "J
1o '',;;N $ %K#&==1C1C#D%K !K)778IJ  $==NN85E*F  >  HO(77
!!zz../E/EFH*
 --(:(:;JC3*,3#JsO	 <
 *77
C#>Bm)00Go
oo!!#//"10=+.::*.	 " 1rB   FT)r   r   sub_optssplitr~   r   RaiseInvalidArgumentExceptionr   r   r<   r=   r   r   r   )r?   oalabel_split	val_splitr   r   r   r   r   r   s   `          r@   _ChLabelzLabelCommand._ChLabel   s   DD}}--$!Q9+""KMNOP P 0;1~$

[^
,$Yggcl)^q "ACDEF F #'$

Q




!


,
,
.%  & 
MO O  :11 ;11f LyyH
//1009k +
,- !,  3d8nDEE rB   c                 <   | j                  |dg      \  }}|j                  dk(  r1t        | j                  j	                  ||j                               y|j
                  r+t        t        j                  |j
                  d             yt        d|z         y)	z.Gets and prints the labels for a cloud bucket.rN   rP   rK   rL   T)pretty_printz%s has no label configuration.N)rj   rc   printrd   XmlPassThroughGetTaggingrN   r   rl   )r?   
bucket_arg
bucket_urlry   s       r@   _GetAndPrintLabelzLabelCommand._GetAndPrintLabel  s    "&"@"@8* #A #.JD T__55
z00 6 2 4 
		//0F0F=AC 	E 	/*<>rB   c           	         | j                   j                  d      }| j                  d       t        j                  | j
                         |dk(  r6t        j                  |g       | j                  | j                   d          y|dk(  r(t        j                  |g       | j                          y|dk(  r(t        j                  |g       | j                          yt        d	|d
| j                  d| j                  d      )z*Command entry point for the label command.r   T)
check_args)r   r   )subcommandsr   r    zInvalid subcommand "z
" for the z command.
See "gsutil help z".)r<   popParseSubOptsr   LogCommandParamsr   r   r   r   r   command_name)r?   action_subcommands     r@   
RunCommandzLabelCommand.RunCommand  s    		a(& dmm4E!,=+>?
TYYq\*  
e	#,=+>?
nn  
d	",=+>?
mmo
  d//1B1BDE ErB   N)"__name__
__module____qualname____doc__r
   CreateCommandSpec	_SYNOPSISr   r   XMLri   r   MakeNFileURLsArgument%MakeZeroOrMoreCloudBucketURLsArgumentMakeNCloudURLsArgumentcommand_specHelpSpec_DETAILED_HELP_TEXT_get_help_text_set_help_text_ch_help_text	help_specr   r   r   RepeatFlagTypeLISTDICTgcloud_storage_maprA   r   r   r   r   rT   rB   r@   r   r      sr   / +**!oo{'7'78 %% 4o33A6CoCCE 9/88;=FFFHJ,* g
D#) (

  N
 = (+&/&>&>&C&CE (+&/&>&>&C&CE	!8< 24=5@AFF]F~?rB   r   )7r   
__future__r   r   r   r   r   rf   r   rn   gslibr   gslib.cloud_apir   r	   gslib.commandr
   gslib.command_argumentr   gslib.cs_api_mapr   gslib.exceptionr   r   gslib.help_providerr   "gslib.third_party.storage_apitoolsr   rq   gslib.utilsr   gslib.utils.constantsr   r   gslib.utils.retry_utilr   gslib.utils.shim_utilr   r   gslib.utils.translation_helperr   _SET_SYNOPSIS_GET_SYNOPSIS_CH_SYNOPSIS_GET_DESCRIPTION_SET_DESCRIPTION_CH_DESCRIPTIONlstripr   _DESCRIPTIONr   r   r   r   r   rT   rB   r@   <module>r      s   C & %  '   	 
  1 ) ! 2 ( , 2 . W ! ( & ( 3 2 ;  &< ]11$77  &')/0	  ** -<< %Y= /?@/?@|_=S7 SrB   