1 // Copyright 2020 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.
5 // Package proxydir provides functions for writing module data to a directory
6 // in proxy format, so that it can be used as a module proxy by setting
7 // GOPROXY="file://<dir>".
19 "golang.org/x/tools/internal/testenv"
22 // WriteModuleVersion creates a directory in the proxy dir for a module.
23 func WriteModuleVersion(rootDir, module, ver string, files map[string][]byte) (rerr error) {
24 dir := filepath.Join(rootDir, module, "@v")
25 if err := os.MkdirAll(dir, 0755); err != nil {
29 // The go command checks for versions by looking at the "list" file. Since
30 // we are supporting multiple versions, create this file if it does not exist
31 // or append the version number to the preexisting file.
32 f, err := os.OpenFile(filepath.Join(dir, "list"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
36 defer checkClose("list file", f, &rerr)
37 if _, err := f.WriteString(ver + "\n"); err != nil {
41 // Serve the go.mod file on the <version>.mod url, if it exists. Otherwise,
43 modContents, ok := files["go.mod"]
45 modContents = []byte("module " + module)
47 if err := ioutil.WriteFile(filepath.Join(dir, ver+".mod"), modContents, 0644); err != nil {
51 // info file, just the bare bones.
52 infoContents := []byte(fmt.Sprintf(`{"Version": "%v", "Time":"2017-12-14T13:08:43Z"}`, ver))
53 if err := ioutil.WriteFile(filepath.Join(dir, ver+".info"), infoContents, 0644); err != nil {
57 // zip of all the source files.
58 f, err = os.OpenFile(filepath.Join(dir, ver+".zip"), os.O_CREATE|os.O_WRONLY, 0644)
62 defer checkClose("zip file", f, &rerr)
64 defer checkClose("zip writer", z, &rerr)
65 for name, contents := range files {
66 zf, err := z.Create(module + "@" + ver + "/" + name)
70 if _, err := zf.Write(contents); err != nil {
78 func checkClose(name string, closer io.Closer, err *error) {
79 if cerr := closer.Close(); cerr != nil && *err == nil {
80 *err = fmt.Errorf("closing %s: %v", name, cerr)
84 // ToURL returns the file uri for a proxy directory.
85 func ToURL(dir string) string {
86 if testenv.Go1Point() >= 13 {
87 // file URLs on Windows must start with file:///. See golang.org/issue/6027.
88 path := filepath.ToSlash(dir)
89 if !strings.HasPrefix(path, "/") {
92 return "file://" + path
94 // Prior to go1.13, the Go command on Windows only accepted GOPROXY file URLs
95 // of the form file://C:/path/to/proxy. This was incorrect: when parsed, "C:"
96 // is interpreted as the host. See golang.org/issue/6027. This has been
97 // fixed in go1.13, but we emit the old format for old releases.
98 return "file://" + filepath.ToSlash(dir)