git ssb

30+

cel / git-ssb-web



Tree: fb416ad1c63eb661888fd5c6fd9e9d6f1fbb98f0

Files: fb416ad1c63eb661888fd5c6fd9e9d6f1fbb98f0 / lib / repos / index.js

38873 bytesRaw
1var url = require('url')
2var pull = require('pull-stream')
3var once = pull.once
4var cat = require('pull-cat')
5var paramap = require('pull-paramap')
6var multicb = require('multicb')
7var JsDiff = require('diff')
8var GitRepo = require('pull-git-repo')
9var gitPack = require('pull-git-pack')
10var u = require('../util')
11var paginate = require('../paginate')
12var markdown = require('../markdown')
13var forms = require('../forms')
14var ssbRef = require('ssb-ref')
15var zlib = require('zlib')
16var toPull = require('stream-to-pull-stream')
17var h = require('pull-hyperscript')
18
19function extend(obj, props) {
20 for (var k in props)
21 obj[k] = props[k]
22 return obj
23}
24
25module.exports = function (web) {
26 return new RepoRoutes(web)
27}
28
29function RepoRoutes(web) {
30 this.web = web
31 this.issues = require('./issues')(this, web)
32 this.pulls = require('./pulls')(this, web)
33}
34
35var R = RepoRoutes.prototype
36
37function getRepoObjectString(repo, id, mode, cb) {
38 if (!id) return cb(null, '')
39 if (mode == 0160000) return cb(null,
40 'Subproject commit ' + id)
41 repo.getObjectFromAny(id, function (err, obj) {
42 if (err) return cb(err)
43 u.readObjectString(obj, cb)
44 })
45}
46
47/* Repo */
48
49R.serveRepoPage = function (req, repo, path) {
50 var self = this
51 var defaultBranch = 'master'
52 var query = req._u.query
53
54 if (query.rev != null) {
55 // Allow navigating revs using GET query param.
56 // Replace the branch in the path with the rev query value
57 path[0] = path[0] || 'tree'
58 path[1] = query.rev
59 req._u.pathname = u.encodeLink([repo.id].concat(path))
60 delete req._u.query.rev
61 delete req._u.search
62 return self.web.serveRedirect(req, url.format(req._u))
63 }
64
65 // get branch
66 return path[1] ?
67 R_serveRepoPage2.call(self, req, repo, path) :
68 u.readNext(function (cb) {
69 // TODO: handle this in pull-git-repo or ssb-git-repo
70 repo.getSymRef('HEAD', true, function (err, ref) {
71 if (err) return cb(err)
72 repo.resolveRef(ref, function (err, rev) {
73 path[1] = rev ? ref : null
74 cb(null, R_serveRepoPage2.call(self, req, repo, path))
75 })
76 })
77 })
78}
79
80function R_serveRepoPage2(req, repo, path) {
81 var branch = path[1]
82 var filePath = path.slice(2)
83 switch (path[0]) {
84 case undefined:
85 case '':
86 return this.serveRepoTree(req, repo, branch, [])
87 case 'activity':
88 return this.serveRepoActivity(req, repo, branch)
89 case 'commits':
90 return this.serveRepoCommits(req, repo, branch)
91 case 'commit':
92 return this.serveRepoCommit(req, repo, path[1])
93 case 'tag':
94 return this.serveRepoTag(req, repo, branch, filePath)
95 case 'tree':
96 return this.serveRepoTree(req, repo, branch, filePath)
97 case 'blob':
98 return this.serveRepoBlob(req, repo, branch, filePath)
99 case 'raw':
100 return this.serveRepoRaw(req, repo, branch, filePath)
101 case 'digs':
102 return this.serveRepoDigs(req, repo)
103 case 'fork':
104 return this.serveRepoForkPrompt(req, repo)
105 case 'forks':
106 return this.serveRepoForks(req, repo)
107 case 'issues':
108 switch (path[1]) {
109 case 'new':
110 if (filePath.length == 0)
111 return this.issues.serveRepoNewIssue(req, repo)
112 break
113 default:
114 return this.issues.serveRepoIssues(req, repo, false)
115 }
116 case 'pulls':
117 return this.issues.serveRepoIssues(req, repo, true)
118 case 'compare':
119 return this.pulls.serveRepoCompare(req, repo)
120 case 'comparing':
121 return this.pulls.serveRepoComparing(req, repo)
122 case 'info':
123 switch (path[1]) {
124 case 'refs':
125 return this.serveRepoRefs(req, repo)
126 default:
127 return this.web.serve404(req)
128 }
129 case 'objects':
130 switch (path[1]) {
131 case 'info':
132 switch (path[2]) {
133 case 'packs':
134 return this.serveRepoPacksInfo(req, repo)
135 default:
136 return this.web.serve404(req)
137 }
138 case 'pack':
139 return this.serveRepoPack(req, repo, filePath.join('/'))
140 default:
141 var hash = path[1] + path[2]
142 if (hash.length === 40) {
143 return this.serveRepoObject(req, repo, hash)
144 }
145 return this.web.serve404(req)
146 }
147 case 'HEAD':
148 return this.serveRepoHead(req, repo)
149 default:
150 return this.web.serve404(req)
151 }
152}
153
154R.serveRepoNotFound = function (req, id, err) {
155 return this.web.serveTemplate(req, req._t('error.RepoNotFound'), 404)
156 (pull.values([
157 '<h2>' + req._t('error.RepoNotFound') + '</h2>',
158 '<p>' + req._t('error.RepoNameNotFound') + '</p>',
159 '<pre>' + u.escape(err.stack) + '</pre>'
160 ]))
161}
162
163R.renderRepoPage = function (req, repo, page, branch, titleTemplate, body) {
164 var self = this
165 var gitUrl = 'ssb://' + repo.id
166 var host = req.headers.host || '127.0.0.1:7718'
167 var path = '/' + encodeURIComponent(repo.id)
168 var httpUrl = 'http://' + encodeURI(host) + path
169 var digsPath = [repo.id, 'digs']
170 var cloneUrls = '<span class="clone-urls">' +
171 '<select class="custom-dropdown clone-url-protocol" ' +
172 'onchange="this.nextSibling.value=this.value;this.nextSibling.select()">' +
173 '<option selected="selected" value="' + gitUrl + '">SSB</option>' +
174 '<option class="http-clone-url" value="' + httpUrl + '">HTTP</option>' +
175 '</select>' +
176 '<input class="clone-url" readonly="readonly" ' +
177 'value="ssb://' + repo.id + '" size="45" ' +
178 'onclick="this.select()"/>' +
179 '<script>' +
180 'var httpOpt = document.querySelector(".http-clone-url")\n' +
181 'if (location.protocol === "https:") httpOpt.text = "HTTPS"\n' +
182 'httpOpt.value = location.origin + "' + path + '"\n' +
183 '</script>' +
184 '</span>'
185
186 var done = multicb({ pluck: 1, spread: true })
187 self.web.getRepoName(repo.feed, repo.id, done())
188 self.web.about.getName(repo.feed, done())
189 self.web.getVotes(repo.id, done())
190
191 if (repo.upstream) {
192 self.web.getRepoName(repo.upstream.feed, repo.upstream.id, done())
193 self.web.about.getName(repo.upstream.feed, done())
194 }
195
196 return u.readNext(function (cb) {
197 done(function (err, repoName, authorName, votes, upstreamName, upstreamAuthorName) {
198 if (err) return cb(null, self.web.serveError(req, err))
199 var upvoted = votes.upvoters[self.web.myId] > 0
200 var upstreamLink = !repo.upstream ? '' :
201 u.link([repo.upstream])
202 var title = titleTemplate ? titleTemplate
203 .replace(/%\{repo\}/g, repoName)
204 .replace(/%\{author\}/g, authorName)
205 : authorName + '/' + repoName
206 var isPublic = self.web.isPublic
207 var isLocal = !isPublic
208 cb(null, self.web.serveTemplate(req, title)(cat([
209 h('div', {class: 'repo-title'}, [
210 h('form', {class: 'right-bar', action: '', method: 'post'}, [
211 h('strong', {class: 'ml2 mr1'}, u.link(digsPath, votes.upvotes)),
212 h('button',
213 extend(
214 {class: 'btn', name: 'action', value: 'vote'},
215 isPublic ? {disabled: 'disabled'} : {type: 'submit'}
216 ), [
217 h('i', '✌ '),
218 h('span', req._t(isLocal && upvoted ? 'Undig' : 'Dig'))
219 ]
220 ),
221 u.when(isLocal, cat([
222 h('input', {type: 'hidden', name: 'value', value: (upvoted ? '0' : '1')}),
223 h('input', {type: 'hidden', name: 'id', value: u.escape(repo.id)})
224 ])),
225 h('a', {href: u.encodeLink([repo.id, 'forks']), title: req._t('Forks'), class: 'ml2 mr1'}, '+'),
226 u.when(isLocal,
227 h('button', {class: 'btn', type: 'submit', name: 'action', value: 'fork-prompt'}, [
228 h('i', '⑂ '),
229 once(req._t('Fork'))
230 ])
231 )
232 ]),
233 forms.name(req, isLocal, repo.id, repoName, 'repo-name', null, req._t('repo.Rename'),
234 h('h2', {class: 'bgslash'}, `${u.link([repo.feed], authorName)} / ${u.link([repo.id], repoName)}`)
235 ),
236 ]),
237 (!repo.upstream
238 ? once('')
239 : h('small', {class: 'bgslash'}, req._t('ForkedFrom', {
240 repo: `${u.link([repo.upstream.feed], upstreamAuthorName)} / ${u.link([repo.upstream.id], upstreamName)}`
241 }))
242 //TODO (mix) replace the with when. It's reporteding repo.upstream is true, then undefined attr feed is requested!
243 ),
244 u.nav([
245 [[repo.id], req._t('Code'), 'code'],
246 [[repo.id, 'activity'], req._t('Activity'), 'activity'],
247 [[repo.id, 'commits', branch||''], req._t('Commits'), 'commits'],
248 [[repo.id, 'issues'], req._t('Issues'), 'issues'],
249 [[repo.id, 'pulls'], req._t('PullRequests'), 'pulls']
250 ], page, cloneUrls),
251 body
252 ])
253 ))
254 })
255 })
256}
257
258R.serveEmptyRepo = function (req, repo) {
259 if (repo.feed != this.web.myId)
260 return this.renderRepoPage(req, repo, 'code', null, null, pull.once(
261 '<section>' +
262 '<h3>' + req._t('EmptyRepo') + '</h3>' +
263 '</section>'))
264
265 var gitUrl = 'ssb://' + repo.id
266 return this.renderRepoPage(req, repo, 'code', null, null, pull.once(
267 '<section>' +
268 '<h3>' + req._t('initRepo.GettingStarted') + '</h3>' +
269 '<h4>' + req._t('initRepo.CreateNew') + '</h4><pre>' +
270 'touch ' + req._t('initRepo.README') + '.md\n' +
271 'git init\n' +
272 'git add ' + req._t('initRepo.README') + '.md\n' +
273 'git commit -m "' + req._t('initRepo.InitialCommit') + '"\n' +
274 'git remote add origin ' + gitUrl + '\n' +
275 'git push -u origin master</pre>\n' +
276 '<h4>' + req._t('initRepo.PushExisting') + '</h4>\n' +
277 '<pre>git remote add origin ' + gitUrl + '\n' +
278 'git push -u origin master</pre>' +
279 '</section>'))
280}
281
282R.serveRepoTree = function (req, repo, rev, path) {
283 var type = repo.isCommitHash(rev) ? 'Tree' : 'Branch'
284 var title = (path.length ? path.join('/') + ' · ' : '') +
285 '%{author}/%{repo}' +
286 (repo.head == 'refs/heads/' + rev ? '' : '@' + rev)
287 return this.renderRepoPage(req, repo, 'code', rev, title, cat([
288 pull.once('<section class="branch-info light-grey"><form action="" method="get">' +
289 '<h3>' + req._t(type) + ': '),
290 this.revMenu(req, repo, rev),
291 pull.once('</h3></form>'),
292 type == 'Branch' && renderRepoLatest(req, repo, rev),
293 pull.once('</section>'),
294 rev ? cat([
295 pull.once('<section class="files">'),
296 renderRepoTree(req, repo, rev, path),
297 pull.once('</section>'),
298 this.renderRepoReadme(req, repo, rev, path)
299 ]) : this.serveEmptyRepo(req, repo)
300 ]))
301}
302
303/* Repo activity */
304
305R.serveRepoActivity = function (req, repo, branch) {
306 var self = this
307 var title = req._t('Activity') + ' · %{author}/%{repo}'
308 return self.renderRepoPage(req, repo, 'activity', branch, title, cat([
309 pull.once('<h3>' + req._t('Activity') + '</h3>'),
310 pull(
311 self.web.ssb.links({
312 dest: repo.id,
313 rel: 'repo',
314 values: true,
315 reverse: true
316 }),
317 pull.asyncMap(renderRepoUpdate.bind(self, req, repo, false))
318 ),
319 u.readOnce(function (cb) {
320 var done = multicb({ pluck: 1, spread: true })
321 self.web.about.getName(repo.feed, done())
322 self.web.getMsg(repo.id, done())
323 done(function (err, authorName, msg) {
324 if (err) return cb(err)
325 self.web.renderFeedItem(req, {
326 key: repo.id,
327 value: msg,
328 authorName: authorName
329 }, cb)
330 })
331 })
332 ]))
333}
334
335function renderRepoUpdate(req, repo, full, msg, cb) {
336 var c = msg.value.content
337
338 if (c.type != 'git-update') {
339 return ''
340 // return renderFeedItem(msg, cb)
341 // TODO: render post, issue, pull-request
342 }
343
344 var branches = []
345 var tags = []
346 if (c.refs) for (var name in c.refs) {
347 var m = name.match(/^refs\/(heads|tags)\/(.*)$/) || [,, name]
348 ;(m[1] == 'tags' ? tags : branches)
349 .push({name: m[2], value: c.refs[name]})
350 }
351 var numObjects = c.objects ? Object.keys(c.objects).length : 0
352
353 var dateStr = new Date(msg.value.timestamp).toLocaleString(req._locale)
354
355 this.web.about.getName(msg.value.author, function (err, name) {
356 if (err) return cb(err)
357 cb(null, '<section class="collapse">' +
358 u.link([msg.key], dateStr) + '<br>' +
359 u.link([msg.value.author], name) + '<br>' +
360
361 branches.map(function (update) {
362 if (!update.value) {
363 return '<s>' + u.escape(update.name) + '</s><br/>'
364 } else {
365 var commitLink = u.link([repo.id, 'commit', update.value])
366 var branchLink = u.link([repo.id, 'tree', update.name])
367 return branchLink + ' &rarr; <tt>' + commitLink + '</tt><br/>'
368 }
369 }).join('') +
370 tags.map(function (update) {
371 return update.value
372 ? u.link([repo.id, 'tag', update.value], update.name)
373 : '<s>' + u.escape(update.name) + '</s>'
374 }).join(', ') +
375 '</section>')
376 })
377}
378
379/* Repo commits */
380
381R.serveRepoCommits = function (req, repo, branch) {
382 var query = req._u.query
383 var title = req._t('Commits') + ' · %{author}/%{repo}'
384 return this.renderRepoPage(req, repo, 'commits', branch, title, cat([
385 pull.once('<h3>' + req._t('Commits') + '</h3>'),
386 pull(
387 repo.readLog(query.start || branch),
388 pull.take(20),
389 paramap(repo.getCommitParsed.bind(repo), 8),
390 paginate(
391 !query.start ? '' : function (first, cb) {
392 cb(null, '&hellip;')
393 },
394 pull.map(renderCommit.bind(this, req, repo)),
395 function (commit, cb) {
396 cb(null, commit.parents && commit.parents[0] ?
397 '<a href="?start=' + commit.id + '">' +
398 req._t('Older') + '</a>' : '')
399 }
400 )
401 )
402 ]))
403}
404
405function renderCommit(req, repo, commit) {
406 var commitPath = [repo.id, 'commit', commit.id]
407 var treePath = [repo.id, 'tree', commit.id]
408 return '<section class="collapse">' +
409 '<strong>' + u.link(commitPath, commit.title) + '</strong><br>' +
410 '<tt>' + commit.id + '</tt> ' +
411 u.link(treePath, req._t('Tree')) + '<br>' +
412 u.escape(commit.author.name) + ' &middot; ' +
413 commit.author.date.toLocaleString(req._locale) +
414 (commit.separateAuthor ? '<br>' + req._t('CommittedOn', {
415 name: u.escape(commit.committer.name),
416 date: commit.committer.date.toLocaleString(req._locale)
417 }) : '') +
418 '</section>'
419}
420
421/* Branch menu */
422
423R.formatRevOptions = function (currentName) {
424 return function (name) {
425 var htmlName = u.escape(name)
426 return '<option value="' + htmlName + '"' +
427 (name == currentName ? ' selected="selected"' : '') +
428 '>' + htmlName + '</option>'
429 }
430}
431
432R.formatRevType = function(req, type) {
433 return (
434 type == 'heads' ? req._t('Branches') :
435 type == 'tags' ? req._t('Tags') :
436 type)
437}
438
439R.revMenu = function (req, repo, currentName) {
440 var self = this
441 return u.readOnce(function (cb) {
442 repo.getRefNames(function (err, refs) {
443 if (err) return cb(err)
444 cb(null, '<select class="custom-dropdown" name="rev" onchange="this.form.submit()">' +
445 Object.keys(refs).map(function (group) {
446 return '<optgroup ' +
447 'label="' + self.formatRevType(req, group) + '">' +
448 refs[group].map(self.formatRevOptions(currentName)).join('') +
449 '</optgroup>'
450 }).join('') +
451 '</select><noscript> ' +
452 '<input type="submit" value="' + req._t('Go') + '"/></noscript>')
453 })
454 })
455}
456
457/* Repo tree */
458
459function renderRepoLatest(req, repo, rev) {
460 if (!rev) return pull.empty()
461 return u.readOnce(function (cb) {
462 repo.getCommitParsed(rev, function (err, commit) {
463 if (err) return cb(err)
464 var commitPath = [repo.id, 'commit', commit.id]
465 var actor = commit.separateAuthor ? 'author' : 'committer'
466 var actionKey = actor.slice(0,1).toUpperCase() + actor.slice(1) + 'ReleasedCommit'
467 cb(null,
468 '<div class="mt2">' +
469 '<span>' +
470 req._t(actionKey, {
471 name: u.escape(commit[actor].name),
472 commitName: u.link(commitPath, commit.title)
473 }) +
474 '</span>' +
475 '<tt class="float-right">' +
476 req._t('LatestOn', {
477 commitId: commit.id.slice(0, 7),
478 date: commit[actor].date.toLocaleString(req._locale)
479 }) +
480 '</tt>' +
481 '</div>'
482 )
483 })
484 })
485}
486
487// breadcrumbs
488function linkPath(basePath, path) {
489 path = path.slice()
490 var last = path.pop()
491 return path.map(function (dir, i) {
492 return u.link(basePath.concat(path.slice(0, i+1)), dir)
493 }).concat(last).join(' / ')
494}
495
496function renderRepoTree(req, repo, rev, path) {
497 var source = repo.readDir(rev,path)
498 var pathLinks = path.length === 0 ? '' :
499 ': ' + linkPath([repo.id, 'tree'], [rev].concat(path))
500
501 var location = once('')
502 if (path.length !== 0) {
503 var link = linkPath([repo.id, 'tree'], [rev].concat(path))
504 location = h('div', {class: 'fileLocation'}, `${req._t('Files')}: ${link}`)
505 }
506
507 return cat([
508 location,
509 h('table', {class: "files w-100"}, u.sourceMap(source, file =>
510 h('tr', [
511 h('td', [
512 h('i', fileIcon(file))
513 ]),
514 h('td', u.link(filePath(file), file.name))
515 ])
516 ))
517 ])
518
519 function fileIcon(file) {
520 return fileType(file) === 'tree' ? '📁' : '📄'
521 }
522
523 function filePath(file) {
524 var type = fileType(file)
525 return [repo.id, type, rev].concat(path, file.name)
526 }
527
528 function fileType(file) {
529 if (file.mode === 040000) return 'tree'
530 else if (file.mode === 0160000) return 'commit'
531 else return 'blob'
532 }
533}
534
535/* Repo readme */
536
537R.renderRepoReadme = function (req, repo, branch, path) {
538 var self = this
539 return u.readNext(function (cb) {
540 pull(
541 repo.readDir(branch, path),
542 pull.filter(function (file) {
543 return /readme(\.|$)/i.test(file.name)
544 }),
545 pull.take(1),
546 pull.collect(function (err, files) {
547 if (err) return cb(null, pull.empty())
548 var file = files[0]
549 if (!file)
550 return cb(null, pull.once(path.length ? '' :
551 '<p>' + req._t('NoReadme') + '</p>'))
552 repo.getObjectFromAny(file.id, function (err, obj) {
553 if (err) return cb(err)
554 cb(null, cat([
555 pull.once('<section class="readme">'),
556 self.web.renderObjectData(obj, file.name, repo, branch, path),
557 pull.once('</section>')
558 ]))
559 })
560 })
561 )
562 })
563}
564
565/* Repo commit */
566
567R.serveRepoCommit = function (req, repo, rev) {
568 var self = this
569 return u.readNext(function (cb) {
570 repo.getCommitParsed(rev, function (err, commit) {
571 if (err) return cb(err)
572 var commitPath = [repo.id, 'commit', commit.id]
573 var treePath = [repo.id, 'tree', commit.id]
574 var title = u.escape(commit.title) + ' · ' +
575 '%{author}/%{repo}@' + commit.id.substr(0, 8)
576 cb(null, self.renderRepoPage(req, repo, null, rev, title, cat([
577 pull.once(
578 '<h3>' + u.link(commitPath,
579 req._t('CommitRev', {rev: rev})) + '</h3>' +
580 '<section class="collapse">' +
581 '<div class="right-bar">' +
582 u.link(treePath, req._t('BrowseFiles')) +
583 '</div>' +
584 '<h4>' + u.linkify(u.escape(commit.title)) + '</h4>' +
585 (commit.body ? u.linkify(u.pre(commit.body)) : '') +
586 (commit.separateAuthor ? req._t('AuthoredOn', {
587 name: u.escape(commit.author.name),
588 date: commit.author.date.toLocaleString(req._locale)
589 }) + '<br/>' : '') +
590 req._t('CommittedOn', {
591 name: u.escape(commit.committer.name),
592 date: commit.committer.date.toLocaleString(req._locale)
593 }) + '<br/>' +
594 commit.parents.map(function (id) {
595 return req._t('Parent') + ': ' +
596 u.link([repo.id, 'commit', id], id)
597 }).join('<br>') +
598 '</section>' +
599 '<section><h3>' + req._t('FilesChanged') + '</h3>'),
600 // TODO: show diff from all parents (merge commits)
601 self.renderDiffStat(req, [repo, repo], [commit.parents[0], commit.id]),
602 pull.once('</section>')
603 ])))
604 })
605 })
606}
607
608/* Repo tag */
609
610R.serveRepoTag = function (req, repo, rev, path) {
611 var self = this
612 return u.readNext(function (cb) {
613 repo.getTagParsed(rev, function (err, tag) {
614 if (err) {
615 if (/Expected tag, got commit/.test(err.message)) {
616 req._u.pathname = u.encodeLink([repo.id, 'commit', rev].concat(path))
617 return cb(null, self.web.serveRedirect(req, url.format(req._u)))
618 }
619 return cb(null, self.web.serveError(req, err))
620 }
621
622 var title = req._t('TagName', {
623 tag: u.escape(tag.tag)
624 }) + ' · %{author}/%{repo}'
625 var body = (tag.title + '\n\n' +
626 tag.body.replace(/-----BEGIN PGP SIGNATURE-----\n[^.]*?\n-----END PGP SIGNATURE-----\s*$/, '')).trim()
627 var date = tag.tagger.date
628 cb(null, self.renderRepoPage(req, repo, 'tags', tag.object, title,
629 pull.once(
630 '<section class="collapse">' +
631 '<h3>' + u.link([repo.id, 'tag', rev], tag.tag) + '</h3>' +
632 req._t('TaggedOn', {
633 name: u.escape(tag.tagger.name),
634 date: date && date.toLocaleString(req._locale)
635 }) + '<br/>' +
636 u.link([repo.id, tag.type, tag.object]) +
637 u.linkify(u.pre(body)) +
638 '</section>')))
639 })
640 })
641}
642
643
644/* Diff stat */
645
646R.renderDiffStat = function (req, repos, treeIds) {
647 if (treeIds.length == 0) treeIds = [null]
648 var id = treeIds[0]
649 var lastI = treeIds.length - 1
650 var oldTree = treeIds[0]
651 var changedFiles = []
652 var source = GitRepo.diffTrees(repos, treeIds, true)
653
654 return cat([
655 h('table', u.sourceMap(source, item => {
656 var filename = u.escape(item.filename = item.path.join('/'))
657 var oldId = item.id && item.id[0]
658 var newId = item.id && item.id[lastI]
659 var oldMode = item.mode && item.mode[0]
660 var newMode = item.mode && item.mode[lastI]
661 var action =
662 !oldId && newId ? req._t('action.added') :
663 oldId && !newId ? req._t('action.deleted') :
664 oldMode != newMode ? req._t('action.changedMode', {
665 old: oldMode.toString(8),
666 new: newMode.toString(8)
667 }) : req._t('changed')
668 if (item.id)
669 changedFiles.push(item)
670 var blobsPath = item.id[1]
671 ? [repos[1].id, 'blob', treeIds[1]]
672 : [repos[0].id, 'blob', treeIds[0]]
673 var rawsPath = item.id[1]
674 ? [repos[1].id, 'raw', treeIds[1]]
675 : [repos[0].id, 'raw', treeIds[0]]
676 item.blobPath = blobsPath.concat(item.path)
677 item.rawPath = rawsPath.concat(item.path)
678 var fileHref = item.id ?
679 '#' + encodeURIComponent(item.path.join('/')) :
680 u.encodeLink(item.blobPath)
681
682 return h('tr', [
683 h('td', [
684 h('a', {href: fileHref}, filename)
685 ]),
686 h('td', action)
687 ])
688 })),
689 pull(
690 pull.values(changedFiles),
691 paramap(function (item, cb) {
692 var extension = u.getExtension(item.filename)
693 if (extension in u.imgMimes) {
694 var filename = u.escape(item.filename)
695 return cb(null,
696 '<pre><table class="code">' +
697 '<tr><th id="' + u.escape(item.filename) + '">' +
698 filename + '</th></tr>' +
699 '<tr><td><img src="' + u.encodeLink(item.rawPath) + '"' +
700 ' alt="' + filename + '"/></td></tr>' +
701 '</table></pre>')
702 }
703 var done = multicb({ pluck: 1, spread: true })
704 var mode0 = item.mode && item.mode[0]
705 var modeI = item.mode && item.mode[lastI]
706 var isSubmodule = (modeI == 0160000)
707 getRepoObjectString(repos[0], item.id[0], mode0, done())
708 getRepoObjectString(repos[1], item.id[lastI], modeI, done())
709 done(function (err, strOld, strNew) {
710 if (err) return cb(err)
711 cb(null, htmlLineDiff(req, item.filename, item.filename,
712 strOld, strNew,
713 u.encodeLink(item.blobPath), !isSubmodule))
714 })
715 }, 4)
716 )
717 ])
718}
719
720function htmlLineDiff(req, filename, anchor, oldStr, newStr, blobHref,
721 showViewLink) {
722 return '<pre><table class="code">' +
723 '<tr><th colspan=3 id="' + u.escape(anchor) + '">' + filename +
724 (showViewLink === false ? '' :
725 '<span class="right-bar">' +
726 '<a href="' + blobHref + '">' + req._t('View') + '</a> ' +
727 '</span>') +
728 '</th></tr>' +
729 (oldStr.length + newStr.length > 200000
730 ? '<tr><td class="diff-info">' + req._t('diff.TooLarge') + '<br>' +
731 req._t('diff.OldFileSize', {bytes: oldStr.length}) + '<br>' +
732 req._t('diff.NewFileSize', {bytes: newStr.length}) + '</td></tr>'
733 : tableDiff(oldStr, newStr, filename)) +
734 '</table></pre>'
735}
736
737function tableDiff(oldStr, newStr, filename) {
738 var diff = JsDiff.structuredPatch('', '', oldStr, newStr)
739 var groups = diff.hunks.map(function (hunk) {
740 var oldLine = hunk.oldStart
741 var newLine = hunk.newStart
742 var header = '<tr class="diff-hunk-header"><td colspan=2></td><td>' +
743 '@@ -' + oldLine + ',' + hunk.oldLines + ' ' +
744 '+' + newLine + ',' + hunk.newLines + ' @@' +
745 '</td></tr>'
746 return [header].concat(hunk.lines.map(function (line) {
747 var s = line[0]
748 if (s == '\\') return
749 var html = u.highlight(line, u.getExtension(filename))
750 var trClass = s == '+' ? 'diff-new' : s == '-' ? 'diff-old' : ''
751 var lineNums = [s == '+' ? '' : oldLine++, s == '-' ? '' : newLine++]
752 var id = [filename].concat(lineNums).join('-')
753 return '<tr id="' + u.escape(id) + '" class="' + trClass + '">' +
754 lineNums.map(function (num) {
755 return '<td class="code-linenum">' +
756 (num ? '<a href="#' + encodeURIComponent(id) + '">' +
757 num + '</a>' : '') + '</td>'
758 }).join('') +
759 '<td class="code-text">' + html + '</td></tr>'
760 }))
761 })
762 return [].concat.apply([], groups).join('')
763}
764
765/* An unknown message linking to a repo */
766
767R.serveRepoSomething = function (req, repo, id, msg, path) {
768 return this.renderRepoPage(req, repo, null, null, null,
769 pull.once('<section><h3>' + u.link([id]) + '</h3>' +
770 u.json(msg) + '</section>'))
771}
772
773/* Repo update */
774
775function objsArr(objs) {
776 return Array.isArray(objs) ? objs :
777 Object.keys(objs).map(function (sha1) {
778 var obj = Object.create(objs[sha1])
779 obj.sha1 = sha1
780 return obj
781 })
782}
783
784R.serveRepoUpdate = function (req, repo, id, msg, path) {
785 var self = this
786 var raw = req._u.query.raw != null
787 var title = req._t('Update') + ' · %{author}/%{repo}'
788
789 if (raw)
790 return self.renderRepoPage(req, repo, 'activity', null, title, pull.once(
791 '<a href="?" class="raw-link header-align">' +
792 req._t('Info') + '</a>' +
793 '<h3>' + req._t('Update') + '</h3>' +
794 '<section class="collapse">' +
795 u.json({key: id, value: msg}) + '</section>'))
796
797 // convert packs to old single-object style
798 if (msg.content.indexes) {
799 for (var i = 0; i < msg.content.indexes.length; i++) {
800 msg.content.packs[i] = {
801 pack: {link: msg.content.packs[i].link},
802 idx: msg.content.indexes[i]
803 }
804 }
805 }
806
807 var commits = cat([
808 msg.content.objects && pull(
809 pull.values(msg.content.objects),
810 pull.filter(function (obj) { return obj.type == 'commit' }),
811 paramap(function (obj, cb) {
812 self.web.getBlob(req, obj.link || obj.key, function (err, readObject) {
813 if (err) return cb(err)
814 GitRepo.getCommitParsed({read: readObject}, cb)
815 })
816 }, 8)
817 ),
818 msg.content.packs && pull(
819 pull.values(msg.content.packs),
820 paramap(function (pack, cb) {
821 var done = multicb({ pluck: 1, spread: true })
822 self.web.getBlob(req, pack.pack.link, done())
823 self.web.getBlob(req, pack.idx.link, done())
824 done(function (err, readPack, readIdx) {
825 if (err) return cb(self.web.renderError(err))
826 cb(null, gitPack.decodeWithIndex(repo, readPack, readIdx))
827 })
828 }, 4),
829 pull.flatten(),
830 pull.asyncMap(function (obj, cb) {
831 if (obj.type == 'commit')
832 GitRepo.getCommitParsed(obj, cb)
833 else
834 pull(obj.read, pull.drain(null, cb))
835 }),
836 pull.filter()
837 )
838 ])
839
840 return self.renderRepoPage(req, repo, 'activity', null, title, cat([
841 pull.once('<a href="?raw" class="raw-link header-align">' +
842 req._t('Data') + '</a>' +
843 '<h3>' + req._t('Update') + '</h3>'),
844 pull(
845 pull.once({key: id, value: msg}),
846 pull.asyncMap(renderRepoUpdate.bind(self, req, repo, true))
847 ),
848 (msg.content.objects || msg.content.packs) &&
849 pull.once('<h3>' + req._t('Commits') + '</h3>'),
850 pull(commits, pull.map(function (commit) {
851 return renderCommit(req, repo, commit)
852 }))
853 ]))
854}
855
856/* Blob */
857
858R.serveRepoBlob = function (req, repo, rev, path) {
859 var self = this
860 return u.readNext(function (cb) {
861 repo.getFile(rev, path, function (err, object) {
862 if (err) return cb(null, self.web.serveBlobNotFound(req, repo.id, err))
863 var type = repo.isCommitHash(rev) ? 'Tree' : 'Branch'
864 var pathLinks = path.length === 0 ? '' :
865 ': ' + linkPath([repo.id, 'tree'], [rev].concat(path))
866 var rawFilePath = [repo.id, 'raw', rev].concat(path)
867 var dirPath = path.slice(0, path.length-1)
868 var filename = path[path.length-1]
869 var extension = u.getExtension(filename)
870 var title = (path.length ? path.join('/') + ' · ' : '') +
871 '%{author}/%{repo}' +
872 (repo.head == 'refs/heads/' + rev ? '' : '@' + rev)
873 cb(null, self.renderRepoPage(req, repo, 'code', rev, title, cat([
874 pull.once('<section><form action="" method="get">' +
875 '<h3>' + req._t(type) + ': ' + rev + ' '),
876 self.revMenu(req, repo, rev),
877 pull.once('</h3></form>'),
878 type == 'Branch' && renderRepoLatest(req, repo, rev),
879 pull.once('</section><section class="collapse">' +
880 '<h3>' + req._t('Files') + pathLinks + '</h3>' +
881 '<div>' + object.length + ' bytes' +
882 '<span class="raw-link">' +
883 u.link(rawFilePath, req._t('Raw')) + '</span>' +
884 '</div></section>' +
885 '<section>'),
886 extension in u.imgMimes
887 ? pull.once('<img src="' + u.encodeLink(rawFilePath) +
888 '" alt="' + u.escape(filename) + '" />')
889 : self.web.renderObjectData(object, filename, repo, rev, dirPath),
890 pull.once('</section>')
891 ])))
892 })
893 })
894}
895
896/* Raw blob */
897
898R.serveRepoRaw = function (req, repo, branch, path) {
899 var self = this
900 return u.readNext(function (cb) {
901 repo.getFile(branch, path, function (err, object) {
902 if (err) return cb(null,
903 self.web.serveBuffer(404, req._t('error.BlobNotFound')))
904 var extension = u.getExtension(path[path.length-1])
905 var contentType = u.imgMimes[extension]
906 cb(null, pull(object.read, self.web.serveRaw(object.length, contentType)))
907 })
908 })
909}
910
911/* Digs */
912
913R.serveRepoDigs = function serveRepoDigs (req, repo) {
914 var self = this
915 return u.readNext(cb => {
916 var title = req._t('Digs') + ' · %{author}/%{repo}'
917 self.web.getVotes(repo.id, (err, votes) => {
918 cb(null, self.renderRepoPage(req, repo, null, null, title,
919 h('section', [
920 h('h3', req._t('Digs')),
921 h('div', `${req._t('Total')}: ${votes.upvotes}`),
922 h('ul', u.paraSourceMap(Object.keys(votes.upvoters), (feedId, cb) => {
923 self.web.about.getName(feedId, (err, name) => {
924 cb(null, h('li', u.link([feedId], name)))
925 })
926 }))
927 ])
928 ))
929 })
930 })
931}
932
933/* Forks */
934
935R.getForks = function (repo, includeSelf) {
936 var self = this
937 return pull(
938 cat([
939 includeSelf && pull.once(repo.id),
940 // get downstream repos
941 pull(
942 self.web.ssb.links({
943 dest: repo.id,
944 rel: 'upstream'
945 }),
946 pull.map('key')
947 ),
948 // look for other repos that previously had pull requests to this one
949 pull(
950 self.web.ssb.links({
951 dest: repo.id,
952 values: true,
953 rel: 'project'
954 }),
955 pull.filter(function (msg) {
956 var c = msg && msg.value && msg.value.content
957 return c && c.type == 'pull-request'
958 }),
959 pull.map(function (msg) { return msg.value.content.head_repo })
960 )
961 ]),
962 pull.unique(),
963 paramap(function (key, cb) {
964 self.web.ssb.get(key, function (err, value) {
965 if (err) cb(err)
966 else cb(null, {key: key, value: value})
967 })
968 }, 4),
969 pull.filter(function (msg) {
970 var c = msg && msg.value && msg.value.content
971 return c && c.type == 'git-repo'
972 }),
973 paramap(function (msg, cb) {
974 self.web.getRepoFullName(msg.value.author, msg.key,
975 function (err, repoName, authorName) {
976 if (err) return cb(err)
977 cb(null, {
978 key: msg.key,
979 value: msg.value,
980 repoName: repoName,
981 authorName: authorName
982 })
983 })
984 }, 8)
985 )
986}
987
988R.serveRepoForks = function (req, repo) {
989 var hasForks
990 var title = req._t('Forks') + ' · %{author}/%{repo}'
991 return this.renderRepoPage(req, repo, null, null, title, cat([
992 pull.once('<h3>' + req._t('Forks') + '</h3>'),
993 pull(
994 this.getForks(repo),
995 pull.map(function (msg) {
996 hasForks = true
997 return '<section class="collapse">' +
998 u.link([msg.value.author], msg.authorName) + ' / ' +
999 u.link([msg.key], msg.repoName) +
1000 '<span class="right-bar">' +
1001 u.timestamp(msg.value.timestamp, req) +
1002 '</span></section>'
1003 })
1004 ),
1005 u.readOnce(function (cb) {
1006 cb(null, hasForks ? '' : req._t('NoForks'))
1007 })
1008 ]))
1009}
1010
1011R.serveRepoForkPrompt = function (req, repo) {
1012 var title = req._t('Fork') + ' · %{author}/%{repo}'
1013 return this.renderRepoPage(req, repo, null, null, title, pull.once(
1014 '<form action="" method="post" onreset="history.back()">' +
1015 '<h3>' + req._t('ForkRepoPrompt') + '</h3>' +
1016 '<p>' + u.hiddenInputs({ id: repo.id }) +
1017 '<button class="btn open" type="submit" name="action" value="fork">' +
1018 req._t('Fork') +
1019 '</button>' +
1020 ' <button class="btn" type="reset">' +
1021 req._t('Cancel') + '</button>' +
1022 '</p></form>'
1023 ))
1024}
1025
1026R.serveIssueOrPullRequest = function (req, repo, issue, path, id) {
1027 return issue.msg.value.content.type == 'pull-request'
1028 ? this.pulls.serveRepoPullReq(req, repo, issue, path, id)
1029 : this.issues.serveRepoIssue(req, repo, issue, path, id)
1030}
1031
1032function getRepoLastMod(repo, cb) {
1033 repo.getState(function (err, state) {
1034 if (err) return cb(err)
1035 var lastMod = new Date(Math.max.apply(Math, state.refs.map(function (ref) {
1036 return ref.link.value.timestamp
1037 }))) || new Date()
1038 cb(null, lastMod)
1039 })
1040}
1041
1042R.serveRepoRefs = function (req, repo) {
1043 var self = this
1044 return u.readNext(function (cb) {
1045 getRepoLastMod(repo, function (err, lastMod) {
1046 if (err) return cb(null, self.web.serveError(req, err, 500))
1047 if (u.ifModifiedSince(req, lastMod)) {
1048 return cb(null, pull.once([304]))
1049 }
1050 repo.getState(function (err, state) {
1051 if (err) return cb(null, self.web.serveError(req, err, 500))
1052 var buf = state.refs.sort(function (a, b) {
1053 return a.name > b.name ? 1 : a.name < b.name ? -1 : 0
1054 }).map(function (ref) {
1055 return ref.hash + '\t' + ref.name + '\n'
1056 }).join('')
1057 cb(null, pull.values([[200, {
1058 'Content-Type': 'text/plain; charset=utf-8',
1059 'Content-Length': Buffer.byteLength(buf),
1060 'Last-Modified': lastMod.toGMTString()
1061 }], buf]))
1062 })
1063 })
1064 })
1065}
1066
1067R.serveRepoObject = function (req, repo, sha1) {
1068 var self = this
1069 if (!/[0-9a-f]{20}/.test(sha1)) return pull.once([401])
1070 return u.readNext(function (cb) {
1071 repo.getObjectFromAny(sha1, function (err, obj) {
1072 if (err) return cb(null, pull.once([404]))
1073 cb(null, cat([
1074 pull.once([200, {
1075 'Content-Type': 'application/x-git-loose-object',
1076 'Cache-Control': 'max-age=31536000'
1077 }]),
1078 pull(
1079 cat([
1080 pull.values([obj.type, ' ', obj.length.toString(10), '\0']),
1081 obj.read
1082 ]),
1083 toPull(zlib.createDeflate())
1084 )
1085 ]))
1086 })
1087 })
1088}
1089
1090R.serveRepoHead = function (req, repo) {
1091 var self = this
1092 return u.readNext(function (cb) {
1093 repo.getHead(function (err, name) {
1094 if (err) return cb(null, pull.once([500]))
1095 return cb(null, self.web.serveBuffer(200, 'ref: ' + name))
1096 })
1097 })
1098}
1099
1100R.serveRepoPacksInfo = function (req, repo) {
1101 var self = this
1102 return u.readNext(function (cb) {
1103 getRepoLastMod(repo, function (err, lastMod) {
1104 if (err) return cb(null, self.web.serveError(req, err, 500))
1105 if (u.ifModifiedSince(req, lastMod)) {
1106 return cb(null, pull.once([304]))
1107 }
1108 cb(null, cat([
1109 pull.once([200, {
1110 'Content-Type': 'text/plain; charset=utf-8',
1111 'Last-Modified': lastMod.toGMTString()
1112 }]),
1113 pull(
1114 repo.packs(),
1115 pull.map(function (pack) {
1116 var sha1 = pack.sha1
1117 if (!sha1) {
1118 // make up a sha1 and hope git doesn't notice
1119 var packId = new Buffer(pack.packId.substr(1, 44), 'base64')
1120 sha1 = packId.slice(0, 20).toString('hex')
1121 }
1122 return 'P pack-' + sha1 + '.pack\n'
1123 })
1124 )
1125 ]))
1126 })
1127 })
1128}
1129
1130R.serveRepoPack = function (req, repo, name) {
1131 var m = name.match(/^pack-(.*)\.(pack|idx)$/)
1132 if (!m) return pull.once([400])
1133 var hex;
1134 try {
1135 hex = new Buffer(m[1], 'hex')
1136 } catch(e) {
1137 return pull.once([400])
1138 }
1139
1140 var self = this
1141 return u.readNext(function (cb) {
1142 pull(
1143 repo.packs(),
1144 pull.filter(function (pack) {
1145 var sha1 = pack.sha1
1146 ? new Buffer(pack.sha1, 'hex')
1147 : new Buffer(pack.packId.substr(1, 44), 'base64').slice(0, 20)
1148 return sha1.equals(hex)
1149 }),
1150 pull.take(1),
1151 pull.collect(function (err, packs) {
1152 if (err) return console.error(err), cb(null, pull.once([500]))
1153 if (packs.length < 1) return cb(null, pull.once([404]))
1154 var pack = packs[0]
1155
1156 if (m[2] === 'pack') {
1157 repo.getPackfile(pack.packId, function (err, read) {
1158 if (err) return cb(err)
1159 cb(null, pull(read,
1160 self.web.serveRaw(null, 'application/x-git-packed-objects')
1161 ))
1162 })
1163 }
1164
1165 if (m[2] === 'idx') {
1166 repo.getPackIndex(pack.idxId, function (err, read) {
1167 if (err) return cb(err)
1168 cb(null, pull(read,
1169 self.web.serveRaw(null, 'application/x-git-packed-objects-toc')
1170 ))
1171 })
1172 }
1173 })
1174 )
1175 })
1176}
1177

Built with git-ssb-web