-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmain.go
91 lines (78 loc) · 2.13 KB
/
main.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"regexp"
"sort"
"syscall"
"cloud.google.com/go/storage"
"github.com/maruel/natural"
"golang.org/x/exp/maps"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
var versionRe = regexp.MustCompile(`.*-(\d+\.\d+\.\d+).*`)
func main() {
ctx, cancel := signal.NotifyContext(context.Background(),
syscall.SIGINT, syscall.SIGTERM)
defer cancel()
if err := realMain(ctx); err != nil {
cancel()
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
}
func realMain(ctx context.Context) error {
client, err := storage.NewClient(ctx, option.WithoutAuthentication())
if err != nil {
return fmt.Errorf("failed to create storage client: %w", err)
}
// Do server-side filtering to only return the linux builds and "Name"
// attribute. This dramatically reduces the response size and number of
// entries we need to process.
//
// At some point, the naming scheme changed, so we can't filter by a full glob
// or prefix.
var q storage.Query
q.MatchGlob = "*-linux-x86_64.tar.gz"
if err := q.SetAttrSelection([]string{"Name"}); err != nil {
return fmt.Errorf("failed to set attribute selection: %w", err)
}
var names []string
it := client.Bucket("cloud-sdk-release").Objects(ctx, &q)
for {
attrs, err := it.Next()
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
return fmt.Errorf("failed to get object: %w", err)
}
names = append(names, attrs.Name)
}
// De-duplicate. Even with just selecting linux, there are some duplicate
// versions.
versionsMap := make(map[string]struct{}, len(names))
for _, name := range names {
sub := versionRe.FindStringSubmatch(name)
if sub == nil || len(sub) < 2 {
// no match
continue
}
versionsMap[sub[1]] = struct{}{}
}
// Do a natural sort so that it looks good to humans instead of machines.
versions := maps.Keys(versionsMap)
sort.Sort(natural.StringSlice(versions))
// Print it out.
b, err := json.MarshalIndent(versions, "", " ")
if err != nil {
return fmt.Errorf("failed to create json: %w", err)
}
fmt.Fprintln(os.Stdout, string(b))
return nil
}