git ssb

30+

cel / git-ssb-web



Tree: b0bc02aa8cd11a7db1f9b1758ed7762c117cad1e

Files: b0bc02aa8cd11a7db1f9b1758ed7762c117cad1e / lib / repos / index.js

32826 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 source: repo.feed,
280 rel: 'repo',
281 values: true,
282 reverse: true
283 }),
284 pull.map(renderRepoUpdate.bind(self, req, repo))
285 ),
286 u.readOnce(function (cb) {
287 var done = multicb({ pluck: 1, spread: true })
288 self.web.about.getName(repo.feed, done())
289 self.web.getMsg(repo.id, done())
290 done(function (err, authorName, msg) {
291 if (err) return cb(err)
292 self.web.renderFeedItem(req, {
293 key: repo.id,
294 value: msg,
295 authorName: authorName
296 }, cb)
297 })
298 })
299 ]))
300}
301
302function renderRepoUpdate(req, repo, msg, full) {
303 var c = msg.value.content
304
305 if (c.type != 'git-update') {
306 return ''
307 // return renderFeedItem(msg, cb)
308 // TODO: render post, issue, pull-request
309 }
310
311 var branches = []
312 var tags = []
313 if (c.refs) for (var name in c.refs) {
314 var m = name.match(/^refs\/(heads|tags)\/(.*)$/) || [,, name]
315 ;(m[1] == 'tags' ? tags : branches)
316 .push({name: m[2], value: c.refs[name]})
317 }
318 var numObjects = c.objects ? Object.keys(c.objects).length : 0
319
320 var dateStr = new Date(msg.value.timestamp).toLocaleString(req._locale)
321 return '<section class="collapse">' +
322 u.link([msg.key], dateStr) + '<br>' +
323 branches.map(function (update) {
324 if (!update.value) {
325 return '<s>' + u.escape(update.name) + '</s><br/>'
326 } else {
327 var commitLink = u.link([repo.id, 'commit', update.value])
328 var branchLink = u.link([repo.id, 'tree', update.name])
329 return branchLink + ' &rarr; <tt>' + commitLink + '</tt><br/>'
330 }
331 }).join('') +
332 tags.map(function (update) {
333 return update.value
334 ? u.link([repo.id, 'tag', update.value], update.name)
335 : '<s>' + u.escape(update.name) + '</s>'
336 }).join(', ') +
337 '</section>'
338}
339
340/* Repo commits */
341
342R.serveRepoCommits = function (req, repo, branch) {
343 var query = req._u.query
344 var title = req._t('Commits') + ' · %{author}/%{repo}'
345 return this.renderRepoPage(req, repo, 'commits', branch, title, cat([
346 pull.once('<h3>' + req._t('Commits') + '</h3>'),
347 pull(
348 repo.readLog(query.start || branch),
349 pull.take(20),
350 paramap(repo.getCommitParsed.bind(repo), 8),
351 paginate(
352 !query.start ? '' : function (first, cb) {
353 cb(null, '&hellip;')
354 },
355 pull.map(renderCommit.bind(this, req, repo)),
356 function (commit, cb) {
357 cb(null, commit.parents && commit.parents[0] ?
358 '<a href="?start=' + commit.id + '">' +
359 req._t('Older') + '</a>' : '')
360 }
361 )
362 )
363 ]))
364}
365
366function renderCommit(req, repo, commit) {
367 var commitPath = [repo.id, 'commit', commit.id]
368 var treePath = [repo.id, 'tree', commit.id]
369 return '<section class="collapse">' +
370 '<strong>' + u.link(commitPath, commit.title) + '</strong><br>' +
371 '<tt>' + commit.id + '</tt> ' +
372 u.link(treePath, req._t('Tree')) + '<br>' +
373 u.escape(commit.author.name) + ' &middot; ' +
374 commit.author.date.toLocaleString(req._locale) +
375 (commit.separateAuthor ? '<br>' + req._t('CommittedOn', {
376 name: u.escape(commit.committer.name),
377 date: commit.committer.date.toLocaleString(req._locale)
378 }) : '') +
379 '</section>'
380}
381
382/* Branch menu */
383
384R.formatRevOptions = function (currentName) {
385 return function (name) {
386 var htmlName = u.escape(name)
387 return '<option value="' + htmlName + '"' +
388 (name == currentName ? ' selected="selected"' : '') +
389 '>' + htmlName + '</option>'
390 }
391}
392
393R.formatRevType = function(req, type) {
394 return (
395 type == 'heads' ? req._t('Branches') :
396 type == 'tags' ? req._t('Tags') :
397 type)
398}
399
400R.revMenu = function (req, repo, currentName) {
401 var self = this
402 return u.readOnce(function (cb) {
403 repo.getRefNames(function (err, refs) {
404 if (err) return cb(err)
405 cb(null, '<select name="rev" onchange="this.form.submit()">' +
406 Object.keys(refs).map(function (group) {
407 return '<optgroup ' +
408 'label="' + self.formatRevType(req, group) + '">' +
409 refs[group].map(self.formatRevOptions(currentName)).join('') +
410 '</optgroup>'
411 }).join('') +
412 '</select><noscript> ' +
413 '<input type="submit" value="' + req._t('Go') + '"/></noscript>')
414 })
415 })
416}
417
418/* Repo tree */
419
420function renderRepoLatest(req, repo, rev) {
421 if (!rev) return pull.empty()
422 return u.readOnce(function (cb) {
423 repo.getCommitParsed(rev, function (err, commit) {
424 if (err) return cb(err)
425 var commitPath = [repo.id, 'commit', commit.id]
426 cb(null,
427 req._t('Latest') + ': ' +
428 '<strong>' + u.link(commitPath, commit.title) + '</strong><br/>' +
429 '<tt>' + commit.id + '</tt><br/> ' +
430 req._t('CommittedOn', {
431 name: u.escape(commit.committer.name),
432 date: commit.committer.date.toLocaleString(req._locale)
433 }) +
434 (commit.separateAuthor ? '<br/>' + req._t('AuthoredOn', {
435 name: u.escape(commit.author.name),
436 date: commit.author.date.toLocaleString(req._locale)
437 }) : ''))
438 })
439 })
440}
441
442// breadcrumbs
443function linkPath(basePath, path) {
444 path = path.slice()
445 var last = path.pop()
446 return path.map(function (dir, i) {
447 return u.link(basePath.concat(path.slice(0, i+1)), dir)
448 }).concat(last).join(' / ')
449}
450
451function renderRepoTree(req, repo, rev, path) {
452 var pathLinks = path.length === 0 ? '' :
453 ': ' + linkPath([repo.id, 'tree'], [rev].concat(path))
454 return cat([
455 pull.once('<h3>' + req._t('Files') + pathLinks + '</h3>'),
456 pull(
457 repo.readDir(rev, path),
458 pull.map(function (file) {
459 var type = (file.mode === 040000) ? 'tree' :
460 (file.mode === 0160000) ? 'commit' : 'blob'
461 if (type == 'commit')
462 return [
463 '<span title="' + req._t('gitCommitLink') + '">🖈</span>',
464 '<span title="' + u.escape(file.id) + '">' +
465 u.escape(file.name) + '</span>']
466 var filePath = [repo.id, type, rev].concat(path, file.name)
467 return ['<i>' + (type == 'tree' ? '📁' : '📄') + '</i>',
468 u.link(filePath, file.name)]
469 }),
470 table('class="files"')
471 )
472 ])
473}
474
475/* Repo readme */
476
477R.renderRepoReadme = function (req, repo, branch, path) {
478 var self = this
479 return u.readNext(function (cb) {
480 pull(
481 repo.readDir(branch, path),
482 pull.filter(function (file) {
483 return /readme(\.|$)/i.test(file.name)
484 }),
485 pull.take(1),
486 pull.collect(function (err, files) {
487 if (err) return cb(null, pull.empty())
488 var file = files[0]
489 if (!file)
490 return cb(null, pull.once(path.length ? '' :
491 '<p>' + req._t('NoReadme') + '</p>'))
492 repo.getObjectFromAny(file.id, function (err, obj) {
493 if (err) return cb(err)
494 cb(null, cat([
495 pull.once('<section><h4><a name="readme">' +
496 u.escape(file.name) + '</a></h4><hr/>'),
497 self.web.renderObjectData(obj, file.name, repo, branch, path),
498 pull.once('</section>')
499 ]))
500 })
501 })
502 )
503 })
504}
505
506/* Repo commit */
507
508R.serveRepoCommit = function (req, repo, rev) {
509 var self = this
510 return u.readNext(function (cb) {
511 repo.getCommitParsed(rev, function (err, commit) {
512 if (err) return cb(err)
513 var commitPath = [repo.id, 'commit', commit.id]
514 var treePath = [repo.id, 'tree', commit.id]
515 var title = u.escape(commit.title) + ' · ' +
516 '%{author}/%{repo}@' + commit.id.substr(0, 8)
517 cb(null, self.renderRepoPage(req, repo, null, rev, title, cat([
518 pull.once(
519 '<h3>' + u.link(commitPath,
520 req._t('CommitRev', {rev: rev})) + '</h3>' +
521 '<section class="collapse">' +
522 '<div class="right-bar">' +
523 u.link(treePath, req._t('BrowseFiles')) +
524 '</div>' +
525 '<h4>' + u.linkify(u.escape(commit.title)) + '</h4>' +
526 (commit.body ? u.linkify(u.pre(commit.body)) : '') +
527 (commit.separateAuthor ? req._t('AuthoredOn', {
528 name: u.escape(commit.author.name),
529 date: commit.author.date.toLocaleString(req._locale)
530 }) + '<br/>' : '') +
531 req._t('CommittedOn', {
532 name: u.escape(commit.committer.name),
533 date: commit.committer.date.toLocaleString(req._locale)
534 }) + '<br/>' +
535 commit.parents.map(function (id) {
536 return req._t('Parent') + ': ' +
537 u.link([repo.id, 'commit', id], id)
538 }).join('<br>') +
539 '</section>' +
540 '<section><h3>' + req._t('FilesChanged') + '</h3>'),
541 // TODO: show diff from all parents (merge commits)
542 self.renderDiffStat(req, [repo, repo], [commit.parents[0], commit.id]),
543 pull.once('</section>')
544 ])))
545 })
546 })
547}
548
549/* Repo tag */
550
551R.serveRepoTag = function (req, repo, rev, path) {
552 var self = this
553 return u.readNext(function (cb) {
554 repo.getTagParsed(rev, function (err, tag) {
555 if (err) {
556 if (/Expected tag, got commit/.test(err.message)) {
557 req._u.pathname = u.encodeLink([repo.id, 'commit', rev].concat(path))
558 return cb(null, self.web.serveRedirect(req, url.format(req._u)))
559 }
560 return cb(null, self.web.serveError(req, err))
561 }
562
563 var title = req._t('TagName', {
564 tag: u.escape(tag.tag)
565 }) + ' · %{author}/%{repo}'
566 var body = (tag.title + '\n\n' +
567 tag.body.replace(/-----BEGIN PGP SIGNATURE-----\n[^.]*?\n-----END PGP SIGNATURE-----\s*$/, '')).trim()
568 var date = tag.tagger.date
569 cb(null, self.renderRepoPage(req, repo, 'tags', tag.object, title,
570 pull.once(
571 '<section class="collapse">' +
572 '<h3>' + u.link([repo.id, 'tag', rev], tag.tag) + '</h3>' +
573 req._t('TaggedOn', {
574 name: u.escape(tag.tagger.name),
575 date: date && date.toLocaleString(req._locale)
576 }) + '<br/>' +
577 u.link([repo.id, tag.type, tag.object]) +
578 u.linkify(u.pre(body)) +
579 '</section>')))
580 })
581 })
582}
583
584
585/* Diff stat */
586
587R.renderDiffStat = function (req, repos, treeIds) {
588 if (treeIds.length == 0) treeIds = [null]
589 var id = treeIds[0]
590 var lastI = treeIds.length - 1
591 var oldTree = treeIds[0]
592 var changedFiles = []
593 return cat([
594 pull(
595 GitRepo.diffTrees(repos, treeIds, true),
596 pull.map(function (item) {
597 var filename = u.escape(item.filename = item.path.join('/'))
598 var oldId = item.id && item.id[0]
599 var newId = item.id && item.id[lastI]
600 var oldMode = item.mode && item.mode[0]
601 var newMode = item.mode && item.mode[lastI]
602 var action =
603 !oldId && newId ? req._t('action.added') :
604 oldId && !newId ? req._t('action.deleted') :
605 oldMode != newMode ? req._t('action.changedMode', {
606 old: oldMode.toString(8),
607 new: newMode.toString(8)
608 }) : req._t('changed')
609 if (item.id)
610 changedFiles.push(item)
611 var blobsPath = item.id[1]
612 ? [repos[1].id, 'blob', treeIds[1]]
613 : [repos[0].id, 'blob', treeIds[0]]
614 var rawsPath = item.id[1]
615 ? [repos[1].id, 'raw', treeIds[1]]
616 : [repos[0].id, 'raw', treeIds[0]]
617 item.blobPath = blobsPath.concat(item.path)
618 item.rawPath = rawsPath.concat(item.path)
619 var fileHref = item.id ?
620 '#' + encodeURIComponent(item.path.join('/')) :
621 u.encodeLink(item.blobPath)
622 return ['<a href="' + fileHref + '">' + filename + '</a>', action]
623 }),
624 table()
625 ),
626 pull(
627 pull.values(changedFiles),
628 paramap(function (item, cb) {
629 var extension = u.getExtension(item.filename)
630 if (extension in u.imgMimes) {
631 var filename = u.escape(item.filename)
632 return cb(null,
633 '<pre><table class="code">' +
634 '<tr><th id="' + u.escape(item.filename) + '">' +
635 filename + '</th></tr>' +
636 '<tr><td><img src="' + u.encodeLink(item.rawPath) + '"' +
637 ' alt="' + filename + '"/></td></tr>' +
638 '</table></pre>')
639 }
640 var done = multicb({ pluck: 1, spread: true })
641 var mode0 = item.mode && item.mode[0]
642 var modeI = item.mode && item.mode[lastI]
643 var isSubmodule = (modeI == 0160000)
644 getRepoObjectString(repos[0], item.id[0], mode0, done())
645 getRepoObjectString(repos[1], item.id[lastI], modeI, done())
646 done(function (err, strOld, strNew) {
647 if (err) return cb(err)
648 cb(null, htmlLineDiff(req, item.filename, item.filename,
649 strOld, strNew,
650 u.encodeLink(item.blobPath), !isSubmodule))
651 })
652 }, 4)
653 )
654 ])
655}
656
657function htmlLineDiff(req, filename, anchor, oldStr, newStr, blobHref,
658 showViewLink) {
659 return '<pre><table class="code">' +
660 '<tr><th colspan=3 id="' + u.escape(anchor) + '">' + filename +
661 (showViewLink === false ? '' :
662 '<span class="right-bar">' +
663 '<a href="' + blobHref + '">' + req._t('View') + '</a> ' +
664 '</span>') +
665 '</th></tr>' +
666 (oldStr.length + newStr.length > 200000
667 ? '<tr><td class="diff-info">' + req._t('diff.TooLarge') + '<br>' +
668 req._t('diff.OldFileSize', {bytes: oldStr.length}) + '<br>' +
669 req._t('diff.NewFileSize', {bytes: newStr.length}) + '</td></tr>'
670 : tableDiff(oldStr, newStr, filename)) +
671 '</table></pre>'
672}
673
674function tableDiff(oldStr, newStr, filename) {
675 var diff = JsDiff.structuredPatch('', '', oldStr, newStr)
676 var groups = diff.hunks.map(function (hunk) {
677 var oldLine = hunk.oldStart
678 var newLine = hunk.newStart
679 var header = '<tr class="diff-hunk-header"><td colspan=2></td><td>' +
680 '@@ -' + oldLine + ',' + hunk.oldLines + ' ' +
681 '+' + newLine + ',' + hunk.newLines + ' @@' +
682 '</td></tr>'
683 return [header].concat(hunk.lines.map(function (line) {
684 var s = line[0]
685 if (s == '\\') return
686 var html = u.highlight(line, u.getExtension(filename))
687 var trClass = s == '+' ? 'diff-new' : s == '-' ? 'diff-old' : ''
688 var lineNums = [s == '+' ? '' : oldLine++, s == '-' ? '' : newLine++]
689 var id = [filename].concat(lineNums).join('-')
690 return '<tr id="' + u.escape(id) + '" class="' + trClass + '">' +
691 lineNums.map(function (num) {
692 return '<td class="code-linenum">' +
693 (num ? '<a href="#' + encodeURIComponent(id) + '">' +
694 num + '</a>' : '') + '</td>'
695 }).join('') +
696 '<td class="code-text">' + html + '</td></tr>'
697 }))
698 })
699 return [].concat.apply([], groups).join('')
700}
701
702/* An unknown message linking to a repo */
703
704R.serveRepoSomething = function (req, repo, id, msg, path) {
705 return this.renderRepoPage(req, repo, null, null, null,
706 pull.once('<section><h3>' + u.link([id]) + '</h3>' +
707 u.json(msg) + '</section>'))
708}
709
710/* Repo update */
711
712function objsArr(objs) {
713 return Array.isArray(objs) ? objs :
714 Object.keys(objs).map(function (sha1) {
715 var obj = Object.create(objs[sha1])
716 obj.sha1 = sha1
717 return obj
718 })
719}
720
721R.serveRepoUpdate = function (req, repo, id, msg, path) {
722 var self = this
723 var raw = req._u.query.raw != null
724 var title = req._t('Update') + ' · %{author}/%{repo}'
725
726 if (raw)
727 return self.renderRepoPage(req, repo, 'activity', null, title, pull.once(
728 '<a href="?" class="raw-link header-align">' +
729 req._t('Info') + '</a>' +
730 '<h3>' + req._t('Update') + '</h3>' +
731 '<section class="collapse">' +
732 u.json({key: id, value: msg}) + '</section>'))
733
734 // convert packs to old single-object style
735 if (msg.content.indexes) {
736 for (var i = 0; i < msg.content.indexes.length; i++) {
737 msg.content.packs[i] = {
738 pack: {link: msg.content.packs[i].link},
739 idx: msg.content.indexes[i]
740 }
741 }
742 }
743
744 var commits = cat([
745 msg.content.objects && pull(
746 pull.values(msg.content.objects),
747 pull.filter(function (obj) { return obj.type == 'commit' }),
748 paramap(function (obj, cb) {
749 self.web.getBlob(req, obj.link || obj.key, function (err, readObject) {
750 if (err) return cb(err)
751 GitRepo.getCommitParsed({read: readObject}, cb)
752 })
753 }, 8)
754 ),
755 msg.content.packs && pull(
756 pull.values(msg.content.packs),
757 paramap(function (pack, cb) {
758 var done = multicb({ pluck: 1, spread: true })
759 self.web.getBlob(req, pack.pack.link, done())
760 self.web.getBlob(req, pack.idx.link, done())
761 done(function (err, readPack, readIdx) {
762 if (err) return cb(self.web.renderError(err))
763 cb(null, gitPack.decodeWithIndex(repo, readPack, readIdx))
764 })
765 }, 4),
766 pull.flatten(),
767 pull.asyncMap(function (obj, cb) {
768 if (obj.type == 'commit')
769 GitRepo.getCommitParsed(obj, cb)
770 else
771 pull(obj.read, pull.drain(null, cb))
772 }),
773 pull.filter()
774 )
775 ])
776
777 return self.renderRepoPage(req, repo, 'activity', null, title, cat([
778 pull.once('<a href="?raw" class="raw-link header-align">' +
779 req._t('Data') + '</a>' +
780 '<h3>' + req._t('Update') + '</h3>' +
781 renderRepoUpdate(req, repo, {key: id, value: msg}, true)),
782 (msg.content.objects || msg.content.packs) &&
783 pull.once('<h3>' + req._t('Commits') + '</h3>'),
784 pull(commits, pull.map(function (commit) {
785 return renderCommit(req, repo, commit)
786 }))
787 ]))
788}
789
790/* Blob */
791
792R.serveRepoBlob = function (req, repo, rev, path) {
793 var self = this
794 return u.readNext(function (cb) {
795 repo.getFile(rev, path, function (err, object) {
796 if (err) return cb(null, self.web.serveBlobNotFound(req, repo.id, err))
797 var type = repo.isCommitHash(rev) ? 'Tree' : 'Branch'
798 var pathLinks = path.length === 0 ? '' :
799 ': ' + linkPath([repo.id, 'tree'], [rev].concat(path))
800 var rawFilePath = [repo.id, 'raw', rev].concat(path)
801 var dirPath = path.slice(0, path.length-1)
802 var filename = path[path.length-1]
803 var extension = u.getExtension(filename)
804 var title = (path.length ? path.join('/') + ' · ' : '') +
805 '%{author}/%{repo}' +
806 (repo.head == 'refs/heads/' + rev ? '' : '@' + rev)
807 cb(null, self.renderRepoPage(req, repo, 'code', rev, title, cat([
808 pull.once('<section><form action="" method="get">' +
809 '<h3>' + req._t(type) + ': ' + rev + ' '),
810 self.revMenu(req, repo, rev),
811 pull.once('</h3></form>'),
812 type == 'Branch' && renderRepoLatest(req, repo, rev),
813 pull.once('</section><section class="collapse">' +
814 '<h3>' + req._t('Files') + pathLinks + '</h3>' +
815 '<div>' + object.length + ' bytes' +
816 '<span class="raw-link">' +
817 u.link(rawFilePath, req._t('Raw')) + '</span>' +
818 '</div></section>' +
819 '<section>'),
820 extension in u.imgMimes
821 ? pull.once('<img src="' + u.encodeLink(rawFilePath) +
822 '" alt="' + u.escape(filename) + '" />')
823 : self.web.renderObjectData(object, filename, repo, rev, dirPath),
824 pull.once('</section>')
825 ])))
826 })
827 })
828}
829
830/* Raw blob */
831
832R.serveRepoRaw = function (req, repo, branch, path) {
833 var self = this
834 return u.readNext(function (cb) {
835 repo.getFile(branch, path, function (err, object) {
836 if (err) return cb(null,
837 self.web.serveBuffer(404, req._t('error.BlobNotFound')))
838 var extension = u.getExtension(path[path.length-1])
839 var contentType = u.imgMimes[extension]
840 cb(null, pull(object.read, self.web.serveRaw(object.length, contentType)))
841 })
842 })
843}
844
845/* Digs */
846
847R.serveRepoDigs = function (req, repo) {
848 var self = this
849 return u.readNext(function (cb) {
850 var title = req._t('Digs') + ' · %{author}/%{repo}'
851 self.web.getVotes(repo.id, function (err, votes) {
852 cb(null, self.renderRepoPage(req, repo, null, null, title, cat([
853 pull.once('<section><h3>' + req._t('Digs') + '</h3>' +
854 '<div>' + req._t('Total') + ': ' + votes.upvotes + '</div>'),
855 pull(
856 pull.values(Object.keys(votes.upvoters)),
857 paramap(function (feedId, cb) {
858 self.web.about.getName(feedId, function (err, name) {
859 if (err) return cb(err)
860 cb(null, u.link([feedId], name))
861 })
862 }, 8),
863 ul()
864 ),
865 pull.once('</section>')
866 ])))
867 })
868 })
869}
870
871/* Forks */
872
873R.getForks = function (repo, includeSelf) {
874 var self = this
875 return pull(
876 cat([
877 includeSelf && pull.once(repo.id),
878 // get downstream repos
879 pull(
880 self.web.ssb.links({
881 dest: repo.id,
882 rel: 'upstream'
883 }),
884 pull.map('key')
885 ),
886 // look for other repos that previously had pull requests to this one
887 pull(
888 self.web.ssb.links({
889 dest: repo.id,
890 values: true,
891 rel: 'project'
892 }),
893 pull.filter(function (msg) {
894 var c = msg && msg.value && msg.value.content
895 return c && c.type == 'pull-request'
896 }),
897 pull.map(function (msg) { return msg.value.content.head_repo })
898 )
899 ]),
900 pull.unique(),
901 paramap(function (key, cb) {
902 self.web.ssb.get(key, function (err, value) {
903 if (err) cb(err)
904 else cb(null, {key: key, value: value})
905 })
906 }, 4),
907 pull.filter(function (msg) {
908 var c = msg && msg.value && msg.value.content
909 return c && c.type == 'git-repo'
910 }),
911 paramap(function (msg, cb) {
912 self.web.getRepoFullName(msg.value.author, msg.key,
913 function (err, repoName, authorName) {
914 if (err) return cb(err)
915 cb(null, {
916 key: msg.key,
917 value: msg.value,
918 repoName: repoName,
919 authorName: authorName
920 })
921 })
922 }, 8)
923 )
924}
925
926R.serveRepoForks = function (req, repo) {
927 var hasForks
928 var title = req._t('Forks') + ' · %{author}/%{repo}'
929 return this.renderRepoPage(req, repo, null, null, title, cat([
930 pull.once('<h3>' + req._t('Forks') + '</h3>'),
931 pull(
932 this.getForks(repo),
933 pull.map(function (msg) {
934 hasForks = true
935 return '<section class="collapse">' +
936 u.link([msg.value.author], msg.authorName) + ' / ' +
937 u.link([msg.key], msg.repoName) +
938 '<span class="right-bar">' +
939 u.timestamp(msg.value.timestamp, req) +
940 '</span></section>'
941 })
942 ),
943 u.readOnce(function (cb) {
944 cb(null, hasForks ? '' : req._t('NoForks'))
945 })
946 ]))
947}
948
949R.serveRepoForkPrompt = function (req, repo) {
950 var title = req._t('Fork') + ' · %{author}/%{repo}'
951 return this.renderRepoPage(req, repo, null, null, title, pull.once(
952 '<form action="" method="post" onreset="history.back()">' +
953 '<h3>' + req._t('ForkRepoPrompt') + '</h3>' +
954 '<p>' + u.hiddenInputs({ id: repo.id }) +
955 '<button class="btn open" type="submit" name="action" value="fork">' +
956 req._t('Fork') +
957 '</button>' +
958 ' <button class="btn" type="reset">' +
959 req._t('Cancel') + '</button>' +
960 '</p></form>'
961 ))
962}
963
964R.serveIssueOrPullRequest = function (req, repo, issue, path, id) {
965 return issue.msg.value.content.type == 'pull-request'
966 ? this.pulls.serveRepoPullReq(req, repo, issue, path, id)
967 : this.issues.serveRepoIssue(req, repo, issue, path, id)
968}
969

Built with git-ssb-web