-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquay.go
117 lines (92 loc) · 2.47 KB
/
quay.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
)
type quayTagsResponseTag struct {
Reversion bool `json:"reversion"`
StartTs *int32 `json:"start_ts"`
EndTs *int32 `json:"end_ts"`
Name string `json:"name"`
DockerImageID string `json:"docker_image_id"`
}
type quayTagsResponse struct {
HasAdditional bool `json:"has_additional"`
Page int32 `json:"page"`
Tags []quayTagsResponseTag
}
type errorQuayTagNotFound struct {
s string
}
func newErrorQuayTagNotFound(tag, org, image string) *errorQuayTagNotFound {
return &errorQuayTagNotFound{
s: fmt.Sprintf("Failed to find tag '%s' for image '%s/%s'", tag, org, image),
}
}
func (e *errorQuayTagNotFound) Error() string {
return e.s
}
func getImageTags(image, org, token string) ([]quayTagsResponseTag, error) {
var results []quayTagsResponseTag
for page := 1; ; page++ {
url := fmt.Sprintf("https://quay.io/api/v1/repository/%s/%s/tag/?page=%d", org, image, page)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, errors.New(resp.Status)
}
var apiResponse quayTagsResponse
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&apiResponse)
if err != nil {
return nil, err
}
results = append(results, apiResponse.Tags...)
if apiResponse.HasAdditional == false {
break
}
}
return results, nil
}
func getTagImage(image, org, tag, token string) (string, error) {
tags, err := getImageTags(image, org, token)
if err != nil {
return "", nil
}
for _, t := range tags {
if t.EndTs == nil && t.Name == tag {
return t.DockerImageID, nil
}
}
return "", newErrorQuayTagNotFound(tag, org, image)
}
func setTagImage(image, org, tag, imageID, token string) error {
url := fmt.Sprintf("https://quay.io/api/v1/repository/%s/%s/tag/%s", org, image, tag)
var jsonStr = fmt.Sprintf(`{"image":"%s"}`, imageID)
req, err := http.NewRequest("PUT", url, bytes.NewBuffer([]byte(jsonStr)))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 201 {
return errors.New(resp.Status)
}
return nil
}