-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmagefile.go
More file actions
657 lines (585 loc) · 20.7 KB
/
Copy pathmagefile.go
File metadata and controls
657 lines (585 loc) · 20.7 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
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//go:build mage
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
)
// staleBinaryThreshold is the maximum acceptable age for a freshly-built
// binary. If the binary on disk is older than this it is considered stale.
const staleBinaryThreshold = 30 * time.Second
// deadcodeAllowlist contains functions reported by deadcode that are not
// genuinely dead: build-tag stubs, interface implementations, and functions
// called only from files with non-default build tags.
var deadcodeAllowlist = []string{
"filterEnv", // Unix-only helper called from launchInPlaceUnix (launch_unix.go)
"launchInPlaceUnix", // build-tag stub (launch_windows.go)
"colorSchemeRef.UnmarshalJSON", // Windows-only (wttheme.go)
"colorSchemeRef.resolve", // Windows-only (wttheme.go)
"DetectWTColorScheme", // Windows-only (wttheme.go)
"wtSettingsPaths", // Windows-only (wttheme.go)
"parseWTSettings", // Windows-only (wttheme.go)
"parseWTSettingsData", // Windows-only (wttheme.go)
"keyMap.ShortHelp", // key.Map interface impl
"keyMap.FullHelp", // key.Map interface impl
"CurrentTheme", // called from screenshot.go (//go:build screenshots)
}
const (
// coverProfile is the file name for the raw coverage data.
coverProfile = "coverage.out"
// coverHTML is the file name for the generated HTML coverage report.
coverHTML = "coverage.html"
)
var (
binName = "dispatch-dev"
mainPkg = "./cmd/dispatch/"
versionVar = "github.com/jongio/dispatch/internal/version.Version"
)
// Default target when running `mage` with no args.
var Default = Install
// Install runs tests, kills stale processes, builds the dev binary, and ensures it's in PATH.
func Install() error {
if err := Test(); err != nil {
return err
}
killStale()
if err := Build(); err != nil {
return err
}
if err := ensurePath(); err != nil {
return err
}
return verify()
}
// Test runs all unit tests with race detection and shuffled order.
func Test() error {
fmt.Println("\n=== Running tests ===")
args := []string{"test"}
if raceDetectorAvailable() {
os.Setenv("CGO_ENABLED", "1")
args = append(args, "-race")
fmt.Println(" Race detector: enabled")
} else {
fmt.Println(" Race detector: skipped (requires gcc/CGO on Windows)")
}
args = append(args, "-shuffle=on", "./...", "-count=1")
return run("go", args...)
}
// TestWSL runs tests under WSL Linux to exercise Unix-specific code paths.
func TestWSL() error {
fmt.Println("\n=== Running tests in WSL ===")
if _, err := exec.LookPath("wsl"); err != nil {
fmt.Println(" Skipped (WSL not available)")
return nil
}
// Check whether Go is installed inside WSL before attempting to run tests.
if checkErr := run("wsl", "bash", "-c", "command -v go >/dev/null 2>&1"); checkErr != nil {
fmt.Println(" Skipped (go not installed in WSL)")
return nil
}
wslPath, err := windowsToWSLPath(projectDir())
if err != nil {
return fmt.Errorf("converting path for WSL: %w", err)
}
cmd := fmt.Sprintf("cd %s && go test ./... -count=1", wslPath)
return run("wsl", "bash", "-c", cmd)
}
// CoverageReport generates an HTML coverage report.
func CoverageReport() error {
fmt.Println("\n=== Generating coverage report ===")
if err := run("go", "test", "./internal/...", "-coverprofile="+coverProfile, "-covermode=atomic"); err != nil {
return fmt.Errorf("coverage run: %w", err)
}
if err := run("go", "tool", "cover", "-html="+coverProfile, "-o", coverHTML); err != nil {
return fmt.Errorf("coverage report: %w", err)
}
fmt.Printf(" Coverage report: %s\n", coverHTML)
return nil
}
// Vet runs go vet on all packages.
func Vet() error {
fmt.Println("\n=== Running vet ===")
return run("go", "vet", "./...")
}
// Build compiles the dev binary with version info into bin/.
func Build() error {
fmt.Println("\n=== Building binary ===")
binDir := filepath.Join(projectDir(), "bin")
if err := os.MkdirAll(binDir, 0o755); err != nil {
return fmt.Errorf("creating bin directory: %w", err)
}
version := devVersion()
ldflags := fmt.Sprintf("-X %s=%s", versionVar, version)
outPath := filepath.Join(binDir, binaryName())
if err := run("go", "build", "-ldflags", ldflags, "-o", outPath, mainPkg); err != nil {
return err
}
fmt.Printf(" Version: %s\n", version)
return nil
}
// Preflight runs all pre-commit checks: format, tidy, vet, lint, WSL lint,
// build, test, race detection, WSL tests, vulnerability scan, strict
// formatting, dead code detection, and install verification. If preflight
// passes, CI will pass.
func Preflight() error {
fmt.Println("\n=== 1/13 Formatting ===")
if err := fmtSources(); err != nil {
return fmt.Errorf("format: %w", err)
}
fmt.Println("\n=== 2/13 Tidying modules ===")
if err := run("go", "mod", "tidy"); err != nil {
return fmt.Errorf("mod tidy: %w", err)
}
fmt.Println("\n=== 3/13 Vetting ===")
if err := run("go", "vet", "./..."); err != nil {
return fmt.Errorf("vet: %w", err)
}
fmt.Println("\n=== 4/13 Linting ===")
if _, err := exec.LookPath("golangci-lint"); err == nil {
if out, err := cmdOutput("golangci-lint", "version"); err == nil {
if !strings.Contains(out, "golangci-lint has version 2.") {
fmt.Printf(" WARNING: golangci-lint v2 expected, got: %s\n", strings.TrimSpace(out))
}
}
if err := run("golangci-lint", "run"); err != nil {
return fmt.Errorf("lint: %w", err)
}
fmt.Println(" Attempting GOOS=linux lint to catch Linux-only files seen in CI")
if err := runWithEnv(map[string]string{"GOOS": "linux"}, "golangci-lint", "run"); err != nil {
fmt.Printf(" WARNING: GOOS=linux golangci-lint run failed on %s: %v\n", runtime.GOOS, err)
}
} else {
fmt.Println(" Skipped (install: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest)")
}
fmt.Println("\n=== 5/13 Linting (WSL / Linux) ===")
if _, err := exec.LookPath("wsl"); err == nil {
// Check whether golangci-lint is installed inside WSL before
// attempting to run it, mirroring the skip pattern used by
// govulncheck, gofumpt, and deadcode.
if checkErr := run("wsl", "bash", "-c", "command -v golangci-lint >/dev/null 2>&1"); checkErr != nil {
fmt.Println(" Skipped (golangci-lint not installed in WSL)")
} else {
wslPath, err := windowsToWSLPath(projectDir())
if err != nil {
return fmt.Errorf("WSL path conversion: %w", err)
}
cmd := fmt.Sprintf("cd %s && golangci-lint run", wslPath)
if err := run("wsl", "bash", "-c", cmd); err != nil {
return fmt.Errorf("WSL lint: %w", err)
}
}
} else {
fmt.Println(" Skipped (WSL not available)")
}
fmt.Println("\n=== 6/13 Building ===")
if err := run("go", "build", "./..."); err != nil {
return fmt.Errorf("build: %w", err)
}
fmt.Println("\n=== 7/13 Testing ===")
if err := run("go", "test", "./...", "-count=1"); err != nil {
return fmt.Errorf("test: %w", err)
}
fmt.Println("\n=== 8/13 Testing (race detector) ===")
if raceDetectorAvailable() {
if err := run("go", "test", "-race", "./...", "-count=1"); err != nil {
return fmt.Errorf("race test: %w", err)
}
} else {
fmt.Println(" Skipped (requires gcc/CGO on Windows)")
}
fmt.Println("\n=== 9/13 Testing (WSL) ===")
if err := TestWSL(); err != nil {
return fmt.Errorf("WSL test: %w", err)
}
fmt.Println("\n=== 10/13 Vulnerability scan ===")
if _, err := exec.LookPath("govulncheck"); err == nil {
if err := run("govulncheck", "./..."); err != nil {
return fmt.Errorf("vulncheck: %w", err)
}
} else {
fmt.Println(" Skipped (install: go install golang.org/x/vuln/cmd/govulncheck@latest)")
}
fmt.Println("\n=== 11/13 Strict formatting (gofumpt) ===")
if _, err := exec.LookPath("gofumpt"); err == nil {
out, _ := cmdOutput("gofumpt", "-l", ".")
if files := strings.TrimSpace(out); files != "" {
return fmt.Errorf("gofumpt: files need formatting:\n%s", files)
}
} else {
fmt.Println(" Skipped (install: go install mvdan.cc/gofumpt@latest)")
}
fmt.Println("\n=== 12/13 Dead code detection ===")
if _, err := exec.LookPath("deadcode"); err == nil {
if err := runDeadcode(); err != nil {
return err
}
} else {
fmt.Println(" Skipped (install: go install golang.org/x/tools/cmd/deadcode@latest)")
}
fmt.Println("\n=== 13/13 Install verification ===")
if err := Install(); err != nil {
return fmt.Errorf("install: %w", err)
}
fmt.Println("\n=== All 13/13 preflight checks passed — ready to commit ===")
return nil
}
// Fmt formats all Go source files.
func Fmt() error {
fmt.Println("=== Formatting ===")
return fmtSources()
}
// Lint runs golangci-lint if available, otherwise falls back to go vet.
func Lint() error {
fmt.Println("\n=== Linting ===")
if _, err := exec.LookPath("golangci-lint"); err == nil {
return run("golangci-lint", "run")
}
fmt.Println(" golangci-lint not found, using go vet")
return run("go", "vet", "./...")
}
// Clean removes the bin/ directory.
func Clean() error {
fmt.Println("=== Cleaning ===")
return os.RemoveAll(filepath.Join(projectDir(), "bin"))
}
// Contributors regenerates CONTRIBUTORS.md from the full git history.
func Contributors() error {
fmt.Println("\n=== Generating CONTRIBUTORS.md ===")
return run("go", "run", "./cmd/contributors/", "--all")
}
// ChangelogCheck verifies that CHANGELOG.md contains an entry for the given
// version (or the latest git tag if no version is specified). Use before
// tagging a release to prevent shipping without changelog entries.
func ChangelogCheck() error {
fmt.Println("\n=== Changelog verification ===")
// Determine which version to check: use RELEASE_VERSION env var if set
// (for CI), otherwise find the latest git tag.
version := os.Getenv("RELEASE_VERSION")
if version == "" {
out, err := cmdOutput("git", "tag", "--list", "v*", "--sort=-v:refname")
if err != nil {
return fmt.Errorf("git tag list: %w", err)
}
tags := strings.Fields(strings.TrimSpace(out))
if len(tags) == 0 {
fmt.Println(" No tags found, skipping changelog check")
return nil
}
version = tags[0]
}
// Normalize: strip leading 'v' for the search, keep it for display
display := version
if !strings.HasPrefix(version, "v") {
display = "v" + version
}
// Search CHANGELOG.md for a heading containing the version
f, err := os.Open(filepath.Join(projectDir(), "CHANGELOG.md"))
if err != nil {
return fmt.Errorf("open CHANGELOG.md: %w", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "## ") && strings.Contains(line, display) {
fmt.Printf(" Found entry for %s\n", display)
return nil
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading CHANGELOG.md: %w", err)
}
return fmt.Errorf("CHANGELOG.md has no entry for %s -- add one before releasing", display)
}
// Deadcode runs dead code detection with allowlist filtering.
// CI uses this target to avoid false positives from build-tag stubs.
func Deadcode() error {
fmt.Println("\n=== Dead code detection ===")
if _, err := exec.LookPath("deadcode"); err != nil {
return fmt.Errorf("deadcode not installed: go install golang.org/x/tools/cmd/deadcode@latest")
}
return runDeadcode()
}
// --- helpers ---
func fmtSources() error {
out, _ := cmdOutput("gofmt", "-l", ".")
files := strings.TrimSpace(out)
if files == "" {
fmt.Println(" All files formatted")
return nil
}
var unformatted []string
for _, f := range strings.Split(files, "\n") {
f = strings.TrimSpace(f)
if f != "" {
unformatted = append(unformatted, f)
}
}
fmt.Printf(" %d file(s) need formatting:\n", len(unformatted))
for _, f := range unformatted {
fmt.Printf(" %s\n", f)
}
fmt.Println("\n Run 'gofmt -w .' to fix, then commit the changes.")
return fmt.Errorf("gofmt: %d file(s) not formatted", len(unformatted))
}
func binaryName() string {
if runtime.GOOS == "windows" {
return binName + ".exe"
}
return binName
}
func projectDir() string {
dir, _ := os.Getwd()
return dir
}
func devVersion() string {
hash, _ := cmdOutput("git", "rev-parse", "--short", "HEAD")
ts := time.Now().Format("20060102-150405")
return fmt.Sprintf("dev-%s-%s", strings.TrimSpace(hash), ts)
}
func killStale() {
fmt.Println("\n=== Killing stale processes ===")
if runtime.GOOS == "windows" {
script := fmt.Sprintf(`Get-Process %s -ErrorAction SilentlyContinue | Stop-Process -Force`, binName)
exec.Command("powershell", "-NoProfile", "-Command", script).Run()
} else {
exec.Command("pkill", "-f", binaryName()).Run()
}
time.Sleep(500 * time.Millisecond)
}
func ensurePath() error {
binDir := filepath.Join(projectDir(), "bin")
if runtime.GOOS != "windows" {
path := os.Getenv("PATH")
if !strings.Contains(path, binDir) {
fmt.Printf("NOTE: Add %s to your PATH:\n export PATH=\"%s:$PATH\"\n", binDir, binDir)
}
return nil
}
// Windows: scrub stale dispatch worktree bins from persistent PATH,
// then ensure the current project's bin dir is registered.
machinePath, _ := cmdOutput("powershell", "-NoProfile", "-Command",
`[Environment]::GetEnvironmentVariable('Path','Machine')`)
machinePath = strings.TrimSpace(machinePath)
userPath, _ := cmdOutput("powershell", "-NoProfile", "-Command",
`[Environment]::GetEnvironmentVariable('Path','User')`)
userPath = strings.TrimSpace(userPath)
cleanedMachine, removedMachine := scrubDispatchBins(machinePath, binDir)
if len(removedMachine) > 0 {
fmt.Println("\n=== Scrubbing stale dispatch bin dirs from Machine PATH ===")
for _, r := range removedMachine {
fmt.Printf(" Removed: %s\n", r)
}
if err := exec.Command("powershell", "-NoProfile", "-Command",
fmt.Sprintf(`[Environment]::SetEnvironmentVariable('Path','%s','Machine')`, cleanedMachine)).Run(); err != nil {
fmt.Println(" Machine PATH update failed (need admin)")
}
}
machinePath = cleanedMachine
cleanedUser, removedUser := scrubDispatchBins(userPath, binDir)
if len(removedUser) > 0 {
fmt.Println("\n=== Scrubbing stale dispatch bin dirs from User PATH ===")
for _, r := range removedUser {
fmt.Printf(" Removed: %s\n", r)
}
exec.Command("powershell", "-NoProfile", "-Command",
fmt.Sprintf(`[Environment]::SetEnvironmentVariable('Path','%s','User')`, cleanedUser)).Run()
}
userPath = cleanedUser
if containsPath(machinePath, binDir) || containsPath(userPath, binDir) {
// Already registered; just make sure the current session has it.
ensureSessionPath(binDir)
return nil
}
fmt.Printf("\n=== Adding %s to PATH ===\n", binDir)
// Prefer Machine PATH (visible to every user) but fall back to User PATH,
// which does not need administrator rights. Report the outcome either way
// so a failed persist is never silent.
machineErr := exec.Command("powershell", "-NoProfile", "-Command",
fmt.Sprintf(`[Environment]::SetEnvironmentVariable('Path','%s;%s','Machine')`, binDir, machinePath)).Run()
if machineErr == nil {
fmt.Println(" Added to Machine PATH.")
} else {
fmt.Println(" Machine PATH needs admin; adding to User PATH instead...")
if userErr := exec.Command("powershell", "-NoProfile", "-Command",
fmt.Sprintf(`[Environment]::SetEnvironmentVariable('Path','%s;%s','User')`, binDir, userPath)).Run(); userErr != nil {
fmt.Printf(" WARNING: could not add %s to User PATH: %v\n", binDir, userErr)
fmt.Println(" Add it manually, or re-run `mage install` from an elevated terminal.")
} else {
fmt.Println(" Added to User PATH.")
}
}
ensureSessionPath(binDir)
return nil
}
func containsPath(pathList, dir string) bool {
return strings.Contains(strings.ToLower(pathList), strings.ToLower(dir))
}
// isDispatchBinDir reports whether a PATH entry looks like a dispatch
// project or worktree bin directory: the path contains "dispatch"
// (case-insensitive) and the final path component is "bin". This
// preserves the production install path (e.g.
// C:\Users\jong\AppData\Local\Programs\dispatch) which does not end
// with \bin.
func isDispatchBinDir(entry string) bool {
clean := filepath.Clean(entry)
if !strings.Contains(strings.ToLower(clean), "dispatch") {
return false
}
return strings.EqualFold(filepath.Base(clean), "bin")
}
// scrubDispatchBins removes dispatch worktree/project bin directories
// from pathList, keeping only the entry matching keep (case-insensitive
// comparison). If keep is empty, all dispatch bin dirs are removed.
// Non-dispatch entries are always preserved. Returns the cleaned path
// and the list of removed entries.
func scrubDispatchBins(pathList, keep string) (string, []string) {
sep := string(os.PathListSeparator)
entries := strings.Split(pathList, sep)
keepClean := ""
if keep != "" {
keepClean = filepath.Clean(keep)
}
var out []string
var removed []string
for _, e := range entries {
e = strings.TrimSpace(e)
if e == "" {
continue
}
clean := filepath.Clean(e)
if keepClean != "" && strings.EqualFold(clean, keepClean) {
out = append(out, e)
continue
}
if isDispatchBinDir(clean) {
removed = append(removed, e)
continue
}
out = append(out, e)
}
return strings.Join(out, sep), removed
}
func ensureSessionPath(binDir string) {
current := os.Getenv("Path")
// Remove all dispatch bin dirs (including current if present), then
// prepend current so it takes priority over any other entry.
cleaned, _ := scrubDispatchBins(current, "")
os.Setenv("Path", binDir+string(os.PathListSeparator)+cleaned)
}
func verify() error {
outPath := filepath.Join(projectDir(), "bin", binaryName())
info, err := os.Stat(outPath)
if err != nil {
return fmt.Errorf("binary not found after build at %s: %w", outPath, err)
}
age := time.Since(info.ModTime())
if age > staleBinaryThreshold {
return fmt.Errorf("%s seems stale (built %s, %.0fs ago)", binaryName(), info.ModTime().Format(time.DateTime), age.Seconds())
}
resolved, err := exec.LookPath(binaryName())
if err != nil {
return fmt.Errorf("%s not found in PATH: %w", binaryName(), err)
}
resolvedAbs, err := filepath.Abs(resolved)
if err != nil {
return fmt.Errorf("resolving actual binary path: %w", err)
}
expectedAbs, err := filepath.Abs(outPath)
if err != nil {
return fmt.Errorf("resolving expected binary path: %w", err)
}
if !strings.EqualFold(resolvedAbs, expectedAbs) {
return fmt.Errorf("PATH resolves to %s, expected %s — another binary may be shadowing", resolvedAbs, expectedAbs)
}
fmt.Printf("\n✅ %s installed\n", binaryName())
fmt.Printf(" Path: %s\n", outPath)
fmt.Printf(" Built: %s\n", info.ModTime().Format(time.DateTime))
fmt.Printf(" Run: open a new terminal, then `%s` (already-open shells keep the old PATH)\n", binName)
return nil
}
// runDeadcode executes `deadcode ./...` and filters the output against
// deadcodeAllowlist. Only genuinely dead functions cause a failure.
func runDeadcode() error {
// deadcode writes findings to stdout and exits 0 regardless.
out, err := cmdOutput("deadcode", "./...")
if err != nil {
return fmt.Errorf("deadcode: %w", err)
}
var genuine []string
allowed := 0
for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
if isAllowlisted(line) {
allowed++
continue
}
genuine = append(genuine, line)
}
if len(genuine) > 0 {
fmt.Println(" Unexpected dead code found:")
for _, g := range genuine {
fmt.Printf(" %s\n", g)
}
return fmt.Errorf("deadcode: %d genuine finding(s) (update deadcodeAllowlist if false positive)", len(genuine))
}
fmt.Printf(" OK (%d known exclusions)\n", allowed)
return nil
}
// isAllowlisted reports whether a deadcode output line matches a function in
// the deadcodeAllowlist. Each deadcode line ends with "unreachable func: <name>".
func isAllowlisted(line string) bool {
for _, name := range deadcodeAllowlist {
if strings.HasSuffix(line, ": "+name) {
return true
}
}
return false
}
func run(name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = projectDir()
return cmd.Run()
}
func runWithEnv(env map[string]string, name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = projectDir()
cmd.Env = os.Environ()
for key, value := range env {
cmd.Env = append(cmd.Env, key+"="+value)
}
return cmd.Run()
}
func cmdOutput(name string, args ...string) (string, error) {
cmd := exec.Command(name, args...)
cmd.Dir = projectDir()
out, err := cmd.Output()
return string(out), err
}
func raceDetectorAvailable() bool {
if runtime.GOOS != "windows" {
return true
}
_, err := exec.LookPath("gcc")
return err == nil
}
func windowsToWSLPath(winPath string) (string, error) {
if len(winPath) < 2 || winPath[1] != ':' {
return "", fmt.Errorf("unexpected Windows path format: %s", winPath)
}
drive := strings.ToLower(string(winPath[0]))
rest := strings.ReplaceAll(winPath[2:], "\\", "/")
return fmt.Sprintf("/mnt/%s%s", drive, rest), nil
}