-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
adapter.github.js
243 lines (214 loc) · 8.53 KB
/
adapter.github.js
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
const
GH_RESERVED_USER_NAMES = [
'settings', 'orgs', 'organizations',
'site', 'blog', 'about', 'explore',
'styleguide', 'showcases', 'trending',
'stars', 'dashboard', 'notifications',
'search', 'developer', 'account'
]
, GH_RESERVED_REPO_NAMES = ['followers', 'following', 'repositories']
, GH_BRANCH_SEL = '*[data-master-branch]'
, GH_BRANCH_BTN_SEL = '*[data-master-branch] > .js-select-button'
, GH_404_SEL = '#parallax_wrapper'
, GH_PJAX_SEL = '#js-repo-pjax-container'
, GH_CONTAINERS = 'body > .container, .header > .container, .site > .container, .repohead > .container'
function GitHub() {}
/**
* Selects a submodule.
*/
GitHub.prototype.selectSubmodule = function(path) {
window.location.href = path
}
/**
* Selects a path.
*/
GitHub.prototype.selectPath = function(path, tabSize) {
var container = $(GH_PJAX_SEL)
, qs = tabSize ? ('?ts=' + tabSize) : ''
if (container.length) {
$.pjax({
// needs full path for pjax to work with Firefox as per cross-domain-content setting
url : location.protocol + '//' + location.host + path + qs,
container : container
})
}
else window.location.href = path + qs // falls back if no container (i.e. GitHub DOM has changed or is not yet available)
}
/**
* Updates page layout based on visibility status and width of the Octotree sidebar.
*/
GitHub.prototype.updateLayout = function(sidebarVisible, sidebarWidth) {
var $containers = $(GH_CONTAINERS)
$containers = $containers.length === 4 ? $containers : $('html') // falls-back if GH DOM is changed
if (sidebarVisible) $containers.css('margin-left', sidebarWidth + 10)
else $containers.css('margin-left', 'auto')
}
/**
* Returns the repository information if user is at a repository URL. Returns `null` otherwise.
*/
GitHub.prototype.getRepoFromPath = function(showInNonCodePage, currentRepo) {
// 404 page, skip
if ($(GH_404_SEL).length) return false
// (username)/(reponame)[/(subpart)]
var match = window.location.pathname.match(/([^\/]+)\/([^\/]+)(?:\/([^\/]+))?/)
if (!match) return false
// not a repository, skip
if (~GH_RESERVED_USER_NAMES.indexOf(match[1])) return false
if (~GH_RESERVED_REPO_NAMES.indexOf(match[2])) return false
// skip non-code page or not
if (!showInNonCodePage && match[3] && !~['tree', 'blob'].indexOf(match[3])) return false
// use selected branch, or previously selected branch, or master
var branch = $(GH_BRANCH_SEL).data('ref') ||
((currentRepo.username === match[1] && currentRepo.reponame === match[2] && currentRepo.branch)
? currentRepo.branch
: 'master')
return {
username : match[1],
reponame : match[2],
branch : branch
}
}
/**
* Fetches data of a particular repository.
* @param opts: { repo: repository, token (optional): user access token, apiUrl (optional): base API URL }
* @param cb(err: error, tree: array (of arrays) of items)
*/
GitHub.prototype.fetchData = function(opts, cb) {
var self = this
, repo = opts.repo
, folders = { '': [] }
, encodedBranch = encodeURIComponent(decodeURIComponent(repo.branch))
, $dummyDiv = $('<div/>')
getTree(encodedBranch + '?recursive=true', function(err, tree) {
if (err) return cb(err)
fetchSubmodules(function(err, submodules) {
if (err) return cb(err)
submodules = submodules || {}
// split work in chunks to prevent blocking UI on large repos
nextChunk(0)
function nextChunk(iteration) {
var chunkSize = 300
, baseIndex = iteration * chunkSize
, i
, item, path, type, index, name, moduleUrl
for (i = 0; i < chunkSize; i++) {
item = tree[baseIndex + i]
// we're done
if (item === undefined) return cb(null, folders[''])
path = item.path
type = item.type
index = path.lastIndexOf('/')
name = $dummyDiv.text(path.substring(index + 1)).html() // sanitizes, closes #9
item.id = PREFIX + path
item.text = name
item.icon = type // use `type` as class name for tree node
folders[path.substring(0, index)].push(item)
if (type === 'tree') {
folders[item.path] = item.children = []
item.a_attr = { href: '#' }
}
else if (type === 'blob') {
item.a_attr = { href: '/' + repo.username + '/' + repo.reponame + '/' + type + '/' + repo.branch + '/' + encodeURIComponent(path) /* closes #97 */ }
}
else if (type === 'commit') {
moduleUrl = submodules[item.path]
if (moduleUrl) { // fix #105
// special handling for submodules hosted in GitHub
if (~moduleUrl.indexOf('github.com')) {
moduleUrl = moduleUrl.replace(/^git:/, window.location.protocol)
.replace(/.git$/, '')
item.text = '<a href="' + moduleUrl + '" class="jstree-anchor">' + name + '</a>' +
'<span>@ </span>' +
'<a href="' + moduleUrl + '/tree/' + item.sha + '" class="jstree-anchor">' + item.sha.substr(0, 7) + '</a>'
}
item.a_attr = { href: moduleUrl }
}
}
}
setTimeout(function() {
nextChunk(iteration + 1)
}, 0)
}
})
function fetchSubmodules(cb) {
var item = tree.filter(function(item) { return /^\.gitmodules$/i.test(item.path) })[0]
if (!item) return cb()
getBlob(item.sha, function(err, data) {
if (err || !data) return cb(err)
parseGitmodules(data, cb)
})
}
})
function getTree(tree, cb) {
get('/git/trees/' + tree, function(err, res) {
if (err) return cb(err)
cb(null, res.tree)
})
}
function getBlob(sha, cb) {
get('/git/blobs/' + sha, function(err, res) {
if (err) return cb(err)
cb(null, atob(res.content.replace(/\n/g,'')))
})
}
function get(path, cb) {
var token = opts.token
, host = (location.host === 'github.com' ? 'api.github.com' : (location.host + '/api/v3'))
, base = location.protocol + '//' + host + '/repos/' + repo.username + '/' + repo.reponame
, cfg = { method: 'GET', url: base + path, cache: false }
if (token) cfg.headers = { Authorization: 'token ' + token }
$.ajax(cfg)
.done(function(data) {
cb(null, data)
})
.fail(function(jqXHR) {
var createTokenUrl = location.protocol + '//' + location.host + '/settings/tokens/new'
, error
, message
, needAuth
switch (jqXHR.status) {
case 0:
error = 'Connection error'
message = 'Cannot connect to GitHub. If your network connection to GitHub is fine, maybe there is an outage of the GitHub API. Please try again later.'
needAuth = false
break
case 401:
error = 'Invalid token'
message = 'The token is invalid. Follow <a href="' + createTokenUrl + '" target="_blank">this link</a> to create a new token and paste it below.'
needAuth = true
break
case 409:
error = 'Empty repository'
message = 'This repository is empty.'
break
case 404:
error = 'Private repository'
message = 'Accessing private repositories requires a GitHub access token. Follow <a href="' + createTokenUrl + '" target="_blank">this link</a> to create one and paste it below.'
needAuth = true
break
case 403:
if (~jqXHR.getAllResponseHeaders().indexOf('X-RateLimit-Remaining: 0')) {
error = 'API limit exceeded'
message = 'You have exceeded the GitHub API hourly limit and need GitHub access token to make extra requests. Follow <a href="' + createTokenUrl + '" target="_blank">this link</a> to create one and paste it below.'
needAuth = true
break
}
else {
error = 'Forbidden'
message = 'You are not allowed to access the API. You might need to provide an access token. Follow <a href="' + createTokenUrl + '" target="_blank">this link</a> to create one and paste it below.'
needAuth = true
break
}
default:
error = message = jqXHR.statusText
needAuth = false
break
}
cb({
error : 'Error: ' + error,
message : message,
needAuth : needAuth,
})
})
}
}