forked from gpmgo/gopm
/
google.go
285 lines (242 loc) · 7.15 KB
/
google.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
// Copyright 2013 gopm authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package doc
import (
"archive/zip"
"bytes"
"errors"
"io"
"net/http"
"os"
"path"
"regexp"
"strings"
"github.com/Unknwon/com"
"github.com/codegangsta/cli"
"github.com/gpmgo/gopm/log"
)
var (
googleRepoRe = regexp.MustCompile(`id="checkoutcmd">(hg|git|svn)`)
googleRevisionRe = regexp.MustCompile(`<h2>(?:[^ ]+ - )?Revision *([^:]+):`)
googleFileRe = regexp.MustCompile(`<li><a href="([^"/]+)"`)
googleDirRe = regexp.MustCompile(`<li><a href="([^".]+)"`)
googlePattern = regexp.MustCompile(`^code\.google\.com/p/(?P<repo>[a-z0-9\-]+)(:?\.(?P<subrepo>[a-z0-9\-]+))?(?P<dir>/[a-z0-9A-Z_.\-/]+)?$`)
)
// getGoogleDoc downloads raw files from code.google.com.
func getGoogleDoc(client *http.Client, match map[string]string, installRepoPath string, nod *Node, ctx *cli.Context) ([]string, error) {
setupGoogleMatch(match)
// Check version control.
if err := getGoogleVCS(client, match); err != nil {
return nil, errors.New("fail to get vcs " + nod.ImportPath + " : " + err.Error())
}
switch nod.Type {
case BRANCH:
if len(nod.Value) == 0 {
match["tag"] = defaultTags[match["vcs"]]
// Only get and check revision with the latest version.
p, err := com.HttpGetBytes(client,
com.Expand("http://{subrepo}{dot}{repo}.googlecode.com/{vcs}{dir}/?r={tag}", match), nil)
if err != nil {
log.Error("GET", "Fail to get revision")
log.Error("", err.Error())
break
}
if m := googleRevisionRe.FindSubmatch(p); m == nil {
log.Error("GET", "Fail to get revision")
log.Error("", err.Error())
} else {
etag := string(m[1])
if etag == nod.Revision {
log.Log("GET Package hasn't changed: %s", nod.ImportPath)
return nil, nil
}
nod.Revision = etag
}
} else {
match["tag"] = nod.Value
}
case TAG, COMMIT:
match["tag"] = nod.Value
default:
return nil, errors.New("Unknown node type: " + nod.Type)
}
var installPath string
projectPath := GetProjectPath(nod.ImportPath)
if nod.ImportPath == nod.DownloadURL {
suf := "." + nod.Value
if len(suf) == 1 {
suf = ""
}
installPath = installRepoPath + "/" + projectPath + suf
} else {
installPath = installRepoPath + "/" + projectPath
}
// Remove old files.
os.RemoveAll(installPath + "/")
os.MkdirAll(installPath+"/", os.ModePerm)
if match["vcs"] == "svn" {
com.ColorLog("[WARN] SVN detected, may take very long time.\n")
rootPath := com.Expand("http://{subrepo}{dot}{repo}.googlecode.com/{vcs}", match)
d, f := path.Split(rootPath)
err := downloadFiles(client, match, d, installPath+"/", match["tag"],
[]string{f + "/"})
if err != nil {
return nil, errors.New("Fail to download " + nod.ImportPath + " : " + err.Error())
}
}
p, err := com.HttpGetBytes(client, com.Expand("http://{subrepo}{dot}{repo}.googlecode.com/archive/{tag}.zip", match), nil)
if err != nil {
return nil, errors.New("Fail to download " + nod.ImportPath + " : " + err.Error())
}
r, err := zip.NewReader(bytes.NewReader(p), int64(len(p)))
if err != nil {
return nil, errors.New(nod.ImportPath + " -> new zip: " + err.Error())
}
nameLen := strings.Index(r.File[0].Name, "/")
dirPrefix := match["dir"]
if len(dirPrefix) != 0 {
dirPrefix = dirPrefix[1:] + "/"
}
dirs := make([]string, 0, 5)
for _, f := range r.File {
absPath := strings.Replace(f.Name, f.Name[:nameLen], installPath, 1)
// Create diretory before create file.
dir := path.Dir(absPath)
if !checkDir(dir, dirs) && !(!ctx.Bool("example") && strings.Contains(absPath, "example")) {
dirs = append(dirs, dir+"/")
os.MkdirAll(dir+"/", os.ModePerm)
}
// Get file from archive.
r, err := f.Open()
if err != nil {
return nil, err
}
fbytes := make([]byte, f.FileInfo().Size())
_, err = io.ReadFull(r, fbytes)
if err != nil {
return nil, err
}
if err = com.WriteFile(absPath, fbytes); err != nil {
return nil, err
}
}
var imports []string
// Check if need to check imports.
if nod.IsGetDeps {
for _, d := range dirs {
importPkgs, err := CheckImports(d, match["importPath"], nod)
if err != nil {
return nil, err
}
imports = append(imports, importPkgs...)
}
}
return imports, err
}
type rawFile struct {
name string
rawURL string
data []byte
}
func (rf *rawFile) Name() string {
return rf.name
}
func (rf *rawFile) RawUrl() string {
return rf.rawURL
}
func (rf *rawFile) Data() []byte {
return rf.data
}
func (rf *rawFile) SetData(p []byte) {
rf.data = p
}
func downloadFiles(client *http.Client, match map[string]string, rootPath, installPath, commit string, dirs []string) error {
suf := "?r=" + commit
if len(commit) == 0 {
suf = ""
}
for _, d := range dirs {
p, err := com.HttpGetBytes(client, rootPath+d+suf, nil)
if err != nil {
return err
}
// Create destination directory.
os.MkdirAll(installPath+d, os.ModePerm)
// Get source files in current path.
files := make([]com.RawFile, 0, 5)
for _, m := range googleFileRe.FindAllSubmatch(p, -1) {
fname := strings.Split(string(m[1]), "?")[0]
files = append(files, &rawFile{
name: fname,
rawURL: rootPath + d + fname + suf,
})
}
// Fetch files from VCS.
if err := com.FetchFilesCurl(files); err != nil {
return err
}
// Save files.
for _, f := range files {
absPath := installPath + d
// Create diretory before create file.
os.MkdirAll(path.Dir(absPath), os.ModePerm)
// Write data to file
fw, err := os.Create(absPath + f.Name())
if err != nil {
return err
}
_, err = fw.Write(f.Data())
fw.Close()
if err != nil {
return err
}
}
files = nil
subdirs := make([]string, 0, 3)
// Get subdirectories.
for _, m := range googleDirRe.FindAllSubmatch(p, -1) {
dirName := strings.Split(string(m[1]), "?")[0]
if strings.HasSuffix(dirName, "/") {
subdirs = append(subdirs, d+dirName)
}
}
err = downloadFiles(client, match, rootPath, installPath, commit, subdirs)
if err != nil {
return err
}
}
return nil
}
func setupGoogleMatch(match map[string]string) {
if s := match["subrepo"]; s != "" {
match["dot"] = "."
match["query"] = "?repo=" + s
} else {
match["dot"] = ""
match["query"] = ""
}
}
func getGoogleVCS(client *http.Client, match map[string]string) error {
// Scrape the HTML project page to find the VCS.
p, err := com.HttpGetBytes(client, com.Expand("http://code.google.com/p/{repo}/source/checkout", match), nil)
if err != nil {
return errors.New("doc.getGoogleVCS(" + match["importPath"] + ") -> " + err.Error())
}
m := googleRepoRe.FindSubmatch(p)
if m == nil {
return com.NotFoundError{"Could not VCS on Google Code project page."}
}
match["vcs"] = string(m[1])
return nil
}