/
main.go
344 lines (302 loc) · 7.8 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package main
import (
"flag"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/token"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
var (
fake bool
rewrites map[string]string // rewrites that have been performed
visited map[string]bool // packages that have already been visited
)
func main() {
flag.BoolVar(&fake, "n", false, "If true, don't actually do anything")
flag.BoolVar(&verbose, "v", false, "Provide verbose output")
flag.Var(&ignorePrefixes, "ignore", "Package prefix to ignore. Can be given multiple times.")
flag.Parse()
gopaths := filepath.SplitList(os.Getenv("GOPATH"))
if len(gopaths) == 0 {
log.Fatal("GOPATH must be set")
}
pkgName := flag.Arg(0)
if pkgName == "" {
log.Fatal("need a package name")
}
dest := flag.Arg(1)
if dest == "" {
log.Fatal("need a destination path")
}
ignorePrefixes = append(ignorePrefixes, pkgName)
ignorePrefixes = append(ignorePrefixes, dest)
rewrites = make(map[string]string)
visited = make(map[string]bool)
err := vendorize(pkgName, chooseGOPATH(gopaths, dest), dest)
if err != nil {
log.Fatal(err)
}
}
// chooseGOPATH selects the gopath component that has the longest prefix in common with dest.
// It breaks ties by preferring earlier components.
func chooseGOPATH(gopaths []string, dest string) string {
for {
dest = strings.TrimSuffix(dest, "/")
chosen := ""
for i := len(gopaths) - 1; i >= 0; i-- {
dir := filepath.Join(gopaths[i], "src", dest)
if _, err := os.Stat(dir); err == nil {
chosen = gopaths[i]
}
}
if chosen != "" {
return chosen
}
dest, _ = filepath.Split(dest)
if dest == "" {
break
}
}
// None of the gopaths contain any prefix of dest.
// Pick the first gopath that exists.
for _, dir := range gopaths {
if _, err := os.Stat(dir); err == nil {
return dir
}
}
return gopaths[0]
}
func vendorize(path, gopath, dest string) error {
if visited[path] {
return nil
}
visited[path] = true
verbosef("vendorizing %s", path)
rootPkg, err := buildPackage(path)
if err != nil {
return fmt.Errorf("couldn't import %s: %s", path, err)
}
if rootPkg.Goroot {
return fmt.Errorf("can't vendorize packages from GOROOT")
}
allImports := getAllImports(rootPkg)
var pkgs []*build.Package
for _, imp := range allImports {
if imp == "C" {
continue
}
pkg, err := buildPackage(imp)
if err != nil {
return fmt.Errorf("%s: couldn't import %s: %s", path, imp, err)
}
if !pkg.Goroot {
pkgs = append(pkgs, pkg)
}
}
for _, pkg := range pkgs {
err := vendorize(pkg.ImportPath, gopath, dest)
if err != nil {
return fmt.Errorf("couldn't vendorize %s: %s", pkg.ImportPath, err)
}
}
pkgDir := rootPkg.Dir
if !ignored(path) {
newPath := dest + "/" + path
pkgDir = filepath.Join(gopath, "src", newPath)
err = copyDir(pkgDir, rootPkg.Dir)
if err != nil {
return fmt.Errorf("couldn't copy %s: %s", path, err)
}
rewrites[path] = newPath
}
// Rewrite any import lines in the package.
for _, files := range [][]string{
rootPkg.GoFiles, rootPkg.CgoFiles, rootPkg.TestGoFiles, rootPkg.XTestGoFiles,
} {
for _, file := range files {
if len(rewrites) > 0 {
destFile := filepath.Join(pkgDir, file)
verbosef("rewriting imports in %q", destFile)
err := rewriteFile(destFile, filepath.Join(rootPkg.Dir, file), rewrites)
if err != nil {
return fmt.Errorf("%s: couldn't rewrite file %q: %s", path, file, err)
}
}
}
}
return nil
}
// package prefixes that should not be copied
var ignorePrefixes stringSliceFlag
func ignored(path string) bool {
_, rewritten := rewrites[path]
if rewritten {
return true
}
for _, prefix := range ignorePrefixes {
if strings.HasPrefix(path, prefix) {
return true
}
}
return false
}
// copyFile copies the file given by src to dest, creating dest with the permissions given by perm.
func copyFile(dest, src string, perm os.FileMode) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
return err
}
// copyDir non-recursively copies the contents of the src directory to dest.
func copyDir(dest, src string) error {
log.Printf("copying contents of %q to %q", src, dest)
if !fake {
err := os.MkdirAll(dest, 0770)
if err != nil {
return fmt.Errorf("couldn't make destination directory", dest)
}
}
return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// We don't recurse.
if info.IsDir() {
if path != src {
return filepath.SkipDir
}
return nil
}
relPath, err := filepath.Rel(src, path)
if err != nil {
return err
}
destFile := filepath.Join(dest, relPath)
verbosef("copying %q to %q", path, destFile)
if fake {
return nil
}
return copyFile(destFile, path, info.Mode().Perm())
})
}
// getAllImports returns a list of all import paths in the Go files of pkg.
func getAllImports(pkg *build.Package) []string {
allImports := make(map[string]bool)
for _, imports := range [][]string{pkg.Imports, pkg.TestImports, pkg.XTestImports} {
for _, imp := range imports {
allImports[imp] = true
}
}
result := make([]string, 0, len(allImports))
for imp := range allImports {
result = append(result, imp)
}
return result
}
// builtPackages maintains a cache of package builds.
var builtPackages map[string]*build.Package
// buildPackage builds a package given by the path.
func buildPackage(path string) (*build.Package, error) {
if builtPackages == nil {
builtPackages = make(map[string]*build.Package)
}
if pkg, ok := builtPackages[path]; ok {
return pkg, nil
}
ctx := build.Default
// TODO(kisielk): support relative imports?
pkg, err := ctx.Import(path, "", 0)
if err != nil {
return nil, err
}
builtPackages[path] = pkg
return pkg, nil
}
func rewriteFile(dest, path string, m map[string]string) error {
if fake {
return nil
}
f, err := ioutil.TempFile(filepath.Dir(dest), "vendorize")
if err != nil {
return err
}
defer f.Close()
err = rewriteFileImports(path, m, f)
if err != nil {
return err
}
return os.Rename(f.Name(), dest)
}
func rewriteFileImports(path string, m map[string]string, w io.Writer) error {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return err
}
removeImportComment(fset, f)
for _, s := range f.Imports {
path, err := strconv.Unquote(s.Path.Value)
if err != nil {
panic(err)
}
if replacement, ok := m[path]; ok {
s.Path.Value = strconv.Quote(replacement)
}
}
return format.Node(w, fset, f)
}
// removeImportComment removes the import comment in f, if one exists.
func removeImportComment(fset *token.FileSet, f *ast.File) {
// The import comment must be immediately after (and on the same line as)
// the package declaration.
// Loop through the comments until we find one that is on that line or beyond.
nameLine := fset.Position(f.Name.NamePos).Line
for _, comments := range f.Comments {
commentLine := fset.Position(comments.Pos()).Line
if commentLine == nameLine {
comment := comments.List[0]
if strings.HasPrefix(comment.Text, "// import ") ||
strings.HasPrefix(comment.Text, "/* import ") {
comment.Text = "// #vendored#"
}
return
}
if commentLine > nameLine {
return
}
}
}
// stringSliceFlag is a flag.Value that accumulates multiple flags in to a slice.
type stringSliceFlag []string
func (s *stringSliceFlag) String() string {
return fmt.Sprintf("%v", []string(*s))
}
func (s *stringSliceFlag) Set(value string) error {
*s = append(*s, value)
return nil
}
// verbose controls the level of logging.
var verbose bool
// verbosef logs only if verbose is true.
func verbosef(s string, args ...interface{}) {
if verbose {
log.Printf(s, args...)
}
}