Source file src/crypto/internal/cryptotest/fetchmodule.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package cryptotest
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/json"
    10  	"internal/testenv"
    11  	"os"
    12  	"os/exec"
    13  	"testing"
    14  )
    15  
    16  // FetchModule fetches the module at the given version and returns the directory
    17  // containing its source tree. It skips the test if fetching modules is not
    18  // possible in this environment.
    19  func FetchModule(t *testing.T, module, version string) string {
    20  	testenv.MustHaveExternalNetwork(t)
    21  
    22  	// If the default GOMODCACHE doesn't exist, use a temporary directory
    23  	// instead. (For example, run.bash sets GOPATH=/nonexist-gopath.)
    24  	out, err := testenv.CleanCmdEnv(testenv.Command(t, testenv.GoToolPath(t), "env", "GOMODCACHE")).Output()
    25  	if err != nil {
    26  		t.Errorf("%s env GOMODCACHE: %v\n%s", testenv.GoToolPath(t), err, out)
    27  		if ee, ok := err.(*exec.ExitError); ok {
    28  			t.Logf("%s", ee.Stderr)
    29  		}
    30  		t.FailNow()
    31  	}
    32  	modcacheOk := false
    33  	if gomodcache := string(bytes.TrimSpace(out)); gomodcache != "" {
    34  		if _, err := os.Stat(gomodcache); err == nil {
    35  			modcacheOk = true
    36  		}
    37  	}
    38  	if !modcacheOk {
    39  		t.Setenv("GOMODCACHE", t.TempDir())
    40  		// Allow t.TempDir() to clean up subdirectories.
    41  		t.Setenv("GOFLAGS", os.Getenv("GOFLAGS")+" -modcacherw")
    42  	}
    43  
    44  	t.Logf("fetching %s@%s\n", module, version)
    45  
    46  	cmd := testenv.Command(t, testenv.GoToolPath(t), "mod", "download", "-json", module+"@"+version)
    47  	var stderr bytes.Buffer
    48  	cmd.Stderr = &stderr
    49  	output, err := cmd.Output()
    50  	if err != nil {
    51  		t.Fatalf("failed to download %s@%s: %s\nstdout:\n%s\nstderr:\n%s\n", module, version, err, output, stderr.Bytes())
    52  	}
    53  	if stderr.Len() > 0 {
    54  		t.Logf("go mod download stderr:\n%s", stderr.Bytes())
    55  	}
    56  	var j struct {
    57  		Dir string
    58  	}
    59  	if err := json.Unmarshal(output, &j); err != nil {
    60  		t.Fatalf("failed to parse 'go mod download': %s\nstdout:\n%s\nstderr:\n%s\n", err, output, stderr.Bytes())
    61  	}
    62  
    63  	return j.Dir
    64  }
    65  

View as plain text