git ssb

30+

cel / git-ssb-web



Tree: c0c4a89445a7f748556d6403dee36babb70ad67f

Files: c0c4a89445a7f748556d6403dee36babb70ad67f / lib / repos / index.js

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

Built with git-ssb-web