-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.go
111 lines (96 loc) · 2.19 KB
/
util.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
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/google/go-github/v29/github"
"github.com/pkg/errors"
)
func download(urs string) (string, error) {
ur, err := url.Parse(urs)
if err != nil {
return "", err
}
path := filepath.Join(os.TempDir(), filepath.Base(ur.Path))
log.Printf("Downloading %s to %s\n", urs, path)
resp, err := http.Get(urs)
if err != nil {
return "", err
}
defer resp.Body.Close()
out, err := os.Create(path)
if err != nil {
return "", err
}
defer out.Close()
if resp.StatusCode != 200 {
return "", errors.Errorf("http status %d", resp.StatusCode)
}
_, err = io.Copy(out, resp.Body)
return path, err
}
func sha256FileToHex(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, f); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
func downloadCalculateHash(url string) (string, error) {
path, err := download(url)
if err != nil {
return "", err
}
defer func() { _ = os.Remove(path) }()
log.Printf("Calculating sha256...\n")
sha256, err := sha256FileToHex(path)
if err != nil {
return "", err
}
log.Printf("Calculated sha256: %s\n", sha256)
return sha256, nil
}
func updateRepo(owner string, repo string, file string, data []byte, version string) error {
ctx := context.Background()
client, err := newGithubClient(ctx)
if err != nil {
return err
}
log.Printf("Updating repo...\n")
content, _, _, err := client.Repositories.GetContents(ctx, owner, repo, file, &github.RepositoryContentGetOptions{})
if err != nil {
return err
}
b, err := base64.StdEncoding.DecodeString(*content.Content)
if err != nil {
return err
}
if bytes.Equal(b, data) {
log.Printf("Content already exists")
return nil
}
msg := fmt.Sprintf("Update %s (%s)", file, version)
opts := &github.RepositoryContentFileOptions{
Message: &msg,
Content: data,
SHA: content.SHA,
}
if _, _, err := client.Repositories.UpdateFile(ctx, owner, repo, file, opts); err != nil {
return err
}
return nil
}