github.com/kubernetes-incubator/kube-aws@v0.16.4/cfnstack/s3_uri.go (about)

     1  package cfnstack
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strings"
     7  )
     8  
     9  type S3URI interface {
    10  	Bucket() string
    11  	KeyComponents() []string
    12  	BucketAndKey() string
    13  	String() string
    14  }
    15  
    16  type s3URIImpl struct {
    17  	bucket    string
    18  	directory string
    19  }
    20  
    21  func (u s3URIImpl) Bucket() string {
    22  	return u.bucket
    23  }
    24  
    25  func (u s3URIImpl) KeyComponents() []string {
    26  	if u.directory != "" {
    27  		return []string{
    28  			u.directory,
    29  		}
    30  	}
    31  	return []string{}
    32  }
    33  
    34  func (u s3URIImpl) BucketAndKey() string {
    35  	components := []string{}
    36  	path := u.KeyComponents()
    37  	components = append(components, u.bucket)
    38  	components = append(components, path...)
    39  	return strings.Join(components, "/")
    40  }
    41  
    42  func (u s3URIImpl) String() string {
    43  	return fmt.Sprintf("s3://%s", u.BucketAndKey())
    44  }
    45  
    46  func S3URIFromString(s3URI string) (S3URI, error) {
    47  	re := regexp.MustCompile("s3://(?P<bucket>[^/]+)/(?P<directory>.+[^/])/*$")
    48  	matches := re.FindStringSubmatch(s3URI)
    49  	var bucket string
    50  	var directory string
    51  	if len(matches) == 3 {
    52  		bucket = matches[1]
    53  		directory = matches[2]
    54  	} else {
    55  		re := regexp.MustCompile("s3://(?P<bucket>[^/]+)/*$")
    56  		matches := re.FindStringSubmatch(s3URI)
    57  
    58  		if len(matches) == 2 {
    59  			bucket = matches[1]
    60  		} else {
    61  			return nil, fmt.Errorf("failed to parse s3 uri(=%s): The valid uri pattern for it is s3://mybucket/mydir or s3://mybucket", s3URI)
    62  		}
    63  	}
    64  	return s3URIImpl{
    65  		bucket:    bucket,
    66  		directory: directory,
    67  	}, nil
    68  }