/
main.go
314 lines (284 loc) · 8.21 KB
/
main.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package main
import (
"crypto/sha512"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"text/tabwriter"
"github.com/microsoft/go-infra/executil"
"github.com/microsoft/go-infra/subcmd"
)
const description = `
Gets specific builds of the MinGW toolchain.
Intended for dev scenarios and CI tests. Not a complete list of builds or versions.
`
//go:embed data.json
var data []byte
const (
Nixman string = "nixman"
Winlibs string = "winlibs"
Sourceforge string = "sourceforge"
)
const niXmanPrefix = "https://github.com/niXman/mingw-builds-binaries/releases/"
const winlibsPrefix = "https://github.com/brechtsanders/winlibs_mingw/releases/download/"
var subcommands []subcmd.Option
func main() {
if err := subcmd.Run("getmingw", description, subcommands); err != nil {
log.Fatal(err)
}
}
// Flags responsible for filtering results in multiple commands.
var (
sources subcmd.MultiStringFlag
versions subcmd.MultiStringFlag
arches subcmd.MultiStringFlag
threadings subcmd.MultiStringFlag
exceptions subcmd.MultiStringFlag
runtimes subcmd.MultiStringFlag
llvms subcmd.MultiStringFlag
)
func initFilterFlags() {
flag.Var(&sources, "source", "source: see 'getmingw list'")
flag.Var(&versions, "version", "version: see 'getmingw list'")
flag.Var(&arches, "arch", "architecture: x86_64, i686")
flag.Var(&threadings, "threading", "threading: posix, win32, mcf")
flag.Var(&exceptions, "exception", "exception: seh, dwarf, sjlj")
flag.Var(&runtimes, "runtime", "runtime: ucrt, msvcrt")
flag.Var(&llvms, "llvm", "llvm build present: llvm, no")
}
func unmarshal() (r map[string]build, err error) {
err = json.Unmarshal(data, &r)
if err != nil {
err = fmt.Errorf("failed to read embedded JSON: %v", err)
}
return r, err
}
func marshal(data map[string]build) ([]byte, error) {
return json.MarshalIndent(data, "", " ")
}
func filter(builds map[string]build) []*build {
var result []*build
match := func(msf *subcmd.MultiStringFlag, v string) bool {
if len(msf.Values) == 0 {
return true
}
for _, s := range msf.Values {
if s == v {
return true
}
}
return false
}
for _, b := range builds {
b := b
if match(&sources, b.Source) &&
match(&versions, b.Version) &&
match(&arches, b.Arch) &&
match(&threadings, b.Threading) &&
match(&exceptions, b.Exception) &&
match(&runtimes, b.Runtime) &&
match(&llvms, b.LLVM) {
result = append(result, &b)
}
}
sort.Slice(result, func(i, j int) bool {
return result[i].URL < result[j].URL
})
return result
}
func newBuildTabWriter(w io.Writer) *tabwriter.Writer {
tw := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.DiscardEmptyColumns)
headerBuild := build{
Source: "Source",
Version: "Version",
Arch: "Arch",
Threading: "Threading",
Exception: "Exception",
Runtime: "Runtime",
LLVM: "LLVM",
}
_, err := tw.Write([]byte(headerBuild.FilterTabString() + "\n"))
if err != nil {
panic(err)
}
return tw
}
func cacheDir() (string, error) {
userDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(userDir, ".msft-go-infra", "getmingw"), nil
}
var errBuildNotFound = errors.New("build not found")
type build struct {
Source string
Version string
Arch string
Threading string
Exception string
Runtime string
// LLVM is "llvm" or "no" for WinLibs. "" for other sources.
LLVM string `json:",omitempty"`
// URL of the download. Assumed to be unique for a specific download.
// Not included in filtering.
URL string
// SHA512 is the checksum of the download. Not included in filtering.
SHA512 string
}
func (b *build) CreateFreshChecksum() error {
// Download the URL and compute the SHA512:
var client http.Client
resp, err := client.Get(b.URL)
if err != nil {
return err
}
if resp.StatusCode == http.StatusNotFound {
return errBuildNotFound
}
defer resp.Body.Close()
hash := sha512.New()
if _, err := io.Copy(hash, resp.Body); err != nil {
return err
}
// Write the SHA512 to the struct.
b.SHA512 = fmt.Sprintf("%x", hash.Sum(nil))
return nil
}
func (b *build) GetOrCreateCacheBinDir() (string, error) {
mingwCacheDir, err := cacheDir()
if err != nil {
return "", err
}
buildDir := filepath.Join(mingwCacheDir, b.CacheKey())
if err := os.MkdirAll(buildDir, 0o777); err != nil {
return "", err
}
downloadFile := filepath.Join(buildDir, "mingw.7z")
downloadedIndicator := filepath.Join(buildDir, ".downloaded")
extractDir := filepath.Join(buildDir, "ext")
extractedIndicator := filepath.Join(buildDir, ".extracted")
var extractedBinDir string
switch b.Arch {
case "i686":
extractedBinDir = filepath.Join(extractDir, "mingw32", "bin")
case "x86_64":
extractedBinDir = filepath.Join(extractDir, "mingw64", "bin")
default:
return "", fmt.Errorf("unknown arch %#q", b.Arch)
}
if cachedHash, err := os.ReadFile(downloadedIndicator); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("unexpected error while reading %#q: %v", downloadedIndicator, err)
}
// Best effort to delete old downloaded file, in case it failed in a weird way.
_ = os.Remove(downloadFile)
log.Printf("Downloading %v...", b.URL)
// Download the URL and compute the SHA512:
var client http.Client
resp, err := client.Get(b.URL)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected status code %v", resp.StatusCode)
}
defer resp.Body.Close()
// Open the file for writing:
f, err := os.OpenFile(downloadFile, os.O_CREATE|os.O_WRONLY, 0o666)
if err != nil {
return "", err
}
hash := sha512.New()
_, err = io.Copy(io.MultiWriter(f, hash), resp.Body)
if errClose := f.Close(); err == nil {
err = errClose
}
if err != nil {
return "", err
}
// Verify the SHA512:
if sum := fmt.Sprintf("%x", hash.Sum(nil)); sum != b.SHA512 {
return "", fmt.Errorf("SHA512 mismatch.\n Expected: %v\n Downloaded: %v", b.SHA512, sum)
}
// Write the download complete indicator:
if err := os.WriteFile(downloadedIndicator, []byte(b.SHA512), 0o666); err != nil {
return "", err
}
} else {
// Found an indicator. But was there a collision in the key?
if string(cachedHash) != b.SHA512 {
return "", fmt.Errorf("SHA512 mismatch.\n Expected: %v\n Cached: %v", b.SHA512, string(cachedHash))
}
}
if cachedHash, err := os.ReadFile(extractedIndicator); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("unexpected error while reading %#q: %v", extractedIndicator, err)
}
// Best effort to delete the old extraction dir, in case it failed in a weird way.
_ = os.RemoveAll(extractDir)
log.Printf("Extracting %#q...", downloadFile)
// Extract the 7z file:
cmd := exec.Command("7z", "x", "-o"+extractDir, downloadFile)
// If the user cancels, or one 7z processes of many fails, make sure
// all others are canceled. Otherwise, they may keep running in the
// background.
if out, err := executil.CombinedOutput(cmd); err != nil {
return "", fmt.Errorf("failed to extract: %v, output: %v", err, out)
}
// Write the extraction complete indicator:
if err := os.WriteFile(extractedIndicator, []byte(b.SHA512), 0o666); err != nil {
return "", err
}
log.Printf("Extracted to %v", extractDir)
} else {
// Found an indicator. But was there a collision in the key?
if string(cachedHash) != b.SHA512 {
return "", fmt.Errorf("SHA512 mismatch.\n Expected: %v\n Cached: %v", b.SHA512, string(cachedHash))
}
}
return extractedBinDir, nil
}
func (b *build) CacheKey() string {
url := b.URL
const maxUrlChars = 30
if len(url) > maxUrlChars {
url = url[len(url)-maxUrlChars:]
}
var u strings.Builder
for _, c := range url {
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') {
u.WriteRune(c)
} else {
u.WriteRune('_')
}
}
u.WriteString("-")
u.WriteString(b.SHA512[:32])
return u.String()
}
// FilterTabString returns a tab-separated string of all filtered fields.
func (b *build) FilterTabString() string {
return strings.Join([]string{
b.Source,
b.Version,
b.Arch,
b.Threading,
b.Exception,
b.Runtime,
b.LLVM,
"",
}, "\t")
}