-
Notifications
You must be signed in to change notification settings - Fork 2
/
google.go
81 lines (65 loc) · 1.72 KB
/
google.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"context"
"fmt"
"cloud.google.com/go/storage"
"github.com/Sirupsen/logrus"
"github.com/spf13/cobra"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
var jsonCredsFile string
func GoogleCmd() *cobra.Command {
gcsCmd := &cobra.Command{
Use: "google",
Short: "google <project_id>",
Run: uploadToGoogle,
}
gcsCmd.Flags().StringVarP(&jsonCredsFile, "auth", "a", "", "the service role json config file")
return gcsCmd
}
func uploadToGoogle(_ *cobra.Command, args []string) {
if len(args) != 1 {
logrus.Fatal("Must provide the project id to use")
}
opts := []option.ClientOption{}
if jsonCredsFile != "" {
opts = append(opts, option.WithServiceAccountFile(jsonCredsFile))
}
projectID := args[0]
ctx := context.Background()
client, err := storage.NewClient(ctx, opts...)
if err != nil {
logrus.WithError(err).Fatal("Failed to configure storage client")
}
logrus.Debug("Connected to google API")
logrus.Debug("Listing out buckets")
found := false
iter := client.Buckets(ctx, projectID)
iter.Prefix = bucket
for b, err := iter.Next(); err != iterator.Done && err == nil; b, err = iter.Next() {
if b.Name == bucket {
found = true
break
}
}
if err != nil && err != iterator.Done {
logrus.WithError(err).Fatal("Failed to walk buckets")
}
b := client.Bucket(bucket)
if !found {
if err := b.Create(ctx, projectID, nil); err != nil {
logrus.WithError(err).Fatalf("Failed to create bucket %s in project %s", bucket, projectID)
}
}
runTest(func(key string, data []byte) {
obj := b.Object(key)
w := obj.NewWriter(ctx)
if _, err := fmt.Fprintf(w, string(data)); err != nil {
panic(err)
}
if err := w.Close(); err != nil {
panic(err)
}
})
}