github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/imports/wasi_snapshot_preview1/gotip_test.go (about) 1 package wasi_snapshot_preview1_test 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 "os/exec" 8 "path" 9 "path/filepath" 10 "runtime" 11 "testing" 12 "time" 13 ) 14 15 func TestMain(m *testing.M) { 16 // Find the gotip binary (if present), and compile the Wasm binary. 17 if gotipBin, err := findGotipBin(); err != nil { 18 println("gotip: skipping due missing binary:", err) 19 } else if wasmGotip, err = compileWasip1Wasm(gotipBin); err != nil { 20 println("gotip: skipping due compilation error:", err) 21 } 22 os.Exit(m.Run()) 23 } 24 25 // compileWasip1Wasm allows us to generate a binary with runtime.GOOS=wasip1 26 // and runtime.GOARCH=wasm. This intentionally does so on-demand, because the 27 // wasm is too big to check in. Pls, not everyone will have gotip. 28 func compileWasip1Wasm(gotipBin string) ([]byte, error) { 29 // Prepare the working directory. 30 workdir, err := os.MkdirTemp("", "wasi") 31 if err != nil { 32 return nil, err 33 } 34 defer os.RemoveAll(workdir) 35 36 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) 37 defer cancel() 38 39 bin := path.Join(workdir, "wasi.wasm") 40 cmd := exec.CommandContext(ctx, gotipBin, "build", "-o", bin, ".") //nolint:gosec 41 cmd.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm") 42 cmd.Dir = "testdata/gotip" 43 out, err := cmd.CombinedOutput() 44 if err != nil { 45 return nil, fmt.Errorf("couldn't compile %s: %w", string(out), err) 46 } 47 48 return os.ReadFile(bin) //nolint:gosec 49 } 50 51 func findGotipBin() (string, error) { 52 binName := "gotip" 53 if runtime.GOOS == "windows" { 54 binName += ".exe" 55 } 56 gotipBin := filepath.Join(runtime.GOROOT(), "bin", binName) 57 if _, err := os.Stat(gotipBin); err == nil { 58 return gotipBin, nil 59 } 60 // Now, search the path 61 return exec.LookPath(binName) 62 }