Repository navigation
Expand file tree
/
Copy pathhandler_execute.go
More file actions
343 lines (328 loc) · 9.31 KB
/
Copy pathhandler_execute.go
File metadata and controls
343 lines (328 loc) · 9.31 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
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
package handler
import (
"bufio"
"errors"
"fmt"
"log"
"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
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)
}
var (
candidates = map[string]Asset{}
index = map[string]Asset{}
foundLinuxAMD64 = false
)
for _, ga := range ghas {
url := ga.BrowserDownloadURL
// only binary containers are supported
// TODO deb,rpm etc
fext := getFileExt(url)
if fext == "" {
// Check if this looks like a binary by checking for OS and Arch patterns
// This handles assets like "joker_darwin_amd64" without extension
if getOS(ga.Name) != "" && getArch(ga.Name) != "" && ga.Size > 1024 {
fext = ".bin" // Likely a binary if it has OS/Arch in name and > 1KB
}
}
switch fext {
case ".bin", ".zip", ".tar.bz", ".tar.bz2", ".tar.xz", ".txz", ".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
}
// stop guessing for linux/amd64 assets when the exact match is found
if os == "linux" && arch == "amd64" {
foundLinuxAMD64 = true
}
assumedLinuxAsset := false
// unknown arch/os, the asset will be regarded as linux/amd64 if no other assets match
if os == "" {
assumedLinuxAsset = true
if arch == "" || arch == "amd64" {
if foundLinuxAMD64 {
continue
}
}
}
if arch == "" {
arch = "amd64"
if os == "linux" {
assumedLinuxAsset = true
}
}
// 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],
Size: ga.Size,
}
key := asset.Key()
// "linux/", "/amd64" will all be assumed as "linux/amd64"
if assumedLinuxAsset {
// "linux/" always win.
if key == "linux/" {
delete(candidates, "/amd64")
foundLinuxAMD64 = true
// If key "linux/" exist,
// assets like "unknown-os-i386" would be ignored (stop guessing OS)
} else if _, exists := candidates["linux/"]; exists {
continue
}
candidates[key] = asset
continue
}
// there can only be 1 file for each OS/Arch
if other, exists := index[key]; 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 {
// If both are gnu or both are not gnu/musl, prefer the larger file (usually static build)
// This handles cases like joker_linux_amd64 (497KB static) vs joker_linux_amd64_gnu (39KB dynamic)
if (gnu(other.Name) == gnu(asset.Name)) && (musl(other.Name) == musl(asset.Name)) {
if ga.Size > other.Size {
log.Printf("preferring larger asset %s (%d bytes) over %s (%d bytes) for %s",
ga.Name, ga.Size, other.Name, other.Size, key)
} else {
log.Printf("skipping smaller asset %s (%d bytes), keeping %s (%d bytes) for %s",
ga.Name, ga.Size, other.Name, other.Size, key)
continue
}
} else {
// Different gnu/musl status, prefer non-gnu (static) over gnu (dynamic)
if !gnu(other.Name) && gnu(asset.Name) {
log.Printf("skipping gnu asset %s, preferring static build %s for %s",
ga.Name, other.Name, key)
} else if gnu(other.Name) && !gnu(asset.Name) {
log.Printf("replacing gnu asset %s with static build %s for %s",
other.Name, ga.Name, key)
}
continue
}
}
}
index[key] = asset
}
for _, cAsset := range candidates {
// "/loong64" will be assumed to be "linux/loong64"
if cAsset.OS == "" {
cAsset.OS = "linux"
}
indexKey := cAsset.Key()
// and will only be selected if the exact match failed
if _, exists := index[indexKey]; !exists {
log.Printf("[DEBUG] Adding candidate asset: %s -> %s", cAsset.Name, indexKey)
index[indexKey] = cAsset
}
}
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 := httpGet(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("sum file request returned status: %s", resp.Status)
}
// 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 any `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"`
}