/
bucket_collector.go
102 lines (91 loc) · 2.53 KB
/
bucket_collector.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package collector
import (
"context"
"github.com/jenkins-x/jx/pkg/util"
"github.com/pkg/errors"
"gocloud.dev/blob"
"io/ioutil"
"path/filepath"
"time"
)
// BucketCollector stores the state for the git collector
type BucketCollector struct {
Timeout time.Duration
bucketURL string
bucket *blob.Bucket
classifier string
}
// NewBucketCollector creates a new git based collector
func NewBucketCollector(bucketURL string, bucket *blob.Bucket, classifier string) (Collector, error) {
return &BucketCollector{
Timeout: time.Second * 20,
bucketURL: bucketURL,
bucket: bucket,
classifier: classifier,
}, nil
}
// CollectFiles collects files and returns the URLs
func (c *BucketCollector) CollectFiles(patterns []string, outputPath string, basedir string) ([]string, error) {
urls := []string{}
bucket := c.bucket
ctx := c.createContext()
for _, p := range patterns {
fn := func(name string) error {
var err error
toName := name
if basedir != "" {
toName, err = filepath.Rel(basedir, name)
if err != nil {
return errors.Wrapf(err, "failed to remove basedir %s from %s", basedir, name)
}
}
if outputPath != "" {
toName = filepath.Join(outputPath, toName)
}
data, err := ioutil.ReadFile(name)
if err != nil {
return errors.Wrapf(err, "failed to read file %s", name)
}
opts := &blob.WriterOptions{
ContentType: util.ContentTypeForFileName(name),
Metadata: map[string]string{
"classification": c.classifier,
},
}
err = bucket.WriteAll(ctx, toName, data, opts)
if err != nil {
return errors.Wrapf(err, "failed to write to bucket %s", toName)
}
u := util.UrlJoin(c.bucketURL, toName)
urls = append(urls, u)
return nil
}
err := util.GlobAllFiles("", p, fn)
if err != nil {
return urls, err
}
}
return urls, nil
}
// CollectData collects the data storing it at the given output path and returning the URL
// to access it
func (c *BucketCollector) CollectData(data []byte, outputName string) (string, error) {
opts := &blob.WriterOptions{
ContentType: util.ContentTypeForFileName(outputName),
Metadata: map[string]string{
"classification": c.classifier,
},
}
u := ""
ctx := c.createContext()
err := c.bucket.WriteAll(ctx, outputName, data, opts)
if err != nil {
return u, errors.Wrapf(err, "failed to write to bucket %s", outputName)
}
u = util.UrlJoin(c.bucketURL, outputName)
return u, nil
}
func (c *BucketCollector) createContext() context.Context {
ctx, _ := context.WithTimeout(context.Background(), c.Timeout)
return ctx
}