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  	goTool := testenv.GoToolPath(t)
    22  
    23  	// If the default GOMODCACHE doesn't exist, use a temporary directory
    24  	// instead. (For example, run.bash sets GOPATH=/nonexist-gopath.)
    25  	out, err := testenv.Command(t, goTool, "env", "GOMODCACHE").Output()
    26  	if err != nil {
    27  		t.Errorf("%s env GOMODCACHE: %v\n%s", goTool, err, out)
    28  		if ee, ok := err.(*exec.ExitError); ok {
    29  			t.Logf("%s", ee.Stderr)
    30  		}
    31  		t.FailNow()
    32  	}
    33  	modcacheOk := false
    34  	if gomodcache := string(bytes.TrimSpace(out)); gomodcache != "" {
    35  		if _, err := os.Stat(gomodcache); err == nil {
    36  			modcacheOk = true
    37  		}
    38  	}
    39  	if !modcacheOk {
    40  		t.Setenv("GOMODCACHE", t.TempDir())
    41  		// Allow t.TempDir() to clean up subdirectories.
    42  		t.Setenv("GOFLAGS", os.Getenv("GOFLAGS")+" -modcacherw")
    43  	}
    44  
    45  	t.Logf("fetching %s@%s\n", module, version)
    46  
    47  	output, err := testenv.Command(t, goTool, "mod", "download", "-json", module+"@"+version).CombinedOutput()
    48  	if err != nil {
    49  		t.Fatalf("failed to download %s@%s: %s\n%s\n", module, version, err, output)
    50  	}
    51  	var j struct {
    52  		Dir string
    53  	}
    54  	if err := json.Unmarshal(output, &j); err != nil {
    55  		t.Fatalf("failed to parse 'go mod download': %s\n%s\n", err, output)
    56  	}
    57  
    58  	return j.Dir
    59  }
    60  

View as plain text