1package client
2
3import (
4 "os"
5 "path/filepath"
6 "strings"
7 "testing"
8
9 "github.com/bnema/go-wayland-bindings/spec"
10)
11
12// repoRoot is the repository root relative to this package.
13const repoRoot = "../../.."
14
15// rootRequirement returns the version of module required by the repository's
16// own go.mod, so the temp modules compile against the pinned release.
17func rootRequirement(t *testing.T, module string) string {
18 t.Helper()
19 b, err := os.ReadFile(filepath.Join(repoRoot, "go.mod"))
20 if err != nil {
21 t.Fatal(err)
22 }
23 for _, line := range strings.Split(string(b), "\n") {
24 f := strings.Fields(strings.TrimPrefix(strings.TrimSpace(line), "require "))
25 if len(f) >= 2 && f[0] == module {
26 return f[1]
27 }
28 }
29 t.Fatalf("go.mod has no requirement on %s", module)
30 return ""
31}
32
33// writeTempModule writes go.mod and go.sum for a throwaway module that
34// requires the wlturbo runtime and golang.org/x/sys at the versions pinned in
35// the repository's go.mod. With selfReplace, the module also requires this
36// repository and replaces it with the working tree, so generated code may
37// import the generated client packages. go.sum starts from the repository's
38// own go.sum; tempModuleEnv lets the go command complete it offline from the
39// module cache.
40func writeTempModule(t *testing.T, dir, module string, selfReplace bool) {
41 t.Helper()
42 mod := "module " + module + "\n\ngo 1.27\n\n" +
43 "require (\n\tgithub.com/bnema/wlturbo " + rootRequirement(t, "github.com/bnema/wlturbo") +
44 "\n\tgolang.org/x/sys " + rootRequirement(t, "golang.org/x/sys") + "\n)\n"
45 if selfReplace {
46 root, err := filepath.Abs(repoRoot)
47 if err != nil {
48 t.Fatal(err)
49 }
50 mod += "\nrequire " + spec.ModulePath + " v0.0.0\n\nreplace " + spec.ModulePath + " => " + root + "\n"
51 }
52 if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(mod), 0o600); err != nil {
53 t.Fatal(err)
54 }
55 sum, err := os.ReadFile(filepath.Join(repoRoot, "go.sum"))
56 if err != nil {
57 t.Fatal(err)
58 }
59 if err := os.WriteFile(filepath.Join(dir, "go.sum"), sum, 0o600); err != nil {
60 t.Fatal(err)
61 }
62}
63
64// tempModuleEnv resolves modules from the local module cache only: no network
65// access and no checksum database lookups.
66func tempModuleEnv() []string {
67 return append(os.Environ(), "GOWORK=off", "GOFLAGS=-mod=mod", "GOPROXY=off", "GONOSUMDB=*", "GOSUMDB=off")
68}