Repository navigation
Expand file tree
/
Copy pathhandler_execute.go
More file actions
265 lines (257 loc) · 6.81 KB
/
Copy pathhandler_execute.go
File metadata and controls
265 lines (257 loc) · 6.81 KB
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
package handler
import (
"bufio"
"errors"
"fmt"
"log"
"net/http"
"sort"
"strings"
"time"
)
func (h *Handler) execute(q Query) (Result, error) {
//load from cache
key := q.cacheKey()
h.cacheMut.Lock()
if h.cache == nil {
h.cache = map[string]Result{}
}
cached, ok := h.cache[key]
h.cacheMut.Unlock()
//cache hit
if ok && time.Since(cached.Timestamp) < cacheTTL {
return cached, nil
}
//do real operation
ts := time.Now()
release, assets, err := h.getAssetsNoCache(q)
if err == nil {
//didn't need search
q.Search = false
} else if errors.Is(err, errNotFound) && q.Search {
//use ddg/google to auto-detect user...
user, program, gerr := imFeelingLuck(q.Program)
if gerr != nil {
log.Printf("web search failed: %s", gerr)
} else {
log.Printf("web search found: %s/%s", user, program)
if program != q.Program {
log.Printf("program mismatch: got %s: expected %s", q.Program, program)
}
q.Program = program
q.User = user
//retry assets...
release, assets, err = h.getAssetsNoCache(q)
}
}
//asset fetch failed, dont cache
if err != nil {
return Result{}, err
}
//success
if q.Release == "" && release != "" {
log.Printf("detected release: %s", release)
q.Release = release
}
result := Result{
Timestamp: ts,
Query: q,
ResolvedRelease: release,
Assets: assets,
M1Asset: assets.HasM1(),
}
//success store results
h.cacheMut.Lock()
h.cache[key] = result
h.cacheMut.Unlock()
return result, nil
}
func (h *Handler) getAssetsNoCache(q Query) (string, Assets, error) {
user := q.User
repo := q.Program
release := q.Release
//not cached - ask github
log.Printf("fetching asset info for %s/%s@%s", user, repo, release)
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases", user, repo)
ghas := ghAssets{}
if release == "" || release == "latest" {
url += "/latest"
ghr := ghRelease{}
if err := h.get(url, &ghr); err != nil {
return release, nil, err
}
release = ghr.TagName //discovered
ghas = ghr.Assets
} else {
ghrs := []ghRelease{}
if err := h.get(url, &ghrs); err != nil {
return release, nil, err
}
found := false
for _, ghr := range ghrs {
if ghr.TagName == release {
found = true
if err := h.get(ghr.AssetsURL, &ghas); err != nil {
return release, nil, err
}
ghas = ghr.Assets
break
}
}
if !found {
return release, nil, fmt.Errorf("release tag '%s' not found", release)
}
}
if len(ghas) == 0 {
return release, nil, errors.New("no assets found")
}
sumIndex, _ := ghas.getSumIndex()
if l := len(sumIndex); l > 0 {
log.Printf("fetched %d asset shasums", l)
}
index := map[string]Asset{}
for _, ga := range ghas {
url := ga.BrowserDownloadURL
//only binary containers are supported
//TODO deb,rpm etc
fext := getFileExt(url)
if fext == "" && ga.Size > 1024*1024 {
fext = ".bin" // +1MB binary
}
switch fext {
case ".bin", ".zip", ".tar.bz", ".tar.bz2", ".bz2", ".gz", ".tar.gz", ".tgz":
// valid
default:
log.Printf("fetched asset has unsupported file type: %s (ext '%s')", ga.Name, fext)
continue
}
//match
os := getOS(ga.Name)
arch := getArch(ga.Name)
//windows not supported yet
if os == "windows" {
log.Printf("fetched asset is for windows: %s", ga.Name)
//TODO: powershell
// EG: iwr https://deno.land/x/install/install.ps1 -useb | iex
continue
}
//unknown os, cant use
if os == "" {
log.Printf("fetched asset has unknown os: %s", ga.Name)
continue
}
// user selecting a particular asset?
if q.Select != "" && !strings.Contains(ga.Name, q.Select) {
log.Printf("select excludes asset: %s", ga.Name)
continue
}
asset := Asset{
OS: os,
Arch: arch,
Name: ga.Name,
URL: url,
Type: fext,
SHA256: sumIndex[ga.Name],
}
//there can only be 1 file for each OS/Arch
key := asset.Key()
other, exists := index[key]
if exists {
gnu := func(s string) bool { return strings.Contains(s, "gnu") }
musl := func(s string) bool { return strings.Contains(s, "musl") }
g2m := gnu(other.Name) && !musl(other.Name) && !gnu(asset.Name) && musl(asset.Name)
// prefer musl over glib for portability, override with select=gnu
if !g2m {
continue
}
}
index[key] = asset
}
if len(index) == 0 {
return release, nil, errors.New("no downloads found for this release")
}
assets := Assets{}
for _, a := range index {
log.Printf("including asset: %s (%s)", a.Name, a.Key())
assets = append(assets, a)
}
sort.Slice(assets, func(i, j int) bool {
return assets[i].Key() < assets[j].Key()
})
return release, assets, nil
}
type ghAssets []ghAsset
func (as ghAssets) getSumIndex() (map[string]string, error) {
url := ""
for _, ga := range as {
//is checksum file?
if ga.IsChecksumFile() {
url = ga.BrowserDownloadURL
break
}
}
if url == "" {
return nil, errors.New("no sum file found")
}
resp, err := http.DefaultClient.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// take each line and insert into the index
index := map[string]string{}
s := bufio.NewScanner(resp.Body)
for s.Scan() {
fs := strings.Fields(s.Text())
if len(fs) != 2 {
continue
}
index[fs[1]] = fs[0]
}
if err := s.Err(); err != nil {
return nil, err
}
return index, nil
}
type ghAsset struct {
BrowserDownloadURL string `json:"browser_download_url"`
ContentType string `json:"content_type"`
CreatedAt string `json:"created_at"`
DownloadCount int `json:"download_count"`
ID int `json:"id"`
Label string `json:"label"`
Name string `json:"name"`
Size int `json:"size"`
State string `json:"state"`
UpdatedAt string `json:"updated_at"`
Uploader struct {
ID int `json:"id"`
Login string `json:"login"`
} `json:"uploader"`
URL string `json:"url"`
}
func (g ghAsset) IsChecksumFile() bool {
return checksumRe.MatchString(strings.ToLower(g.Name)) && g.Size < 64*1024 //maximum file size 64KB
}
type ghRelease struct {
Assets []ghAsset `json:"assets"`
AssetsURL string `json:"assets_url"`
Author struct {
ID int `json:"id"`
Login string `json:"login"`
} `json:"author"`
Body string `json:"body"`
CreatedAt string `json:"created_at"`
Draft bool `json:"draft"`
HTMLURL string `json:"html_url"`
ID int `json:"id"`
Name interface{} `json:"name"`
Prerelease bool `json:"prerelease"`
PublishedAt string `json:"published_at"`
TagName string `json:"tag_name"`
TarballURL string `json:"tarball_url"`
TargetCommitish string `json:"target_commitish"`
UploadURL string `json:"upload_url"`
URL string `json:"url"`
ZipballURL string `json:"zipball_url"`
}