generated from bep/golibtemplate
/
githubreleasedownloader.go
457 lines (412 loc) · 12 KB
/
githubreleasedownloader.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package githubreleasedownloader
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/bep/workers"
)
const tokenEnvVar = "GITHUB_TOKEN"
func New() (*Client, error) {
token := os.Getenv(tokenEnvVar)
if token == "" {
return nil, fmt.Errorf("no token found in %s", tokenEnvVar)
}
return &Client{
client: &http.Client{
Timeout: 60 * time.Second,
},
auth: "Bearer " + token,
}, nil
}
type Client struct {
client *http.Client
auth string
}
// GetRelease returns the release for the given owner, repo and tag.
// Note that this method will download the assets to calculate their sha256 checksums,
// so it can be slow for large assets etc.
func (c *Client) GetRelease(owner, repo, tag string) (Release, error) {
api := "https://api.github.com/repos/" + owner + "/" + repo + "/releases/tags/" + tag
resp, err := c.get(api)
if err != nil {
return Release{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return Release{}, fmt.Errorf("unexpected status code: %s", resp.Status)
}
var ri releaseInfo
if err := json.NewDecoder(resp.Body).Decode(&ri); err != nil {
return Release{}, err
}
release := Release{
TagName: ri.TagName,
TargetCommitish: ri.TargetCommitish,
Name: ri.Name,
Draft: ri.Draft,
Prerelease: ri.Prerelease,
CreatedAt: ri.CreatedAt,
PublishedAt: ri.PublishedAt,
}
// Speed up the sha256 calculation by doing it in parallel.
var assetsMu sync.Mutex
w := workers.New(runtime.NumCPU())
r, _ := w.Start(context.Background())
for _, a := range ri.Assets {
a := a
r.Run(func() error {
var sha256 string
resp, err := c.get(a.BrowserDownloadURL)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %s", resp.Status)
}
sha256, err = sha256sum(resp.Body)
if err != nil {
return err
}
assetsMu.Lock()
release.Assets = append(release.Assets, Asset{
Name: a.Name,
URL: a.BrowserDownloadURL,
Sha256: sha256,
ContentType: a.ContentType,
Size: a.Size,
})
assetsMu.Unlock()
return nil
})
}
if err := r.Wait(); err != nil {
return Release{}, err
}
sort.Slice(release.Assets, func(i, j int) bool {
return release.Assets[i].Name < release.Assets[j].Name
})
return release, nil
}
func sha256sum(r io.Reader) (string, error) {
h := sha256.New()
if _, err := io.Copy(h, r); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func (c *Client) get(url string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", c.auth)
return c.client.Do(req)
}
// Release represents a GitHub release.
type Release struct {
TagName string `json:"tag_name"`
TargetCommitish string `json:"target_commitish"`
Name string `json:"name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
CreatedAt time.Time `json:"created_at"`
PublishedAt time.Time `json:"published_at"`
Assets Assets `json:"assets"`
}
// Assets is a slice of Asset.
type Assets []Asset
// Filter returns a new Assets slice containing only the assets for which the
// given function returns true.
func (a Assets) Filter(f func(Asset) bool) Assets {
var filtered Assets
for _, asset := range a {
if f(asset) {
filtered = append(filtered, asset)
}
}
return filtered
}
// Asset represents a GitHub release asset.
type Asset struct {
// Name is the name of the asset.
Name string `json:"name"`
// URL is the URL to download the asset.
URL string `json:"url"`
// Sha256 is the sha256 checksum of the asset.
Sha256 string `json:"sha256"`
// ContentType is the content type of the asset.
ContentType string `json:"content_type"`
// Size is the size of the asset in bytes.
Size int `json:"size"`
}
// Generated by https://mholt.github.io/json-to-go/
type releaseInfo struct {
URL string `json:"url"`
AssetsURL string `json:"assets_url"`
UploadURL string `json:"upload_url"`
HTMLURL string `json:"html_url"`
ID int `json:"id"`
Author struct {
Login string `json:"login"`
ID int `json:"id"`
NodeID string `json:"node_id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"author"`
NodeID string `json:"node_id"`
TagName string `json:"tag_name"`
TargetCommitish string `json:"target_commitish"`
Name string `json:"name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
CreatedAt time.Time `json:"created_at"`
PublishedAt time.Time `json:"published_at"`
Assets []struct {
URL string `json:"url"`
ID int `json:"id"`
NodeID string `json:"node_id"`
Name string `json:"name"`
Label string `json:"label"`
Uploader struct {
Login string `json:"login"`
ID int `json:"id"`
NodeID string `json:"node_id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"uploader"`
ContentType string `json:"content_type"`
State string `json:"state"`
Size int `json:"size"`
DownloadCount int `json:"download_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
BrowserDownloadURL string `json:"browser_download_url"`
} `json:"assets"`
TarballURL string `json:"tarball_url"`
ZipballURL string `json:"zipball_url"`
Body string `json:"body"`
Reactions struct {
URL string `json:"url"`
TotalCount int `json:"total_count"`
Num1 int `json:"+1"`
Num10 int `json:"-1"`
Laugh int `json:"laugh"`
Hooray int `json:"hooray"`
Confused int `json:"confused"`
Heart int `json:"heart"`
Rocket int `json:"rocket"`
Eyes int `json:"eyes"`
} `json:"reactions"`
MentionsCount int `json:"mentions_count"`
}
type (
DownloadAssetOptions struct {
TargetBaseDir string
ExtractToSubDirectory bool
ExtractFilter func(filename string, isDir bool) bool
}
DownloadAssetsResult struct {
TargetDir string
}
)
// DownloadAndExtractAsset downloads and extracts the given asset to the given directory.
// If the SHA256 checksum of the downloaded file does not match the one stored
// in the asset, an error is returned.
func DownloadAndExtractAsset(asset Asset, opts DownloadAssetOptions) (DownloadAssetsResult, error) {
var res DownloadAssetsResult
checksumFilename := strings.ReplaceAll(asset.Name, ".", "_") + "_" + asset.Sha256
targetDir := opts.TargetBaseDir
if opts.ExtractToSubDirectory {
targetDir = filepath.Join(targetDir, checksumFilename)
}
extractFilter := opts.ExtractFilter
if extractFilter == nil {
extractFilter = func(filename string, isDir bool) bool {
return true
}
}
res.TargetDir = targetDir
// Check if the asset has already been downloaded.
if opts.ExtractToSubDirectory {
if _, err := os.Stat(targetDir); err == nil {
return res, nil
}
} else {
if _, err := os.Stat(filepath.Join(targetDir, checksumFilename)); err == nil {
return res, nil
}
}
resp, err := http.Get(asset.URL)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return res, fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
// Write archive to a temporary file.
tmp, err := os.CreateTemp("", "*"+asset.Name)
if err != nil {
return res, err
}
defer tmp.Close()
defer os.Remove(tmp.Name())
h := sha256.New()
w := io.MultiWriter(tmp, h)
_, err = io.Copy(w, resp.Body)
if err != nil {
return res, err
}
// Compare the sha256 checksum of the downloaded file with the one stored.
if hex.EncodeToString(h.Sum(nil)) != asset.Sha256 {
return res, fmt.Errorf("sha256 checksum mismatch")
}
// Extract archive.
if err := extractArchive(tmp.Name(), targetDir, extractFilter); err != nil {
return res, err
}
if !opts.ExtractToSubDirectory {
// Create checksum file.
f, err := os.Create(filepath.Join(targetDir, checksumFilename))
if err != nil {
return res, err
}
defer f.Close()
}
return res, nil
}
// extractArchive extracts the given archive to the given directory.
func extractArchive(archive, dir string, filter func(filename string, isDir bool) bool) error {
if strings.HasSuffix(archive, ".zip") {
return extractZip(archive, dir, filter)
}
if strings.HasSuffix(archive, ".tar.gz") || strings.HasSuffix(archive, ".tgz") {
return extractTarGz(archive, dir, filter)
}
return fmt.Errorf("unsupported archive format: %s", archive)
}
func extractZip(archiveFilename, dir string, filter func(filename string, isDir bool) bool) error {
archive, err := zip.OpenReader(archiveFilename)
if err != nil {
return err
}
for _, f := range archive.File {
isDir := f.FileInfo().IsDir()
filename := filepath.Join(dir, f.Name)
if !filter(filename, isDir) {
continue
}
if isDir {
if err := os.MkdirAll(filename, os.ModePerm); err != nil {
return err
}
continue
}
if err := os.MkdirAll(filepath.Dir(filename), os.ModePerm); err != nil {
return err
}
if err := func() error {
dst, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(f.Mode()))
if err != nil {
return err
}
src, err := f.Open()
if err != nil {
return err
}
defer src.Close()
defer dst.Close()
_, err = io.Copy(dst, src)
return err
}(); err != nil {
return err
}
}
return nil
}
func extractTarGz(filename, dir string, filter func(filename string, isDir bool) bool) error {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
gzr, err := gzip.NewReader(f)
if err != nil {
return err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
filename := filepath.Join(dir, hdr.Name)
if !filter(filename, hdr.Typeflag == tar.TypeDir) {
continue
}
switch hdr.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(filename, os.ModePerm); err != nil {
return err
}
case tar.TypeReg:
if err := os.MkdirAll(filepath.Dir(filename), os.ModePerm); err != nil {
return err
}
dst, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, os.FileMode(hdr.Mode))
if err != nil {
return err
}
defer dst.Close()
if _, err := io.Copy(dst, tr); err != nil {
return err
}
}
}
return nil
}