forked from gptscript-ai/gptscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgolang.go
371 lines (305 loc) · 8.39 KB
/
golang.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
package golang
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/gptscript-ai/gptscript/pkg/credentials"
"github.com/gptscript-ai/gptscript/pkg/debugcmd"
runtimeEnv "github.com/gptscript-ai/gptscript/pkg/env"
"github.com/gptscript-ai/gptscript/pkg/hash"
"github.com/gptscript-ai/gptscript/pkg/repos/download"
"github.com/gptscript-ai/gptscript/pkg/types"
)
//go:embed digests.txt
var releasesData []byte
const downloadURL = "https://go.dev/dl/"
type Runtime struct {
// version something like "1.22.1"
Version string
}
func (r *Runtime) ID() string {
return "go" + r.Version
}
func (r *Runtime) GetHash(_ types.Tool) (string, error) {
return "", nil
}
func (r *Runtime) Supports(tool types.Tool, cmd []string) bool {
return tool.Source.IsGit() &&
len(cmd) > 0 && cmd[0] == "${GPTSCRIPT_TOOL_DIR}/bin/gptscript-go-tool"
}
type release struct {
account, repo, label string
}
func (r release) checksumTxt() string {
return fmt.Sprintf(
"https://github.com/%s/%s/releases/download/%s/checksums.txt",
r.account,
r.repo,
r.label)
}
func (r release) binURL() string {
return fmt.Sprintf(
"https://github.com/%s/%s/releases/download/%s/%s",
r.account,
r.repo,
r.label,
r.srcBinName())
}
func (r release) targetBinName() string {
suffix := ""
if runtime.GOOS == "windows" {
suffix = ".exe"
}
return "gptscript-go-tool" + suffix
}
func (r release) srcBinName() string {
suffix := ""
if runtime.GOOS == "windows" {
suffix = ".exe"
}
return r.repo + "-" +
runtime.GOOS + "-" +
runtime.GOARCH + suffix
}
type tag struct {
Name string `json:"name,omitempty"`
Commit struct {
Sha string `json:"sha,omitempty"`
} `json:"commit"`
}
func getLatestRelease(tool types.Tool) (*release, bool) {
if tool.Source.Repo == nil || !strings.HasPrefix(tool.Source.Repo.Root, "https://github.com/") {
return nil, false
}
parts := strings.Split(strings.TrimPrefix(strings.TrimSuffix(tool.Source.Repo.Root, ".git"), "https://"), "/")
if len(parts) != 3 {
return nil, false
}
client := http.Client{
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
},
}
account, repo := parts[1], parts[2]
resp, err := client.Get(fmt.Sprintf("https://api.github.com/repos/%s/%s/tags", account, repo))
if err != nil || resp.StatusCode != http.StatusOK {
// ignore error
return nil, false
}
defer resp.Body.Close()
var tags []tag
if err := json.NewDecoder(resp.Body).Decode(&tags); err != nil {
return nil, false
}
for _, tag := range tags {
if tag.Commit.Sha == tool.Source.Repo.Revision {
return &release{
account: account,
repo: repo,
label: tag.Name,
}, true
}
}
resp, err = client.Get(fmt.Sprintf("https://github.com/%s/%s/releases/latest", account, repo))
if err != nil || resp.StatusCode != http.StatusFound {
// ignore error
return nil, false
}
defer resp.Body.Close()
target := resp.Header.Get("Location")
if target == "" {
return nil, false
}
parts = strings.Split(target, "/")
label := parts[len(parts)-1]
return &release{
account: account,
repo: repo,
label: label,
}, true
}
func get(ctx context.Context, url string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
} else if resp.StatusCode != http.StatusOK {
_ = resp.Body.Close()
return nil, fmt.Errorf("bad HTTP status code: %d", resp.StatusCode)
}
return resp, nil
}
func downloadBin(ctx context.Context, checksum, src, url, bin string) error {
resp, err := get(ctx, url)
if err != nil {
return err
}
defer resp.Body.Close()
if err := os.MkdirAll(filepath.Join(src, "bin"), 0755); err != nil {
return err
}
targetFile, err := os.Create(filepath.Join(src, "bin", bin))
if err != nil {
return err
}
digest := sha256.New()
if _, err := io.Copy(io.MultiWriter(targetFile, digest), resp.Body); err != nil {
return err
}
if err := targetFile.Close(); err != nil {
return nil
}
if got := hex.EncodeToString(digest.Sum(nil)); got != checksum {
return fmt.Errorf("checksum mismatch %s != %s", got, checksum)
}
if err := os.Chmod(targetFile.Name(), 0755); err != nil {
return err
}
return nil
}
func getChecksum(ctx context.Context, rel *release) string {
resp, err := get(ctx, rel.checksumTxt())
if err != nil {
// ignore error
return ""
}
defer resp.Body.Close()
scan := bufio.NewScanner(resp.Body)
for scan.Scan() {
fields := strings.Fields(scan.Text())
if len(fields) != 2 || fields[1] != rel.srcBinName() {
continue
}
return fields[0]
}
return ""
}
func (r *Runtime) Binary(ctx context.Context, tool types.Tool, _, toolSource string, env []string) (bool, []string, error) {
if !tool.Source.IsGit() {
return false, nil, nil
}
rel, ok := getLatestRelease(tool)
if !ok {
return false, nil, nil
}
checksum := getChecksum(ctx, rel)
if checksum == "" {
return false, nil, nil
}
if err := downloadBin(ctx, checksum, toolSource, rel.binURL(), rel.targetBinName()); err != nil {
// ignore error
return false, nil, nil
}
return true, env, nil
}
func (r *Runtime) Setup(ctx context.Context, _ types.Tool, dataRoot, toolSource string, env []string) ([]string, error) {
binPath, err := r.getRuntime(ctx, dataRoot)
if err != nil {
return nil, err
}
newEnv := runtimeEnv.AppendPath(env, binPath)
if err := r.runBuild(ctx, toolSource, binPath, append(env, newEnv...)); err != nil {
return nil, err
}
return newEnv, nil
}
func (r *Runtime) BuildCredentialHelper(ctx context.Context, helperName string, credHelperDirs credentials.CredentialHelperDirs, dataRoot, revision string, env []string) error {
if helperName == "file" {
return nil
}
var suffix string
if helperName == "wincred" {
suffix = ".exe"
}
binPath, err := r.getRuntime(ctx, dataRoot)
if err != nil {
return err
}
newEnv := runtimeEnv.AppendPath(env, binPath)
log.InfofCtx(ctx, "Building credential helper %s", helperName)
cmd := debugcmd.New(ctx, filepath.Join(binPath, "go"),
"build", "-buildvcs=false", "-o",
filepath.Join(credHelperDirs.BinDir, "gptscript-credential-"+helperName+suffix),
fmt.Sprintf("./%s/cmd/", helperName))
cmd.Env = stripGo(append(env, newEnv...))
cmd.Dir = filepath.Join(credHelperDirs.RepoDir, revision)
return cmd.Run()
}
func (r *Runtime) getReleaseAndDigest() (string, string, error) {
scanner := bufio.NewScanner(bytes.NewReader(releasesData))
key := r.ID() + "." + runtime.GOOS + "-" + runtime.GOARCH
for scanner.Scan() {
line := strings.Split(scanner.Text(), " ")
file, digest := strings.TrimSpace(line[1]), strings.TrimSpace(line[0])
if strings.HasPrefix(file, key) {
return downloadURL + file, digest, nil
}
}
return "", "", fmt.Errorf("failed to find %s release for os=%s arch=%s", r.ID(), runtime.GOOS, runtime.GOARCH)
}
func stripGo(env []string) (result []string) {
for _, env := range env {
if strings.HasPrefix(env, "GO") {
continue
}
result = append(result, env)
}
return
}
func (r *Runtime) runBuild(ctx context.Context, toolSource, binDir string, env []string) error {
log.InfofCtx(ctx, "Running go build in %s", toolSource)
cmd := debugcmd.New(ctx, filepath.Join(binDir, "go"), "build", "-buildvcs=false", "-o", artifactName())
cmd.Env = stripGo(env)
cmd.Dir = toolSource
return cmd.Run()
}
func artifactName() string {
if runtime.GOOS == "windows" {
return filepath.Join("bin", "gptscript-go-tool.exe")
}
return filepath.Join("bin", "gptscript-go-tool")
}
func (r *Runtime) binDir(rel string) string {
return filepath.Join(rel, "go", "bin")
}
func (r *Runtime) getRuntime(ctx context.Context, cwd string) (string, error) {
url, sha, err := r.getReleaseAndDigest()
if err != nil {
return "", err
}
target := filepath.Join(cwd, "golang", hash.ID(url, sha))
if _, err := os.Stat(target); err == nil {
return r.binDir(target), nil
} else if !errors.Is(err, fs.ErrNotExist) {
return "", err
}
log.InfofCtx(ctx, "Downloading Go %s", r.Version)
tmp := target + ".download"
defer os.RemoveAll(tmp)
if err := os.MkdirAll(tmp, 0755); err != nil {
return "", err
}
if err := download.Extract(ctx, url, sha, tmp); err != nil {
return "", err
}
if err := os.Rename(tmp, target); err != nil {
return "", err
}
return r.binDir(target), nil
}