forked from golang/gddo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
329 lines (281 loc) · 8.78 KB
/
github.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
// 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.
package gosrc
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"time"
)
func init() {
addService(&service{
pattern: regexp.MustCompile(`^github\.com/(?P<owner>[a-z0-9A-Z_.\-]+)/(?P<repo>[a-z0-9A-Z_.\-]+)(?P<dir>/[a-z0-9A-Z_.\-/]*)?$`),
prefix: "github.com/",
get: getGitHubDir,
getPresentation: getGitHubPresentation,
getProject: getGitHubProject,
})
addService(&service{
pattern: regexp.MustCompile(`^gist\.github\.com/(?P<gist>[a-z0-9A-Z_.\-]+)\.git$`),
prefix: "gist.github.com/",
get: getGistDir,
})
}
var (
gitHubRawHeader = http.Header{"Accept": {"application/vnd.github-blob.raw"}}
gitHubPreviewHeader = http.Header{"Accept": {"application/vnd.github.preview"}}
ownerRepoPat = regexp.MustCompile(`^https://api.github.com/repos/([^/]+)/([^/]+)/`)
)
func gitHubError(resp *http.Response) error {
var e struct {
Message string `json:"message"`
}
if err := json.NewDecoder(resp.Body).Decode(&e); err == nil {
return &RemoteError{resp.Request.URL.Host, fmt.Errorf("%d: %s (%s)", resp.StatusCode, e.Message, resp.Request.URL.String())}
}
return &RemoteError{resp.Request.URL.Host, fmt.Errorf("%d: (%s)", resp.StatusCode, resp.Request.URL.String())}
}
func getGitHubDir(client *http.Client, match map[string]string, savedEtag string) (*Directory, error) {
c := &httpClient{client: client, errFn: gitHubError}
type refJSON struct {
Object struct {
Type string
Sha string
URL string
}
Ref string
URL string
}
var refs []*refJSON
resp, err := c.getJSON(expand("https://api.github.com/repos/{owner}/{repo}/git/refs", match), &refs)
if err != nil {
return nil, err
}
// If the response contains a Link header, then fallback to requesting "master" and "go1" by name.
if resp.Header.Get("Link") != "" {
var masterRef refJSON
if _, err := c.getJSON(expand("https://api.github.com/repos/{owner}/{repo}/git/refs/heads/master", match), &masterRef); err == nil {
refs = append(refs, &masterRef)
}
var go1Ref refJSON
if _, err := c.getJSON(expand("https://api.github.com/repos/{owner}/{repo}/git/refs/tags/go1", match), &go1Ref); err == nil {
refs = append(refs, &go1Ref)
}
}
tags := make(map[string]string)
for _, ref := range refs {
switch {
case strings.HasPrefix(ref.Ref, "refs/heads/"):
tags[ref.Ref[len("refs/heads/"):]] = ref.Object.Sha
case strings.HasPrefix(ref.Ref, "refs/tags/"):
tags[ref.Ref[len("refs/tags/"):]] = ref.Object.Sha
}
}
var commit string
match["tag"], commit, err = bestTag(tags, "master")
if err != nil {
return nil, err
}
if commit == savedEtag {
return nil, ErrNotModified
}
var contents []*struct {
Type string
Name string
GitURL string `json:"git_url"`
HTMLURL string `json:"html_url"`
}
if _, err := c.getJSON(expand("https://api.github.com/repos/{owner}/{repo}/contents{dir}?ref={tag}", match), &contents); err != nil {
return nil, err
}
if len(contents) == 0 {
return nil, NotFoundError{Message: "No files in directory."}
}
// GitHub owner and repo names are case-insensitive. Redirect if requested
// names do not match the canonical names in API response.
if m := ownerRepoPat.FindStringSubmatch(contents[0].GitURL); m != nil && (m[1] != match["owner"] || m[2] != match["repo"]) {
match["owner"] = m[1]
match["repo"] = m[2]
return nil, NotFoundError{
Message: "Github import path has incorrect case.",
Redirect: expand("github.com/{owner}/{repo}{dir}", match),
}
}
var files []*File
var dataURLs []string
var subdirs []string
for _, item := range contents {
switch {
case item.Type == "dir":
if isValidPathElement(item.Name) {
subdirs = append(subdirs, item.Name)
}
case isDocFile(item.Name):
files = append(files, &File{Name: item.Name, BrowseURL: item.HTMLURL})
dataURLs = append(dataURLs, item.GitURL)
}
}
c.header = gitHubRawHeader
if err := c.getFiles(dataURLs, files); err != nil {
return nil, err
}
browseURL := expand("https://github.com/{owner}/{repo}", match)
if match["dir"] != "" {
browseURL = expand("https://github.com/{owner}/{repo}/tree/{tag}{dir}", match)
}
var repo = struct {
Fork bool `json:"fork"`
CreatedAt time.Time `json:"created_at"`
PushedAt time.Time `json:"pushed_at"`
}{}
if _, err := c.getJSON(expand("https://api.github.com/repos/{owner}/{repo}", match), &repo); err != nil {
return nil, err
}
isDeadEndFork := repo.Fork && repo.PushedAt.Before(repo.CreatedAt)
return &Directory{
BrowseURL: browseURL,
Etag: commit,
Files: files,
LineFmt: "%s#L%d",
ProjectName: match["repo"],
ProjectRoot: expand("github.com/{owner}/{repo}", match),
ProjectURL: expand("https://github.com/{owner}/{repo}", match),
Subdirectories: subdirs,
VCS: "git",
DeadEndFork: isDeadEndFork,
}, nil
}
func getGitHubPresentation(client *http.Client, match map[string]string) (*Presentation, error) {
c := &httpClient{client: client, header: gitHubRawHeader}
p, err := c.getBytes(expand("https://api.github.com/repos/{owner}/{repo}/contents{dir}/{file}", match))
if err != nil {
return nil, err
}
apiBase, err := url.Parse(expand("https://api.github.com/repos/{owner}/{repo}/contents{dir}/", match))
if err != nil {
return nil, err
}
rawBase, err := url.Parse(expand("https://raw.github.com/{owner}/{repo}/master{dir}/", match))
if err != nil {
return nil, err
}
c.header = gitHubRawHeader
b := &presBuilder{
data: p,
filename: match["file"],
fetch: func(fnames []string) ([]*File, error) {
var files []*File
var dataURLs []string
for _, fname := range fnames {
u, err := apiBase.Parse(fname)
if err != nil {
return nil, err
}
u.RawQuery = apiBase.RawQuery
files = append(files, &File{Name: fname})
dataURLs = append(dataURLs, u.String())
}
err := c.getFiles(dataURLs, files)
return files, err
},
resolveURL: func(fname string) string {
u, err := rawBase.Parse(fname)
if err != nil {
return "/notfound"
}
if strings.HasSuffix(fname, ".svg") {
u.Host = "rawgithub.com"
}
return u.String()
},
}
return b.build()
}
// GetGitHubUpdates returns the full names ("owner/repo") of recently pushed GitHub repositories.
// by pushedAfter.
func GetGitHubUpdates(client *http.Client, pushedAfter string) (maxPushedAt string, names []string, err error) {
c := httpClient{client: client, header: gitHubPreviewHeader}
if pushedAfter == "" {
pushedAfter = time.Now().Add(-24 * time.Hour).UTC().Format("2006-01-02T15:04:05Z")
}
u := "https://api.github.com/search/repositories?order=asc&sort=updated&q=fork:true+language:Go+pushed:>" + pushedAfter
var updates struct {
Items []struct {
FullName string `json:"full_name"`
PushedAt string `json:"pushed_at"`
}
}
_, err = c.getJSON(u, &updates)
if err != nil {
return pushedAfter, nil, err
}
maxPushedAt = pushedAfter
for _, item := range updates.Items {
names = append(names, item.FullName)
if item.PushedAt > maxPushedAt {
maxPushedAt = item.PushedAt
}
}
return maxPushedAt, names, nil
}
func getGitHubProject(client *http.Client, match map[string]string) (*Project, error) {
c := &httpClient{client: client, errFn: gitHubError}
var repo struct {
Description string
}
if _, err := c.getJSON(expand("https://api.github.com/repos/{owner}/{repo}", match), &repo); err != nil {
return nil, err
}
return &Project{
Description: repo.Description,
}, nil
}
func getGistDir(client *http.Client, match map[string]string, savedEtag string) (*Directory, error) {
c := &httpClient{client: client, errFn: gitHubError}
var gist struct {
Files map[string]struct {
Content string
}
HtmlUrl string `json:"html_url"`
History []struct {
Version string
}
}
if _, err := c.getJSON(expand("https://api.github.com/gists/{gist}", match), &gist); err != nil {
return nil, err
}
if len(gist.History) == 0 {
return nil, NotFoundError{Message: "History not found."}
}
commit := gist.History[0].Version
if commit == savedEtag {
return nil, ErrNotModified
}
var files []*File
for name, file := range gist.Files {
if isDocFile(name) {
files = append(files, &File{
Name: name,
Data: []byte(file.Content),
BrowseURL: gist.HtmlUrl + "#file-" + strings.Replace(name, ".", "-", -1),
})
}
}
return &Directory{
BrowseURL: gist.HtmlUrl,
Etag: commit,
Files: files,
LineFmt: "%s-L%d",
ProjectName: match["gist"],
ProjectRoot: expand("gist.github.com/{gist}.git", match),
ProjectURL: gist.HtmlUrl,
Subdirectories: nil,
VCS: "git",
}, nil
}