git ssb

30+

cel / git-ssb-web



Tree: a2e4bfb1c3aad80b5a96cc0f888f9af1f6af6021

Files: a2e4bfb1c3aad80b5a96cc0f888f9af1f6af6021 / lib / repos / index.js

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

Built with git-ssb-web