git ssb

30+

cel / git-ssb-web



Tree: cf2e841e49a18c0ef5554cdfafffe5c63efe1959

Files: cf2e841e49a18c0ef5554cdfafffe5c63efe1959 / lib / repos / index.js

38640 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.renderEmptyRepo = function (req, repo) {
259 if (repo.feed != this.web.myId)
260 return pull.once(
261 '<section>' +
262 '<h3>' + req._t('EmptyRepo') + '</h3>' +
263 '</section>')
264
265 var gitUrl = 'ssb://' + repo.id
266 return pull.once(`
267 <section>
268 <h3>${req._t('initRepo.GettingStarted')}</h3>
269 <h4>${req._t('initRepo.CreateNew')}</h4><pre>
270touch ${req._t('initRepo.README')}.md
271git init
272git add ${req._t('initRepo.README')}.md
273git commit -m "${req._t('initRepo.InitialCommit')}"
274git remote add origin ${gitUrl}
275git push -u origin master</pre>
276 <h4>${req._t('initRepo.PushExisting')}</h4>
277 <pre>
278git remote add origin ${gitUrl}
279git push -u origin master</pre>
280 </section>`)
281}
282
283R.serveRepoTree = function (req, repo, rev, path) {
284 var type = repo.isCommitHash(rev) ? 'Tree' : 'Branch'
285 var title = (path.length ? path.join('/') + ' · ' : '') +
286 '%{author}/%{repo}' +
287 (repo.head == 'refs/heads/' + rev ? '' : '@' + rev)
288 return this.renderRepoPage(req, repo, 'code', rev, title, cat([
289 pull.once('<section class="branch-info light-grey"><form action="" method="get">' +
290 '<h3>' + req._t(type) + ': '),
291 this.revMenu(req, repo, rev),
292 pull.once('</h3></form>'),
293 type == 'Branch' && renderRepoLatest(req, repo, rev),
294 pull.once('</section>'),
295 rev ? cat([
296 pull.once('<section class="files">'),
297 renderRepoTree(req, repo, rev, path),
298 pull.once('</section>'),
299 this.renderRepoReadme(req, repo, rev, path)
300 ]) : this.renderEmptyRepo(req, repo)
301 ]))
302}
303
304/* Repo activity */
305
306R.serveRepoActivity = function (req, repo, branch) {
307 var self = this
308 var title = req._t('Activity') + ' · %{author}/%{repo}'
309 return self.renderRepoPage(req, repo, 'activity', branch, title, cat([
310 pull.once('<h3>' + req._t('Activity') + '</h3>'),
311 pull(
312 self.web.ssb.links({
313 dest: repo.id,
314 rel: 'repo',
315 values: true,
316 reverse: true
317 }),
318 pull.asyncMap(renderRepoUpdate.bind(self, req, repo, false))
319 ),
320 u.readOnce(function (cb) {
321 var done = multicb({ pluck: 1, spread: true })
322 self.web.about.getName(repo.feed, done())
323 self.web.getMsg(repo.id, done())
324 done(function (err, authorName, msg) {
325 if (err) return cb(err)
326 self.web.renderFeedItem(req, {
327 key: repo.id,
328 value: msg,
329 authorName: authorName
330 }, cb)
331 })
332 })
333 ]))
334}
335
336function renderRepoUpdate(req, repo, full, msg, cb) {
337 var c = msg.value.content
338
339 if (c.type != 'git-update') {
340 return ''
341 // return renderFeedItem(msg, cb)
342 // TODO: render post, issue, pull-request
343 }
344
345 var branches = []
346 var tags = []
347 if (c.refs) for (var name in c.refs) {
348 var m = name.match(/^refs\/(heads|tags)\/(.*)$/) || [,, name]
349 ;(m[1] == 'tags' ? tags : branches)
350 .push({name: m[2], value: c.refs[name]})
351 }
352 var numObjects = c.objects ? Object.keys(c.objects).length : 0
353
354 var dateStr = new Date(msg.value.timestamp).toLocaleString(req._locale)
355
356 this.web.about.getName(msg.value.author, function (err, name) {
357 if (err) return cb(err)
358 cb(null, '<section class="collapse">' +
359 u.link([msg.key], dateStr) + '<br>' +
360 u.link([msg.value.author], name) + '<br>' +
361
362 branches.map(function (update) {
363 if (!update.value) {
364 return '<s>' + u.escape(update.name) + '</s><br/>'
365 } else {
366 var commitLink = u.link([repo.id, 'commit', update.value])
367 var branchLink = u.link([repo.id, 'tree', update.name])
368 return branchLink + ' &rarr; <tt>' + commitLink + '</tt><br/>'
369 }
370 }).join('') +
371 tags.map(function (update) {
372 return update.value
373 ? u.link([repo.id, 'tag', update.value], update.name)
374 : '<s>' + u.escape(update.name) + '</s>'
375 }).join(', ') +
376 '</section>')
377 })
378}
379
380/* Repo commits */
381
382R.serveRepoCommits = function (req, repo, branch) {
383 var query = req._u.query
384 var title = req._t('Commits') + ' · %{author}/%{repo}'
385 return this.renderRepoPage(req, repo, 'commits', branch, title, cat([
386 pull.once('<h3>' + req._t('Commits') + '</h3>'),
387 pull(
388 repo.readLog(query.start || branch),
389 pull.take(20),
390 paramap(repo.getCommitParsed.bind(repo), 8),
391 paginate(
392 !query.start ? '' : function (first, cb) {
393 cb(null, '&hellip;')
394 },
395 pull.map(renderCommit.bind(this, req, repo)),
396 function (commit, cb) {
397 cb(null, commit.parents && commit.parents[0] ?
398 '<a href="?start=' + commit.id + '">' +
399 req._t('Older') + '</a>' : '')
400 }
401 )
402 )
403 ]))
404}
405
406function renderCommit(req, repo, commit) {
407 var commitPath = [repo.id, 'commit', commit.id]
408 var treePath = [repo.id, 'tree', commit.id]
409 return '<section class="collapse">' +
410 '<strong>' + u.link(commitPath, commit.title) + '</strong><br>' +
411 '<tt>' + commit.id + '</tt> ' +
412 u.link(treePath, req._t('Tree')) + '<br>' +
413 u.escape(commit.author.name) + ' &middot; ' +
414 commit.author.date.toLocaleString(req._locale) +
415 (commit.separateAuthor ? '<br>' + req._t('CommittedOn', {
416 name: u.escape(commit.committer.name),
417 date: commit.committer.date.toLocaleString(req._locale)
418 }) : '') +
419 '</section>'
420}
421
422/* Branch menu */
423
424R.formatRevOptions = function (currentName) {
425 return function (name) {
426 var htmlName = u.escape(name)
427 return '<option value="' + htmlName + '"' +
428 (name == currentName ? ' selected="selected"' : '') +
429 '>' + htmlName + '</option>'
430 }
431}
432
433R.formatRevType = function(req, type) {
434 return (
435 type == 'heads' ? req._t('Branches') :
436 type == 'tags' ? req._t('Tags') :
437 type)
438}
439
440R.revMenu = function (req, repo, currentName) {
441 var self = this
442 return u.readOnce(function (cb) {
443 repo.getRefNames(function (err, refs) {
444 if (err) return cb(err)
445 cb(null, '<select class="custom-dropdown" name="rev" onchange="this.form.submit()">' +
446 Object.keys(refs).map(function (group) {
447 return '<optgroup ' +
448 'label="' + self.formatRevType(req, group) + '">' +
449 refs[group].map(self.formatRevOptions(currentName)).join('') +
450 '</optgroup>'
451 }).join('') +
452 '</select><noscript> ' +
453 '<input type="submit" value="' + req._t('Go') + '"/></noscript>')
454 })
455 })
456}
457
458/* Repo tree */
459
460function renderRepoLatest(req, repo, rev) {
461 if (!rev) return pull.empty()
462 return u.readOnce(function (cb) {
463 repo.getCommitParsed(rev, function (err, commit) {
464 if (err) return cb(err)
465 var commitPath = [repo.id, 'commit', commit.id]
466 var actor = commit.separateAuthor ? 'author' : 'committer'
467 var actionKey = actor.slice(0,1).toUpperCase() + actor.slice(1) + 'ReleasedCommit'
468 cb(null,
469 '<div class="mt2">' +
470 '<span>' +
471 req._t(actionKey, {
472 name: u.escape(commit[actor].name),
473 commitName: u.link(commitPath, commit.title)
474 }) +
475 '</span>' +
476 '<tt class="float-right">' +
477 req._t('LatestOn', {
478 commitId: commit.id.slice(0, 7),
479 date: commit[actor].date.toLocaleString(req._locale)
480 }) +
481 '</tt>' +
482 '</div>'
483 )
484 })
485 })
486}
487
488// breadcrumbs
489function linkPath(basePath, path) {
490 path = path.slice()
491 var last = path.pop()
492 return path.map(function (dir, i) {
493 return u.link(basePath.concat(path.slice(0, i+1)), dir)
494 }).concat(last).join(' / ')
495}
496
497function renderRepoTree(req, repo, rev, path) {
498 var source = repo.readDir(rev,path)
499 var pathLinks = path.length === 0 ? '' :
500 ': ' + linkPath([repo.id, 'tree'], [rev].concat(path))
501
502 var location = once('')
503 if (path.length !== 0) {
504 var link = linkPath([repo.id, 'tree'], [rev].concat(path))
505 location = h('div', {class: 'fileLocation'}, `${req._t('Files')}: ${link}`)
506 }
507
508 return cat([
509 location,
510 h('table', {class: "files w-100"}, u.sourceMap(source, file =>
511 h('tr', [
512 h('td', [
513 h('i', fileIcon(file))
514 ]),
515 h('td', u.link(filePath(file), file.name))
516 ])
517 ))
518 ])
519
520 function fileIcon(file) {
521 return fileType(file) === 'tree' ? '📁' : '📄'
522 }
523
524 function filePath(file) {
525 var type = fileType(file)
526 return [repo.id, type, rev].concat(path, file.name)
527 }
528
529 function fileType(file) {
530 if (file.mode === 040000) return 'tree'
531 else if (file.mode === 0160000) return 'commit'
532 else return 'blob'
533 }
534}
535
536/* Repo readme */
537
538R.renderRepoReadme = function (req, repo, branch, path) {
539 var self = this
540 return u.readNext(function (cb) {
541 pull(
542 repo.readDir(branch, path),
543 pull.filter(function (file) {
544 return /readme(\.|$)/i.test(file.name)
545 }),
546 pull.take(1),
547 pull.collect(function (err, files) {
548 if (err) return cb(null, pull.empty())
549 var file = files[0]
550 if (!file)
551 return cb(null, pull.once(path.length ? '' :
552 '<p>' + req._t('NoReadme') + '</p>'))
553 repo.getObjectFromAny(file.id, function (err, obj) {
554 if (err) return cb(err)
555 cb(null, cat([
556 pull.once('<section class="readme">'),
557 self.web.renderObjectData(obj, file.name, repo, branch, path),
558 pull.once('</section>')
559 ]))
560 })
561 })
562 )
563 })
564}
565
566/* Repo commit */
567
568R.serveRepoCommit = function (req, repo, rev) {
569 var self = this
570 return u.readNext(function (cb) {
571 repo.getCommitParsed(rev, function (err, commit) {
572 if (err) return cb(err)
573 var commitPath = [repo.id, 'commit', commit.id]
574 var treePath = [repo.id, 'tree', commit.id]
575 var title = u.escape(commit.title) + ' · ' +
576 '%{author}/%{repo}@' + commit.id.substr(0, 8)
577 cb(null, self.renderRepoPage(req, repo, null, rev, title, cat([
578 pull.once(
579 '<h3>' + u.link(commitPath,
580 req._t('CommitRev', {rev: rev})) + '</h3>' +
581 '<section class="collapse">' +
582 '<div class="right-bar">' +
583 u.link(treePath, req._t('BrowseFiles')) +
584 '</div>' +
585 '<h4>' + u.linkify(u.escape(commit.title)) + '</h4>' +
586 (commit.body ? u.linkify(u.pre(commit.body)) : '') +
587 (commit.separateAuthor ? req._t('AuthoredOn', {
588 name: u.escape(commit.author.name),
589 date: commit.author.date.toLocaleString(req._locale)
590 }) + '<br/>' : '') +
591 req._t('CommittedOn', {
592 name: u.escape(commit.committer.name),
593 date: commit.committer.date.toLocaleString(req._locale)
594 }) + '<br/>' +
595 commit.parents.map(function (id) {
596 return req._t('Parent') + ': ' +
597 u.link([repo.id, 'commit', id], id)
598 }).join('<br>') +
599 '</section>' +
600 '<section><h3>' + req._t('FilesChanged') + '</h3>'),
601 // TODO: show diff from all parents (merge commits)
602 self.renderDiffStat(req, [repo, repo], [commit.parents[0], commit.id]),
603 pull.once('</section>')
604 ])))
605 })
606 })
607}
608
609/* Repo tag */
610
611R.serveRepoTag = function (req, repo, rev, path) {
612 var self = this
613 return u.readNext(function (cb) {
614 repo.getTagParsed(rev, function (err, tag) {
615 if (err) {
616 if (/Expected tag, got commit/.test(err.message)) {
617 req._u.pathname = u.encodeLink([repo.id, 'commit', rev].concat(path))
618 return cb(null, self.web.serveRedirect(req, url.format(req._u)))
619 }
620 return cb(null, self.web.serveError(req, err))
621 }
622
623 var title = req._t('TagName', {
624 tag: u.escape(tag.tag)
625 }) + ' · %{author}/%{repo}'
626 var body = (tag.title + '\n\n' +
627 tag.body.replace(/-----BEGIN PGP SIGNATURE-----\n[^.]*?\n-----END PGP SIGNATURE-----\s*$/, '')).trim()
628 var date = tag.tagger.date
629 cb(null, self.renderRepoPage(req, repo, 'tags', tag.object, title,
630 pull.once(
631 '<section class="collapse">' +
632 '<h3>' + u.link([repo.id, 'tag', rev], tag.tag) + '</h3>' +
633 req._t('TaggedOn', {
634 name: u.escape(tag.tagger.name),
635 date: date && date.toLocaleString(req._locale)
636 }) + '<br/>' +
637 u.link([repo.id, tag.type, tag.object]) +
638 u.linkify(u.pre(body)) +
639 '</section>')))
640 })
641 })
642}
643
644
645/* Diff stat */
646
647R.renderDiffStat = function (req, repos, treeIds) {
648 if (treeIds.length == 0) treeIds = [null]
649 var id = treeIds[0]
650 var lastI = treeIds.length - 1
651 var oldTree = treeIds[0]
652 var changedFiles = []
653 var source = GitRepo.diffTrees(repos, treeIds, true)
654
655 return cat([
656 h('table', u.sourceMap(source, item => {
657 var filename = u.escape(item.filename = item.path.join('/'))
658 var oldId = item.id && item.id[0]
659 var newId = item.id && item.id[lastI]
660 var oldMode = item.mode && item.mode[0]
661 var newMode = item.mode && item.mode[lastI]
662 var action =
663 !oldId && newId ? req._t('action.added') :
664 oldId && !newId ? req._t('action.deleted') :
665 oldMode != newMode ? req._t('action.changedMode', {
666 old: oldMode.toString(8),
667 new: newMode.toString(8)
668 }) : req._t('changed')
669 if (item.id)
670 changedFiles.push(item)
671 var blobsPath = item.id[1]
672 ? [repos[1].id, 'blob', treeIds[1]]
673 : [repos[0].id, 'blob', treeIds[0]]
674 var rawsPath = item.id[1]
675 ? [repos[1].id, 'raw', treeIds[1]]
676 : [repos[0].id, 'raw', treeIds[0]]
677 item.blobPath = blobsPath.concat(item.path)
678 item.rawPath = rawsPath.concat(item.path)
679 var fileHref = item.id ?
680 '#' + encodeURIComponent(item.path.join('/')) :
681 u.encodeLink(item.blobPath)
682
683 return h('tr', [
684 h('td', [
685 h('a', {href: fileHref}, filename)
686 ]),
687 h('td', action)
688 ])
689 })),
690 pull(
691 pull.values(changedFiles),
692 paramap(function (item, cb) {
693 var extension = u.getExtension(item.filename)
694 if (extension in u.imgMimes) {
695 var filename = u.escape(item.filename)
696 return cb(null,
697 '<pre><table class="code">' +
698 '<tr><th id="' + u.escape(item.filename) + '">' +
699 filename + '</th></tr>' +
700 '<tr><td><img src="' + u.encodeLink(item.rawPath) + '"' +
701 ' alt="' + filename + '"/></td></tr>' +
702 '</table></pre>')
703 }
704 var done = multicb({ pluck: 1, spread: true })
705 var mode0 = item.mode && item.mode[0]
706 var modeI = item.mode && item.mode[lastI]
707 var isSubmodule = (modeI == 0160000)
708 getRepoObjectString(repos[0], item.id[0], mode0, done())
709 getRepoObjectString(repos[1], item.id[lastI], modeI, done())
710 done(function (err, strOld, strNew) {
711 if (err) return cb(err)
712 cb(null, htmlLineDiff(req, item.filename, item.filename,
713 strOld, strNew,
714 u.encodeLink(item.blobPath), !isSubmodule))
715 })
716 }, 4)
717 )
718 ])
719}
720
721function htmlLineDiff(req, filename, anchor, oldStr, newStr, blobHref,
722 showViewLink) {
723 return '<pre><table class="code">' +
724 '<tr><th colspan=3 id="' + u.escape(anchor) + '">' + filename +
725 (showViewLink === false ? '' :
726 '<span class="right-bar">' +
727 '<a href="' + blobHref + '">' + req._t('View') + '</a> ' +
728 '</span>') +
729 '</th></tr>' +
730 (oldStr.length + newStr.length > 200000
731 ? '<tr><td class="diff-info">' + req._t('diff.TooLarge') + '<br>' +
732 req._t('diff.OldFileSize', {bytes: oldStr.length}) + '<br>' +
733 req._t('diff.NewFileSize', {bytes: newStr.length}) + '</td></tr>'
734 : tableDiff(oldStr, newStr, filename)) +
735 '</table></pre>'
736}
737
738function tableDiff(oldStr, newStr, filename) {
739 var diff = JsDiff.structuredPatch('', '', oldStr, newStr)
740 var groups = diff.hunks.map(function (hunk) {
741 var oldLine = hunk.oldStart
742 var newLine = hunk.newStart
743 var header = '<tr class="diff-hunk-header"><td colspan=2></td><td>' +
744 '@@ -' + oldLine + ',' + hunk.oldLines + ' ' +
745 '+' + newLine + ',' + hunk.newLines + ' @@' +
746 '</td></tr>'
747 return [header].concat(hunk.lines.map(function (line) {
748 var s = line[0]
749 if (s == '\\') return
750 var html = u.highlight(line, u.getExtension(filename))
751 var trClass = s == '+' ? 'diff-new' : s == '-' ? 'diff-old' : ''
752 var lineNums = [s == '+' ? '' : oldLine++, s == '-' ? '' : newLine++]
753 var id = [filename].concat(lineNums).join('-')
754 return '<tr id="' + u.escape(id) + '" class="' + trClass + '">' +
755 lineNums.map(function (num) {
756 return '<td class="code-linenum">' +
757 (num ? '<a href="#' + encodeURIComponent(id) + '">' +
758 num + '</a>' : '') + '</td>'
759 }).join('') +
760 '<td class="code-text">' + html + '</td></tr>'
761 }))
762 })
763 return [].concat.apply([], groups).join('')
764}
765
766/* An unknown message linking to a repo */
767
768R.serveRepoSomething = function (req, repo, id, msg, path) {
769 return this.renderRepoPage(req, repo, null, null, null,
770 pull.once('<section><h3>' + u.link([id]) + '</h3>' +
771 u.json(msg) + '</section>'))
772}
773
774/* Repo update */
775
776function objsArr(objs) {
777 return Array.isArray(objs) ? objs :
778 Object.keys(objs).map(function (sha1) {
779 var obj = Object.create(objs[sha1])
780 obj.sha1 = sha1
781 return obj
782 })
783}
784
785R.serveRepoUpdate = function (req, repo, id, msg, path) {
786 var self = this
787 var raw = req._u.query.raw != null
788 var title = req._t('Update') + ' · %{author}/%{repo}'
789
790 if (raw)
791 return self.renderRepoPage(req, repo, 'activity', null, title, pull.once(
792 '<a href="?" class="raw-link header-align">' +
793 req._t('Info') + '</a>' +
794 '<h3>' + req._t('Update') + '</h3>' +
795 '<section class="collapse">' +
796 u.json({key: id, value: msg}) + '</section>'))
797
798 // convert packs to old single-object style
799 if (msg.content.indexes) {
800 for (var i = 0; i < msg.content.indexes.length; i++) {
801 msg.content.packs[i] = {
802 pack: {link: msg.content.packs[i].link},
803 idx: msg.content.indexes[i]
804 }
805 }
806 }
807
808 var commits = cat([
809 msg.content.objects && pull(
810 pull.values(msg.content.objects),
811 pull.filter(function (obj) { return obj.type == 'commit' }),
812 paramap(function (obj, cb) {
813 self.web.getBlob(req, obj.link || obj.key, function (err, readObject) {
814 if (err) return cb(err)
815 GitRepo.getCommitParsed({read: readObject}, cb)
816 })
817 }, 8)
818 ),
819 msg.content.packs && pull(
820 pull.values(msg.content.packs),
821 paramap(function (pack, cb) {
822 var done = multicb({ pluck: 1, spread: true })
823 self.web.getBlob(req, pack.pack.link, done())
824 self.web.getBlob(req, pack.idx.link, done())
825 done(function (err, readPack, readIdx) {
826 if (err) return cb(self.web.renderError(err))
827 cb(null, gitPack.decodeWithIndex(repo, readPack, readIdx))
828 })
829 }, 4),
830 pull.flatten(),
831 pull.asyncMap(function (obj, cb) {
832 if (obj.type == 'commit')
833 GitRepo.getCommitParsed(obj, cb)
834 else
835 pull(obj.read, pull.drain(null, cb))
836 }),
837 pull.filter()
838 )
839 ])
840
841 return self.renderRepoPage(req, repo, 'activity', null, title, cat([
842 pull.once('<a href="?raw" class="raw-link header-align">' +
843 req._t('Data') + '</a>' +
844 '<h3>' + req._t('Update') + '</h3>'),
845 pull(
846 pull.once({key: id, value: msg}),
847 pull.asyncMap(renderRepoUpdate.bind(self, req, repo, true))
848 ),
849 (msg.content.objects || msg.content.packs) &&
850 pull.once('<h3>' + req._t('Commits') + '</h3>'),
851 pull(commits, pull.map(function (commit) {
852 return renderCommit(req, repo, commit)
853 }))
854 ]))
855}
856
857/* Blob */
858
859R.serveRepoBlob = function (req, repo, rev, path) {
860 var self = this
861 return u.readNext(function (cb) {
862 repo.getFile(rev, path, function (err, object) {
863 if (err) return cb(null, self.web.serveBlobNotFound(req, repo.id, err))
864 var type = repo.isCommitHash(rev) ? 'Tree' : 'Branch'
865 var pathLinks = path.length === 0 ? '' :
866 ': ' + linkPath([repo.id, 'tree'], [rev].concat(path))
867 var rawFilePath = [repo.id, 'raw', rev].concat(path)
868 var dirPath = path.slice(0, path.length-1)
869 var filename = path[path.length-1]
870 var extension = u.getExtension(filename)
871 var title = (path.length ? path.join('/') + ' · ' : '') +
872 '%{author}/%{repo}' +
873 (repo.head == 'refs/heads/' + rev ? '' : '@' + rev)
874 cb(null, self.renderRepoPage(req, repo, 'code', rev, title, cat([
875 pull.once('<section><form action="" method="get">' +
876 '<h3>' + req._t(type) + ': ' + rev + ' '),
877 self.revMenu(req, repo, rev),
878 pull.once('</h3></form>'),
879 type == 'Branch' && renderRepoLatest(req, repo, rev),
880 pull.once('</section><section class="collapse">' +
881 '<h3>' + req._t('Files') + pathLinks + '</h3>' +
882 '<div>' + object.length + ' bytes' +
883 '<span class="raw-link">' +
884 u.link(rawFilePath, req._t('Raw')) + '</span>' +
885 '</div></section>' +
886 '<section>'),
887 extension in u.imgMimes
888 ? pull.once('<img src="' + u.encodeLink(rawFilePath) +
889 '" alt="' + u.escape(filename) + '" />')
890 : self.web.renderObjectData(object, filename, repo, rev, dirPath),
891 pull.once('</section>')
892 ])))
893 })
894 })
895}
896
897/* Raw blob */
898
899R.serveRepoRaw = function (req, repo, branch, path) {
900 var self = this
901 return u.readNext(function (cb) {
902 repo.getFile(branch, path, function (err, object) {
903 if (err) return cb(null,
904 self.web.serveBuffer(404, req._t('error.BlobNotFound')))
905 var extension = u.getExtension(path[path.length-1])
906 var contentType = u.imgMimes[extension]
907 cb(null, pull(object.read, self.web.serveRaw(object.length, contentType)))
908 })
909 })
910}
911
912/* Digs */
913
914R.serveRepoDigs = function serveRepoDigs (req, repo) {
915 var self = this
916 return u.readNext(cb => {
917 var title = req._t('Digs') + ' · %{author}/%{repo}'
918 self.web.getVotes(repo.id, (err, votes) => {
919 cb(null, self.renderRepoPage(req, repo, null, null, title,
920 h('section', [
921 h('h3', req._t('Digs')),
922 h('div', `${req._t('Total')}: ${votes.upvotes}`),
923 h('ul', u.paraSourceMap(Object.keys(votes.upvoters), (feedId, cb) => {
924 self.web.about.getName(feedId, (err, name) => {
925 cb(null, h('li', u.link([feedId], name)))
926 })
927 }))
928 ])
929 ))
930 })
931 })
932}
933
934/* Forks */
935
936R.getForks = function (repo, includeSelf) {
937 var self = this
938 return pull(
939 cat([
940 includeSelf && pull.once(repo.id),
941 // get downstream repos
942 pull(
943 self.web.ssb.links({
944 dest: repo.id,
945 rel: 'upstream'
946 }),
947 pull.map('key')
948 ),
949 // look for other repos that previously had pull requests to this one
950 pull(
951 self.web.ssb.links({
952 dest: repo.id,
953 values: true,
954 rel: 'project'
955 }),
956 pull.filter(function (msg) {
957 var c = msg && msg.value && msg.value.content
958 return c && c.type == 'pull-request'
959 }),
960 pull.map(function (msg) { return msg.value.content.head_repo })
961 )
962 ]),
963 pull.unique(),
964 paramap(function (key, cb) {
965 self.web.ssb.get(key, function (err, value) {
966 if (err) cb(err)
967 else cb(null, {key: key, value: value})
968 })
969 }, 4),
970 pull.filter(function (msg) {
971 var c = msg && msg.value && msg.value.content
972 return c && c.type == 'git-repo'
973 }),
974 paramap(function (msg, cb) {
975 self.web.getRepoFullName(msg.value.author, msg.key,
976 function (err, repoName, authorName) {
977 if (err) return cb(err)
978 cb(null, {
979 key: msg.key,
980 value: msg.value,
981 repoName: repoName,
982 authorName: authorName
983 })
984 })
985 }, 8)
986 )
987}
988
989R.serveRepoForks = function (req, repo) {
990 var hasForks
991 var title = req._t('Forks') + ' · %{author}/%{repo}'
992 return this.renderRepoPage(req, repo, null, null, title, cat([
993 pull.once('<h3>' + req._t('Forks') + '</h3>'),
994 pull(
995 this.getForks(repo),
996 pull.map(function (msg) {
997 hasForks = true
998 return '<section class="collapse">' +
999 u.link([msg.value.author], msg.authorName) + ' / ' +
1000 u.link([msg.key], msg.repoName) +
1001 '<span class="right-bar">' +
1002 u.timestamp(msg.value.timestamp, req) +
1003 '</span></section>'
1004 })
1005 ),
1006 u.readOnce(function (cb) {
1007 cb(null, hasForks ? '' : req._t('NoForks'))
1008 })
1009 ]))
1010}
1011
1012R.serveRepoForkPrompt = function (req, repo) {
1013 var title = req._t('Fork') + ' · %{author}/%{repo}'
1014 return this.renderRepoPage(req, repo, null, null, title, pull.once(
1015 '<form action="" method="post" onreset="history.back()">' +
1016 '<h3>' + req._t('ForkRepoPrompt') + '</h3>' +
1017 '<p>' + u.hiddenInputs({ id: repo.id }) +
1018 '<button class="btn open" type="submit" name="action" value="fork">' +
1019 req._t('Fork') +
1020 '</button>' +
1021 ' <button class="btn" type="reset">' +
1022 req._t('Cancel') + '</button>' +
1023 '</p></form>'
1024 ))
1025}
1026
1027R.serveIssueOrPullRequest = function (req, repo, issue, path, id) {
1028 return issue.msg.value.content.type == 'pull-request'
1029 ? this.pulls.serveRepoPullReq(req, repo, issue, path, id)
1030 : this.issues.serveRepoIssue(req, repo, issue, path, id)
1031}
1032
1033function getRepoLastMod(repo, cb) {
1034 repo.getState(function (err, state) {
1035 if (err) return cb(err)
1036 var lastMod = new Date(Math.max.apply(Math, state.refs.map(function (ref) {
1037 return ref.link.value.timestamp
1038 }))) || new Date()
1039 cb(null, lastMod)
1040 })
1041}
1042
1043R.serveRepoRefs = function (req, repo) {
1044 var self = this
1045 return u.readNext(function (cb) {
1046 getRepoLastMod(repo, function (err, lastMod) {
1047 if (err) return cb(null, self.web.serveError(req, err, 500))
1048 if (u.ifModifiedSince(req, lastMod)) {
1049 return cb(null, pull.once([304]))
1050 }
1051 repo.getState(function (err, state) {
1052 if (err) return cb(null, self.web.serveError(req, err, 500))
1053 var buf = state.refs.sort(function (a, b) {
1054 return a.name > b.name ? 1 : a.name < b.name ? -1 : 0
1055 }).map(function (ref) {
1056 return ref.hash + '\t' + ref.name + '\n'
1057 }).join('')
1058 cb(null, pull.values([[200, {
1059 'Content-Type': 'text/plain; charset=utf-8',
1060 'Content-Length': Buffer.byteLength(buf),
1061 'Last-Modified': lastMod.toGMTString()
1062 }], buf]))
1063 })
1064 })
1065 })
1066}
1067
1068R.serveRepoObject = function (req, repo, sha1) {
1069 var self = this
1070 if (!/[0-9a-f]{20}/.test(sha1)) return pull.once([401])
1071 return u.readNext(function (cb) {
1072 repo.getObjectFromAny(sha1, function (err, obj) {
1073 if (err) return cb(null, pull.once([404]))
1074 cb(null, cat([
1075 pull.once([200, {
1076 'Content-Type': 'application/x-git-loose-object',
1077 'Cache-Control': 'max-age=31536000'
1078 }]),
1079 pull(
1080 cat([
1081 pull.values([obj.type, ' ', obj.length.toString(10), '\0']),
1082 obj.read
1083 ]),
1084 toPull(zlib.createDeflate())
1085 )
1086 ]))
1087 })
1088 })
1089}
1090
1091R.serveRepoHead = function (req, repo) {
1092 var self = this
1093 return u.readNext(function (cb) {
1094 repo.getHead(function (err, name) {
1095 if (err) return cb(null, pull.once([500]))
1096 return cb(null, self.web.serveBuffer(200, 'ref: ' + name))
1097 })
1098 })
1099}
1100
1101R.serveRepoPacksInfo = function (req, repo) {
1102 var self = this
1103 return u.readNext(function (cb) {
1104 getRepoLastMod(repo, function (err, lastMod) {
1105 if (err) return cb(null, self.web.serveError(req, err, 500))
1106 if (u.ifModifiedSince(req, lastMod)) {
1107 return cb(null, pull.once([304]))
1108 }
1109 cb(null, cat([
1110 pull.once([200, {
1111 'Content-Type': 'text/plain; charset=utf-8',
1112 'Last-Modified': lastMod.toGMTString()
1113 }]),
1114 pull(
1115 repo.packs(),
1116 pull.map(function (pack) {
1117 var sha1 = pack.sha1
1118 if (!sha1) {
1119 // make up a sha1 and hope git doesn't notice
1120 var packId = new Buffer(pack.packId.substr(1, 44), 'base64')
1121 sha1 = packId.slice(0, 20).toString('hex')
1122 }
1123 return 'P pack-' + sha1 + '.pack\n'
1124 })
1125 )
1126 ]))
1127 })
1128 })
1129}
1130
1131R.serveRepoPack = function (req, repo, name) {
1132 var m = name.match(/^pack-(.*)\.(pack|idx)$/)
1133 if (!m) return pull.once([400])
1134 var hex;
1135 try {
1136 hex = new Buffer(m[1], 'hex')
1137 } catch(e) {
1138 return pull.once([400])
1139 }
1140
1141 var self = this
1142 return u.readNext(function (cb) {
1143 pull(
1144 repo.packs(),
1145 pull.filter(function (pack) {
1146 var sha1 = pack.sha1
1147 ? new Buffer(pack.sha1, 'hex')
1148 : new Buffer(pack.packId.substr(1, 44), 'base64').slice(0, 20)
1149 return sha1.equals(hex)
1150 }),
1151 pull.take(1),
1152 pull.collect(function (err, packs) {
1153 if (err) return console.error(err), cb(null, pull.once([500]))
1154 if (packs.length < 1) return cb(null, pull.once([404]))
1155 var pack = packs[0]
1156
1157 if (m[2] === 'pack') {
1158 repo.getPackfile(pack.packId, function (err, read) {
1159 if (err) return cb(err)
1160 cb(null, pull(read,
1161 self.web.serveRaw(null, 'application/x-git-packed-objects')
1162 ))
1163 })
1164 }
1165
1166 if (m[2] === 'idx') {
1167 repo.getPackIndex(pack.idxId, function (err, read) {
1168 if (err) return cb(err)
1169 cb(null, pull(read,
1170 self.web.serveRaw(null, 'application/x-git-packed-objects-toc')
1171 ))
1172 })
1173 }
1174 })
1175 )
1176 })
1177}
1178

Built with git-ssb-web