/
main.go
192 lines (159 loc) · 4.36 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"golang.org/x/exp/maps"
"golang.org/x/mod/module"
"golang.org/x/mod/zip"
)
func main() {
if err := run(context.Background(), os.Args[1:]); err != nil {
logf("%v", err)
var exitCode = 1
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
exitCode = exitErr.ExitCode()
}
os.Exit(exitCode)
}
}
func run(ctx context.Context, args []string) error {
config, err := LoadDefaultConfig()
if err != nil {
return err
}
return runWithConfig(ctx, config, args)
}
func runWithConfig(ctx context.Context, config *Config, args []string) error {
if len(args) > 0 && args[0] == "publish" {
return publish(context.Background(), config, args[1:])
}
proxyServer := httptest.NewServer(newProxyHandler(config))
defer proxyServer.Close()
goProxy := os.Getenv("GOPROXY")
if goProxy == "" {
goProxy = "https://proxy.golang.org,direct"
}
goProxy = fmt.Sprintf("%s,%s", proxyServer.URL, goProxy)
goNoSumDB := os.Getenv("GONOSUMDB")
if goNoSumDB == "" {
goNoSumDB = strings.Join(maps.Keys(config.Repos), ",")
} else {
goNoSumDB += "," + strings.Join(maps.Keys(config.Repos), ",")
}
cmd := exec.Command("go")
cmd.Args = append(cmd.Args, args...)
cmd.Env = append(os.Environ(), "GOPROXY="+goProxy, "GONOSUMDB="+goNoSumDB)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func newProxyHandler(config *Config) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
resp.WriteHeader(http.StatusMethodNotAllowed)
return
}
if strings.HasPrefix(req.URL.Path, "/sumdb") {
resp.WriteHeader(http.StatusNotFound)
return
}
atIndex := strings.Index(req.URL.Path, "@")
if atIndex < 0 {
logf("Error parsing request path: %v: '@' expected", req.URL.Path)
resp.WriteHeader(http.StatusBadRequest)
return
}
modPath, err := module.UnescapePath(strings.Trim(req.URL.Path[:atIndex], "/"))
if err != nil {
logf("Error unescaping module path: %v", err)
resp.WriteHeader(http.StatusBadRequest)
return
}
attifact := req.URL.Path[atIndex:]
for moduleGlob, repository := range config.Repos {
match, _ := regexp.MatchString(globToRegexp(moduleGlob), modPath)
if !match {
continue
}
reader, status, err := repository.Get(req.Context(), modPath, attifact)
if err != nil {
// Respond with `Forbidden`` to prevent Go from
// trying to get the module from another proxy
resp.WriteHeader(status)
logf("%v", err)
return
}
_, err = io.Copy(resp, reader)
if err != nil {
logf("Error writing response: %v: %v", req.URL.Path, err)
return
}
reader.Close()
return
}
resp.WriteHeader(http.StatusNotFound)
})
}
func publish(ctx context.Context, config *Config, args []string) error {
if len(args) == 0 || len(args) > 1 {
return fmt.Errorf("Unsupported arguments: Usage: goxm publish <version>")
}
version := strings.TrimSpace(args[0])
modPath, goModData, goModFilePath, err := getGoModule(ctx)
if err != nil {
return err
}
infoData, gitRootPath, err := getGoInfoFromGit(ctx, version)
if err != nil {
return err
}
subDir, err := filepath.Rel(gitRootPath, filepath.Dir(goModFilePath))
if err != nil {
return fmt.Errorf("Unable to resolve relative path to Git repository: %w", err)
}
if subDir == "." {
// If the Git root and the module directories are the same
// then clear `subDir` so that all paths are included in
// the zip file and not just the ones starting with "."
// See the `CreateFromVCS()` docs for more information
subDir = ""
} else if strings.HasPrefix(subDir, "..") {
return fmt.Errorf("Unable to resolve go.mod path within Git repository")
}
modVersion := module.Version{
Path: modPath,
Version: version,
}
zipBuffer := bytes.NewBuffer(nil)
err = zip.CreateFromVCS(zipBuffer, modVersion, gitRootPath, version, subDir)
if err != nil {
return err
}
for moduleGlob, repository := range config.Repos {
match, _ := regexp.MatchString(globToRegexp(moduleGlob), modPath)
if !match {
continue
}
return repository.Put(
context.Background(),
modPath,
version,
goModData,
infoData,
zipBuffer.Bytes(),
)
}
return fmt.Errorf("No repository found matching module: %v", modPath)
}