forked from golang/gddo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vcs.go
357 lines (315 loc) · 8.53 KB
/
vcs.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
// Copyright 2013 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 or at
// https://developers.google.com/open-source/licenses/bsd.
// +build !appengine
package gosrc
import (
"bytes"
"context"
"errors"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"time"
)
func init() {
addService(&service{
pattern: regexp.MustCompile(`^(?P<repo>(?:[a-z0-9.\-]+\.)+[a-z0-9.\-]+(?::[0-9]+)?/[A-Za-z0-9_.\-/]*?)\.(?P<vcs>bzr|git|hg|svn)(?P<dir>/[A-Za-z0-9_.\-/]*)?$`),
prefix: "",
get: getVCSDir,
})
getVCSDirFn = getVCSDir
}
const (
lsRemoteTimeout = 5 * time.Minute
cloneTimeout = 10 * time.Minute
fetchTimeout = 5 * time.Minute
checkoutTimeout = 1 * time.Minute
)
// Store temporary data in this directory.
var TempDir = filepath.Join(os.TempDir(), "gddo")
type urlTemplates struct {
re *regexp.Regexp
fileBrowse string
project string
line string
}
var vcsServices = []*urlTemplates{
{
regexp.MustCompile(`^git\.gitorious\.org/(?P<repo>[^/]+/[^/]+)$`),
"https://gitorious.org/{repo}/blobs/{tag}/{dir}{0}",
"https://gitorious.org/{repo}",
"%s#line%d",
},
{
regexp.MustCompile(`^git\.oschina\.net/(?P<repo>[^/]+/[^/]+)$`),
"http://git.oschina.net/{repo}/blob/{tag}/{dir}{0}",
"http://git.oschina.net/{repo}",
"%s#L%d",
},
{
regexp.MustCompile(`^(?P<r1>[^.]+)\.googlesource.com/(?P<r2>[^./]+)$`),
"https://{r1}.googlesource.com/{r2}/+/{tag}/{dir}{0}",
"https://{r1}.googlesource.com/{r2}/+/{tag}",
"%s#%d",
},
{
regexp.MustCompile(`^gitcafe.com/(?P<repo>[^/]+/.[^/]+)$`),
"https://gitcafe.com/{repo}/tree/{tag}/{dir}{0}",
"https://gitcafe.com/{repo}",
"",
},
}
// lookupURLTemplate finds an expand() template, match map and line number
// format for well known repositories.
func lookupURLTemplate(repo, dir, tag string) (*urlTemplates, map[string]string) {
if strings.HasPrefix(dir, "/") {
dir = dir[1:] + "/"
}
for _, t := range vcsServices {
if m := t.re.FindStringSubmatch(repo); m != nil {
match := map[string]string{
"dir": dir,
"tag": tag,
}
for i, name := range t.re.SubexpNames() {
if name != "" {
match[name] = m[i]
}
}
return t, match
}
}
return &urlTemplates{}, nil
}
type vcsCmd struct {
schemes []string
download func(schemes []string, clonePath, repo, savedEtag string) (tag, etag string, err error)
}
var vcsCmds = map[string]*vcsCmd{
"git": {
schemes: []string{"http", "https", "ssh", "git"},
download: downloadGit,
},
"svn": {
schemes: []string{"http", "https", "svn"},
download: downloadSVN,
},
}
var lsremoteRe = regexp.MustCompile(`(?m)^([0-9a-f]{40})\s+refs/(?:tags|heads)/(.+)$`)
func downloadGit(schemes []string, clonePath, repo, savedEtag string) (string, string, error) {
var p []byte
var scheme string
for i := range schemes {
cmd := exec.Command("git", "ls-remote", "--heads", "--tags", schemes[i]+"://"+clonePath)
log.Println(strings.Join(cmd.Args, " "))
var err error
p, err = outputWithTimeout(cmd, lsRemoteTimeout)
if err == nil {
scheme = schemes[i]
break
}
}
if scheme == "" {
return "", "", NotFoundError{Message: "VCS not found"}
}
tags := make(map[string]string)
for _, m := range lsremoteRe.FindAllSubmatch(p, -1) {
tags[string(m[2])] = string(m[1])
}
tag, commit, err := bestTag(tags, "master")
if err != nil {
return "", "", err
}
etag := scheme + "-" + commit
if etag == savedEtag {
return "", "", NotModifiedError{}
}
dir := filepath.Join(TempDir, repo+".git")
p, err = ioutil.ReadFile(filepath.Join(dir, ".git", "HEAD"))
switch {
case err != nil:
if err := os.MkdirAll(dir, 0777); err != nil {
return "", "", err
}
cmd := exec.Command("git", "clone", scheme+"://"+clonePath, dir)
log.Println(strings.Join(cmd.Args, " "))
if err := runWithTimeout(cmd, cloneTimeout); err != nil {
return "", "", err
}
case string(bytes.TrimRight(p, "\n")) == commit:
return tag, etag, nil
default:
cmd := exec.Command("git", "fetch")
log.Println(strings.Join(cmd.Args, " "))
cmd.Dir = dir
if err := runWithTimeout(cmd, fetchTimeout); err != nil {
return "", "", err
}
}
cmd := exec.Command("git", "checkout", "--detach", "--force", commit)
cmd.Dir = dir
if err := runWithTimeout(cmd, checkoutTimeout); err != nil {
return "", "", err
}
return tag, etag, nil
}
func downloadSVN(schemes []string, clonePath, repo, savedEtag string) (string, string, error) {
var scheme string
var revno string
for i := range schemes {
var err error
revno, err = getSVNRevision(schemes[i] + "://" + clonePath)
if err == nil {
scheme = schemes[i]
break
}
}
if scheme == "" {
return "", "", NotFoundError{Message: "VCS not found"}
}
etag := scheme + "-" + revno
if etag == savedEtag {
return "", "", NotModifiedError{}
}
dir := filepath.Join(TempDir, repo+".svn")
localRevno, err := getSVNRevision(dir)
switch {
case err != nil:
log.Printf("err: %v", err)
if err := os.MkdirAll(dir, 0777); err != nil {
return "", "", err
}
cmd := exec.Command("svn", "checkout", scheme+"://"+clonePath, "-r", revno, dir)
log.Println(strings.Join(cmd.Args, " "))
if err := runWithTimeout(cmd, cloneTimeout); err != nil {
return "", "", err
}
case localRevno != revno:
cmd := exec.Command("svn", "update", "-r", revno)
log.Println(strings.Join(cmd.Args, " "))
cmd.Dir = dir
if err := runWithTimeout(cmd, fetchTimeout); err != nil {
return "", "", err
}
}
return "", etag, nil
}
var svnrevRe = regexp.MustCompile(`(?m)^Last Changed Rev: ([0-9]+)$`)
func getSVNRevision(target string) (string, error) {
cmd := exec.Command("svn", "info", target)
log.Println(strings.Join(cmd.Args, " "))
out, err := outputWithTimeout(cmd, lsRemoteTimeout)
if err != nil {
return "", err
}
match := svnrevRe.FindStringSubmatch(string(out))
if match != nil {
return match[1], nil
}
return "", NotFoundError{Message: "Last changed revision not found"}
}
func getVCSDir(ctx context.Context, client *http.Client, match map[string]string, etagSaved string) (*Directory, error) {
cmd := vcsCmds[match["vcs"]]
if cmd == nil {
return nil, NotFoundError{Message: expand("VCS not supported: {vcs}", match)}
}
scheme := match["scheme"]
if scheme == "" {
i := strings.Index(etagSaved, "-")
if i > 0 {
scheme = etagSaved[:i]
}
}
schemes := cmd.schemes
if scheme != "" {
for i := range cmd.schemes {
if cmd.schemes[i] == scheme {
schemes = cmd.schemes[i : i+1]
break
}
}
}
clonePath, ok := match["clonePath"]
if !ok {
// clonePath may be unset if we're being called via the generic repo.vcs/dir regexp matcher.
// In that case, set it to the repo value.
clonePath = match["repo"]
}
// Download and checkout.
tag, etag, err := cmd.download(schemes, clonePath, match["repo"], etagSaved)
if err != nil {
return nil, err
}
// Find source location.
template, urlMatch := lookupURLTemplate(match["repo"], match["dir"], tag)
// Slurp source files.
d := filepath.Join(TempDir, filepath.FromSlash(expand("{repo}.{vcs}", match)), filepath.FromSlash(match["dir"]))
f, err := os.Open(d)
if err != nil {
if os.IsNotExist(err) {
err = NotFoundError{Message: err.Error()}
}
return nil, err
}
fis, err := f.Readdir(-1)
if err != nil {
return nil, err
}
var files []*File
var subdirs []string
for _, fi := range fis {
switch {
case fi.IsDir():
if isValidPathElement(fi.Name()) {
subdirs = append(subdirs, fi.Name())
}
case isDocFile(fi.Name()):
b, err := ioutil.ReadFile(filepath.Join(d, fi.Name()))
if err != nil {
return nil, err
}
files = append(files, &File{
Name: fi.Name(),
BrowseURL: expand(template.fileBrowse, urlMatch, fi.Name()),
Data: b,
})
}
}
return &Directory{
LineFmt: template.line,
ProjectRoot: expand("{repo}.{vcs}", match),
ProjectName: path.Base(match["repo"]),
ProjectURL: expand(template.project, urlMatch),
BrowseURL: "",
Etag: etag,
VCS: match["vcs"],
Subdirectories: subdirs,
Files: files,
}, nil
}
func runWithTimeout(cmd *exec.Cmd, timeout time.Duration) error {
if err := cmd.Start(); err != nil {
return err
}
t := time.AfterFunc(timeout, func() { cmd.Process.Kill() })
defer t.Stop()
return cmd.Wait()
}
func outputWithTimeout(cmd *exec.Cmd, timeout time.Duration) ([]byte, error) {
if cmd.Stdout != nil {
return nil, errors.New("exec: Stdout already set")
}
var b bytes.Buffer
cmd.Stdout = &b
err := runWithTimeout(cmd, timeout)
return b.Bytes(), err
}