# -*- coding: utf-8 -*-"""Tagging related API."""importtypingasTfromfunc_argsimportNOTHINGfrom..importexcfrom..better_client.head_bucketimportis_bucket_existsfrom..better_client.head_objectimporthead_objectfrom..awsimportcontextfrom.resolve_s3_clientimportresolve_s3_clientifT.TYPE_CHECKING:# pragma: no coverfrom.s3pathimportS3Pathfromboto_session_managerimportBotoSesManagerfrommypy_boto3_s3importS3Client
[docs]classExistsAPIMixin:""" A mixin class that implements the exists test related methods. """
[docs]defexists(self:"S3Path",version_id:str=NOTHING,bsm:T.Optional[T.Union["BotoSesManager","S3Client"]]=None,)->bool:""" Test if an S3Path object actually exists in S3 bucket. - For S3 bucket: check if the bucket exists. If you don't have the access, then it raise exception. - For S3 object: check if the object exists - For S3 directory: check if the directory exists, it returns ``True`` even if the folder doesn't have any object. - For versioning enabled bucket, you can explicitly check if a specific version exists, otherwise it will check the latest version. Example: >>> S3Path("bucket").exists() >>> S3Path("bucket/file.txt").exists() >>> S3Path("bucket/folder/").exists() >>> S3Path("bucket/file.txt").exists(version_id="v123456") .. versionadded:: 1.0.1 .. versionchanged:: 2.0.1 Add ``version_id`` parameter. """ifself.is_bucket():s3_client=resolve_s3_client(context,bsm)returnis_bucket_exists(s3_client,self.bucket)elifself.is_file():s3_client=resolve_s3_client(context,bsm)dct=head_object(s3_client=s3_client,bucket=self.bucket,key=self.key,version_id=version_id,ignore_not_found=True,)ifdctisNone:returnFalseelse:if"ResponseMetadata"indct:deldct["ResponseMetadata"]self._meta=dctreturnTrueelifself.is_dir():l=list(self.iterdir(batch_size=1,limit=1,bsm=bsm,))iflen(l):returnTrueelse:returnFalseelse:# pragma: no coverraiseTypeError
[docs]defensure_not_exists(self:"S3Path",version_id:str=NOTHING,bsm:T.Optional[T.Union["BotoSesManager","S3Client"]]=None,)->None:""" A validator method ensure that it doesn't exists. .. versionadded:: 1.0.1 .. versionchanged:: 2.0.1 Add ``version_id`` parameter. """ifself.exists(version_id=version_id,bsm=bsm):raiseexc.S3AlreadyExist(("cannot write to {}, s3 object ALREADY EXISTS! ""open console for more details {}.").format(self.uri,self.console_url))