github.com/GoogleContainerTools/kaniko@v1.23.0/pkg/util/bucket/bucket_util.go (about) 1 /* 2 Copyright 2018 Google LLC 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package bucket 18 19 import ( 20 "context" 21 "fmt" 22 "io" 23 "net/url" 24 "strings" 25 26 "cloud.google.com/go/storage" 27 "github.com/GoogleContainerTools/kaniko/pkg/constants" 28 "google.golang.org/api/option" 29 ) 30 31 // Upload uploads everything from Reader to the bucket under path 32 func Upload(ctx context.Context, bucketName string, path string, r io.Reader, client *storage.Client) error { 33 bucket := client.Bucket(bucketName) 34 w := bucket.Object(path).NewWriter(ctx) 35 if _, err := io.Copy(w, r); err != nil { 36 return err 37 } 38 if err := w.Close(); err != nil { 39 return err 40 } 41 return nil 42 } 43 44 // Delete will remove the content at path. path should be the full path 45 // to a file in GCS. 46 func Delete(ctx context.Context, bucketName string, path string, client *storage.Client) error { 47 err := client.Bucket(bucketName).Object(path).Delete(ctx) 48 if err != nil { 49 return fmt.Errorf("failed to delete file at %s in gcs bucket %v: %w", path, bucketName, err) 50 } 51 return err 52 } 53 54 // ReadCloser will create io.ReadCloser for the specified bucket and path 55 func ReadCloser(ctx context.Context, bucketName string, path string, client *storage.Client) (io.ReadCloser, error) { 56 bucket := client.Bucket(bucketName) 57 r, err := bucket.Object(path).NewReader(ctx) 58 if err != nil { 59 return nil, err 60 } 61 return r, nil 62 } 63 64 // NewClient returns a new google storage client 65 func NewClient(ctx context.Context, opts ...option.ClientOption) (*storage.Client, error) { 66 client, err := storage.NewClient(ctx, opts...) 67 if err != nil { 68 return nil, err 69 } 70 return client, err 71 } 72 73 // GetNameAndFilepathFromURI returns the bucketname and the path to the item inside. 74 // Will error if provided URI is not a valid URL. 75 // If the filepath is empty, returns the contextTar filename 76 func GetNameAndFilepathFromURI(bucketURI string) (bucketName string, path string, err error) { 77 url, err := url.Parse(bucketURI) 78 if err != nil { 79 return "", "", err 80 } 81 bucketName = url.Host 82 // remove leading slash 83 filePath := strings.TrimPrefix(url.Path, "/") 84 if filePath == "" { 85 filePath = constants.ContextTar 86 } 87 return bucketName, filePath, nil 88 }