forked from kardianos/govendor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
399 lines (356 loc) · 9.47 KB
/
sync.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package context
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"fmt"
"hash"
"io"
"net/url"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"github.com/kardianos/govendor/internal/pathos"
"github.com/kardianos/govendor/vendorfile"
"golang.org/x/tools/go/vcs"
)
func skipperTree(name string, dir bool) bool {
return false
}
func skipperPackage(name string, dir bool) bool {
return dir
}
func (ctx *Context) VerifyVendor() (outOfDate []*vendorfile.Package, err error) {
vf := ctx.VendorFile
root := filepath.Join(ctx.RootDir, ctx.VendorFolder)
add := func(vp *vendorfile.Package) {
outOfDate = append(outOfDate, vp)
}
for _, vp := range vf.Package {
if vp.Remove {
continue
}
if len(vp.Path) == 0 {
continue
}
if len(vp.ChecksumSHA1) == 0 {
add(vp)
continue
}
fp := filepath.Join(root, pathos.SlashToFilepath(vp.Path))
h := sha1.New()
sk := skipperPackage
if vp.Tree {
sk = skipperTree
}
err = getHash(root, fp, h, sk)
if err != nil {
return
}
checksum := base64.StdEncoding.EncodeToString(h.Sum(nil))
if vp.ChecksumSHA1 != checksum {
add(vp)
}
}
return
}
func getHash(root, fp string, h hash.Hash, skipper func(name string, isDir bool) bool) error {
rel := pathos.FileTrimPrefix(fp, root)
rel = pathos.SlashToImportPath(rel)
rel = strings.Trim(rel, "/")
h.Write([]byte(rel))
dir, err := os.Open(fp)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("Failed to open dir %q: %v", fp, err)
}
filelist, err := dir.Readdir(-1)
dir.Close()
if err != nil {
return fmt.Errorf("Failed to read dir %q: %v", fp, err)
}
sort.Sort(fileInfoSort(filelist))
for _, fi := range filelist {
if skipper(fi.Name(), fi.IsDir()) {
continue
}
p := filepath.Join(fp, fi.Name())
if fi.IsDir() {
err = getHash(root, p, h, skipper)
if err != nil {
return err
}
continue
}
f, err := os.Open(p)
if err != nil {
return err
}
h.Write([]byte(fi.Name()))
_, err = io.Copy(h, f)
f.Close()
if err != nil {
return err
}
}
return nil
}
// similarSegments compares two paths and determines if they have
// similar prefix segments. For example github.com/kardianos/rdb and
// github.com/kardianos/govendor have 2 similar segments.
func similarSegments(p1, p2 string) (string, int) {
seg1 := strings.Split(p1, "/")
seg2 := strings.Split(p2, "/")
ct := len(seg1)
if len(seg2) < ct {
ct = len(seg2)
}
similar := &bytes.Buffer{}
for i := 0; i < ct; i++ {
if seg1[i] != seg2[i] {
return similar.String(), i
}
if i != 0 {
similar.WriteRune('/')
}
similar.WriteString(seg1[i])
}
return similar.String(), ct
}
type remoteFailure struct {
Path string
Msg string
Err error
}
func (fail remoteFailure) Error() string {
return fmt.Sprintf("Failed for %q (%s): %v", fail.Path, fail.Msg, fail.Err)
}
type remoteFailureList []remoteFailure
func (list remoteFailureList) Error() string {
if len(list) == 0 {
return "(no remote failure)"
}
buf := &bytes.Buffer{}
buf.WriteString("Remotes failed for:\n")
for _, item := range list {
buf.WriteString("\t")
buf.WriteString(item.Error())
buf.WriteString("\n")
}
return buf.String()
}
type VCSCmd struct {
*vcs.Cmd
}
func (vcsCmd *VCSCmd) RevisionSync(dir, revision string) error {
return vcsCmd.run(dir, vcsCmd.TagSyncCmd, "tag", revision)
}
func (v *VCSCmd) run(dir string, cmd string, keyval ...string) error {
_, err := v.run1(dir, cmd, keyval, true)
return err
}
// run1 is the generalized implementation of run and runOutput.
func (vcsCmd *VCSCmd) run1(dir string, cmdline string, keyval []string, verbose bool) ([]byte, error) {
v := vcsCmd.Cmd
m := make(map[string]string)
for i := 0; i < len(keyval); i += 2 {
m[keyval[i]] = keyval[i+1]
}
args := strings.Fields(cmdline)
for i, arg := range args {
args[i] = expand(m, arg)
}
_, err := exec.LookPath(v.Cmd)
if err != nil {
fmt.Fprintf(os.Stderr,
"go: missing %s command. See http://golang.org/s/gogetcmd\n",
v.Name)
return nil, err
}
cmd := exec.Command(v.Cmd, args...)
cmd.Dir = dir
cmd.Env = envForDir(cmd.Dir)
if vcs.ShowCmd {
fmt.Printf("cd %s\n", dir)
fmt.Printf("%s %s\n", v.Cmd, strings.Join(args, " "))
}
var buf bytes.Buffer
cmd.Stdout = &buf
cmd.Stderr = &buf
err = cmd.Run()
out := buf.Bytes()
if err != nil {
if verbose {
fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.Cmd, strings.Join(args, " "))
os.Stderr.Write(out)
}
return nil, err
}
return out, nil
}
// expand rewrites s to replace {k} with match[k] for each key k in match.
func expand(match map[string]string, s string) string {
for k, v := range match {
s = strings.Replace(s, "{"+k+"}", v, -1)
}
return s
}
// envForDir returns a copy of the environment
// suitable for running in the given directory.
// The environment is the current process's environment
// but with an updated $PWD, so that an os.Getwd in the
// child will be faster.
func envForDir(dir string) []string {
env := os.Environ()
// Internally we only use rooted paths, so dir is rooted.
// Even if dir is not rooted, no harm done.
return mergeEnvLists([]string{"PWD=" + dir}, env)
}
// mergeEnvLists merges the two environment lists such that
// variables with the same name in "in" replace those in "out".
func mergeEnvLists(in, out []string) []string {
NextVar:
for _, inkv := range in {
k := strings.SplitAfterN(inkv, "=", 2)[0]
for i, outkv := range out {
if strings.HasPrefix(outkv, k) {
out[i] = inkv
continue NextVar
}
}
out = append(out, inkv)
}
return out
}
func updateVcsCmd(cmd *vcs.Cmd) *VCSCmd {
switch cmd.Name {
case "Git":
cmd.TagSyncCmd = "reset --hard {tag}"
cmd.TagSyncDefault = "reset --hard origin/master"
cmd.DownloadCmd = "fetch"
case "Mercurial":
case "Bazaar":
case "Subversion":
}
return &VCSCmd{Cmd: cmd}
}
var isSecureScheme = map[string]bool{
"https": true,
"git+ssh": true,
"bzr+ssh": true,
"svn+ssh": true,
"ssh": true,
}
func vcsIsSecure(repo string) bool {
u, err := url.Parse(repo)
if err != nil {
// If repo is not a URL, it's not secure.
return false
}
return isSecureScheme[u.Scheme]
}
// Sync checks for outdated packages in the vendor folder and fetches the
// correct revision from the remote.
func (ctx *Context) Sync() (err error) {
// vcs.ShowCmd = true
outOfDate, err := ctx.VerifyVendor()
if err != nil {
return fmt.Errorf("Failed to verify checksums: %v", err)
}
// GOPATH includes the src dir, move up a level.
cacheRoot := filepath.Join(ctx.RootGopath, "..", ".cache", "govendor")
err = os.MkdirAll(cacheRoot, 0700)
if err != nil {
return err
}
// collect errors and proceed where you can.
rem := remoteFailureList{}
h := sha1.New()
updatedVendorFile := false
for _, vp := range outOfDate {
// Bundle packages together that have the same revision and share at least one root segment.
if len(vp.Revision) == 0 {
continue
}
from := vp.Path
if len(vp.Origin) > 0 {
from = vp.Origin
}
pkgDir := filepath.Join(cacheRoot, from)
// See if repo exists.
sysVcsCmd, repoRoot, err := vcs.FromDir(pkgDir, cacheRoot)
var vcsCmd *VCSCmd
repoRootDir := filepath.Join(cacheRoot, repoRoot)
if err != nil {
rr, err := vcs.RepoRootForImportPath(from, false)
if err != nil {
rem = append(rem, remoteFailure{Msg: "failed to ping remote repo", Path: vp.Path, Err: err})
continue
}
if !ctx.Insecure && !vcsIsSecure(rr.Repo) {
rem = append(rem, remoteFailure{Msg: "repo remote not secure", Path: vp.Path, Err: nil})
continue
}
vcsCmd = updateVcsCmd(rr.VCS)
repoRoot = rr.Root
repoRootDir = filepath.Join(cacheRoot, repoRoot)
err = os.MkdirAll(repoRootDir, 0700)
if err != nil {
rem = append(rem, remoteFailure{Msg: "failed to make repo root dir", Path: vp.Path, Err: err})
continue
}
err = vcsCmd.CreateAtRev(repoRootDir, rr.Repo, vp.Revision)
if err != nil {
rem = append(rem, remoteFailure{Msg: "failed to clone repo", Path: vp.Path, Err: err})
continue
}
} else {
vcsCmd = updateVcsCmd(sysVcsCmd)
err = vcsCmd.Download(repoRootDir)
if err != nil {
rem = append(rem, remoteFailure{Msg: "failed to download repo", Path: vp.Path, Err: err})
continue
}
err = vcsCmd.RevisionSync(repoRootDir, vp.Revision)
if err != nil {
rem = append(rem, remoteFailure{Msg: "failed to sync repo to " + vp.Revision, Path: vp.Path, Err: err})
continue
}
}
dest := filepath.Join(ctx.RootDir, ctx.VendorFolder, pathos.SlashToFilepath(vp.Path))
// Path handling with single sub-packages and differing origins need to be properly handled.
src := pkgDir
// Scan go files for files that should be ignored based on tags and filenames.
ignoreFiles, _, err := ctx.getIngoreFiles(src)
if err != nil {
rem = append(rem, remoteFailure{Msg: "failed to get ignore files", Path: vp.Path, Err: err})
continue
}
root, _ := pathos.TrimCommonSuffix(src, vp.Path)
// Need to ensure we copy files from "b.Root/<import-path>" for the following command.
ctx.CopyPackage(dest, src, root, vp.Path, ignoreFiles, vp.Tree, h, nil)
checksum := h.Sum(nil)
h.Reset()
vp.ChecksumSHA1 = base64.StdEncoding.EncodeToString(checksum)
updatedVendorFile = true
}
// Only write a vendor file if something changes.
if updatedVendorFile {
err = ctx.WriteVendorFile()
if err != nil {
return err
}
}
// Return network errors here.
if len(rem) > 0 {
return rem
}
return nil
}