aboutsummaryrefslogtreecommitdiff
path: root/lib/git.js
blob: fa889ef0f4487aa32595217315ddb33b8cb024b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
var pull = require('pull-stream')
var paramap = require('pull-paramap')
var lru = require('hashlru')
var memo = require('asyncmemo')
var u = require('./util')
var packidx = require('pull-git-packidx-parser')
var Reader = require('pull-reader')
var toPull = require('stream-to-pull-stream')
var zlib = require('zlib')
var looper = require('looper')
var multicb = require('multicb')
var kvdiff = require('pull-kvdiff')

var ObjectNotFoundError = u.customError('ObjectNotFoundError')

var types = {
  blob: true,
  commit: true,
  tree: true,
}
var emptyBlobHash = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391'

module.exports = Git

function Git(app) {
  this.app = app

  this.findObject = memo({
    cache: lru(5),
    asString: function (opts) {
      return opts.obj + opts.headMsgId
    }
  }, this._findObject.bind(this))

  this.findObjectInMsg = memo({
    cache: lru(5),
    asString: function (opts) {
      return opts.obj + opts.msg
    }
  }, this._findObjectInMsg.bind(this))

  this.getPackIndex = memo({
    cache: lru(4),
    asString: JSON.stringify
  }, this._getPackIndex.bind(this))
}

// open, read, buffer and callback an object
Git.prototype.getObject = function (opts, cb) {
  var self = this
  self.openObject(opts, function (err, obj) {
    if (err) return cb(err)
    pull(
      self.readObject(obj),
      u.pullConcat(cb)
    )
  })
}

// get a message that pushed an object
Git.prototype.getObjectMsg = function (opts, cb) {
  this.findObject(opts, function (err, loc) {
    if (err) return cb(err)
    cb(null, loc.msg)
  })
}

Git.prototype.openObject = function (opts, cb) {
  var self = this
  self.findObjectInMsg(opts, function (err, loc) {
    if (err) return cb(err)
    self.app.ensureHasBlobs([loc.packLink], function (err) {
      if (err) return cb(err)
      cb(null, {
        type: opts.type,
        length: opts.length,
        offset: loc.offset,
        next: loc.next,
        packLink: loc.packLink,
        idx: loc.idx,
        msg: loc.msg,
      })
    })
  })
}

Git.prototype.readObject = function (obj) {
  if (obj.offset === obj.next) return pull.empty()
  return pull(
    this.app.readBlobSlice(obj.packLink, {start: obj.offset, end: obj.next}),
    this.decodeObject({
      type: obj.type,
      length: obj.length,
      packLink: obj.packLink,
      idx: obj.idx,
    })
  )
}

// find which packfile contains a git object, and where in the packfile it is
// located
Git.prototype._findObject = function (opts, cb) {
  if (!opts.headMsgId) return cb(new TypeError('missing head message id'))
  if (!opts.obj) return cb(new TypeError('missing object id'))
  var self = this
  var objId = opts.obj
  if (objId === emptyBlobHash) {
    // special case: the empty blob may be found anywhere
    self.app.getMsgDecrypted(opts.headMsgId, function (err, msg) {
      if (err) return cb(err)
      return cb(null, {
        offset: 0,
        next: 0,
        packLink: null,
        idx: null,
        msg: msg,
      })
    })
  }
  self.findObjectMsgs(opts, function (err, msgs) {
    if (err) return cb(err)
    if (msgs.length === 0)
      return cb(new ObjectNotFoundError('unable to find git object ' + objId))
    self.findObjectInMsgs(objId, msgs, cb)
  })
}

Git.prototype._findObjectInMsg = function (opts, cb) {
  if (!opts.msg) return cb(new TypeError('missing message id'))
  if (!opts.obj) return cb(new TypeError('missing object id'))
  var self = this
  self.app.getMsgDecrypted(opts.msg, function (err, msg) {
    if (err) return cb(err)
    self.findObjectInMsgs(opts.obj, [msg], cb)
  })
}

Git.prototype.findObjectInMsgs = function (objId, msgs, cb) {
  var self = this
  var objIdBuf = new Buffer(objId, 'hex')
  // if blobs may need to be fetched, try to ask the user about as many of them
  // at one time as possible
  var packidxs = [].concat.apply([], msgs.map(function (msg) {
    var c = msg.value.content
    var idxs = u.toArray(c.indexes).map(u.toLink)
    return u.toArray(c.packs).map(u.toLink).map(function (pack, i) {
      var idx = idxs[i]
      if (pack && idx) return {
        msg: msg,
        packLink: pack,
        idxLink: idx,
      }
    })
  })).filter(Boolean)
  var blobLinks = packidxs.length === 1
    ? [packidxs[0].idxLink, packidxs[0].packLink]
    : packidxs.map(function (packidx) {
      return packidx.idxLink
    })
  self.app.ensureHasBlobs(blobLinks, function (err) {
    if (err) return cb(err)
    pull(
      pull.values(packidxs),
      paramap(function (pack, cb) {
        self.getPackIndex(pack.idxLink, function (err, idx) {
          if (err) return cb(err)
          var offset = idx.find(objIdBuf)
          if (!offset) return cb()
          cb(null, {
            offset: offset.offset,
            next: offset.next,
            packLink: pack.packLink,
            idx: idx,
            msg: pack.msg,
          })
        })
      }, 4),
      pull.filter(),
      pull.take(1),
      pull.collect(function (err, offsets) {
        if (err) return cb(err)
        if (offsets.length === 0)
          return cb(new ObjectNotFoundError('unable to find git object '
            + objId + ' in ' + msgs.length + ' messages'))
        cb(null, offsets[0])
      })
    )
  })
}

// given an object id and ssb msg id, get a set of messages of which at least one pushed the object.
Git.prototype.findObjectMsgs = function (opts, cb) {
  var self = this
  var id = opts.obj
  var headMsgId = opts.headMsgId
  var ended = false
  var waiting = 0
  var maybeMsgs = []

  function cbOnce(err, msgs) {
    if (ended) return
    ended = true
    cb(err, msgs)
  }

  function objectMatches(commit) {
    return commit && (commit === id || commit.sha1 === id)
  }

  if (!headMsgId) return cb(new TypeError('missing head message id'))
  if (!u.isRef(headMsgId))
    return cb(new TypeError('bad head message id \'' + headMsgId + '\''))

  ;(function getMsg(id) {
    waiting++
    self.app.getMsgDecrypted(id, function (err, msg) {
      waiting--
      if (ended) return
      if (err && err.name == 'NotFoundError')
        return cbOnce(new Error('missing message ' + headMsgId))
      if (err) return cbOnce(err)
      var c = msg.value.content
      if (typeof c === 'string')
        return cbOnce(new Error('unable to decrypt message ' + msg.key))
      if ((u.toArray(c.object_ids).some(objectMatches))
      || (u.toArray(c.tags).some(objectMatches))
      || (u.toArray(c.commits).some(objectMatches))) {
        // found the object
        return cbOnce(null, [msg])
      } else if (!c.object_ids) {
        // the object might be here
        maybeMsgs.push(msg)
      }
      // traverse the DAG to keep looking for the object
      u.toArray(c.repoBranch).filter(u.isRef).forEach(getMsg)
      if (waiting === 0) {
        cbOnce(null, maybeMsgs)
      }
    })
  })(headMsgId)
}

Git.prototype._getPackIndex = function (idxBlobLink, cb) {
  pull(this.app.readBlob(idxBlobLink), packidx(cb))
}

var objectTypes = [
  'none', 'commit', 'tree', 'blob',
  'tag', 'unused', 'ofs-delta', 'ref-delta'
]

function readTypedVarInt(reader, cb) {
  var type, value, shift
  reader.read(1, function (end, buf) {
    if (ended = end) return cb(end)
    var firstByte = buf[0]
    type = objectTypes[(firstByte >> 4) & 7]
    value = firstByte & 15
    shift = 4
    checkByte(firstByte)
  })

  function checkByte(byte) {
    if (byte & 0x80)
      reader.read(1, gotByte)
    else
      cb(null, type, value)
  }

  function gotByte(end, buf) {
    if (ended = end) return cb(end)
    var byte = buf[0]
    value += (byte & 0x7f) << shift
    shift += 7
    checkByte(byte)
  }
}

function readVarInt(reader, cb) {
  var value = 0, shift = 0
  reader.read(1, function gotByte(end, buf) {
    if (ended = end) return cb(end)
    var byte = buf[0]
    value += (byte & 0x7f) << shift
    shift += 7
    if (byte & 0x80)
      reader.read(1, gotByte)
    else
      cb(null, value)
  })
}

function inflate(read) {
  return toPull(zlib.createInflate())(read)
}

Git.prototype.decodeObject = function (opts) {
  var self = this
  var packLink = opts.packLink
  return function (read) {
    var reader = Reader()
    reader(read)
    return u.readNext(function (cb) {
      readTypedVarInt(reader, function (end, type, length) {
        if (end === true) cb(new Error('Missing object type'))
        else if (end) cb(end)
        else if (type === 'ref-delta') getObjectFromRefDelta(length, cb)
        else if (opts.type && type !== opts.type)
          cb(new Error('expected type \'' + opts.type + '\' ' +
            'but found \'' + type + '\''))
        else if (opts.length && length !== opts.length)
          cb(new Error('expected length ' + opts.length + ' ' +
            'but found ' + length))
          else cb(null, inflate(reader.read()))
      })
    })

    function getObjectFromRefDelta(length, cb) {
      reader.read(20, function (end, sourceHash) {
        if (end) return cb(end)
        var inflatedReader = Reader()
        pull(reader.read(), inflate, inflatedReader)
        readVarInt(inflatedReader, function (err, expectedSourceLength) {
          if (err) return cb(err)
          readVarInt(inflatedReader, function (err, expectedTargetLength) {
            if (err) return cb(err)
            var offset = opts.idx.find(sourceHash)
            if (!offset) return cb(null, 'missing source object ' +
              sourcehash.toString('hex'))
            var readSource = pull(
              self.app.readBlobSlice(opts.packLink, {
                start: offset.offset,
                end: offset.next
              }),
              self.decodeObject({
                type: opts.type,
                length: expectedSourceLength,
                packLink: opts.packLink,
                idx: opts.idx
              })
            )
            cb(null, patchObject(inflatedReader, length, readSource, expectedTargetLength))
          })
        })
      })
    }
  }
}

function readOffsetSize(cmd, reader, readCb) {
  var offset = 0, size = 0

  function addByte(bit, outPos, cb) {
    if (cmd & (1 << bit))
      reader.read(1, function (err, buf) {
        if (err) readCb(err)
        else cb(buf[0] << (outPos << 3))
      })
    else
      cb(0)
  }

  addByte(0, 0, function (val) {
    offset = val
    addByte(1, 1, function (val) {
      offset |= val
      addByte(2, 2, function (val) {
        offset |= val
        addByte(3, 3, function (val) {
          offset |= val
          addSize()
        })
      })
    })
  })
  function addSize() {
    addByte(4, 0, function (val) {
      size = val
      addByte(5, 1, function (val) {
        size |= val
        addByte(6, 2, function (val) {
          size |= val
          readCb(null, offset, size || 0x10000)
        })
      })
    })
  }
}

function patchObject(deltaReader, deltaLength, readSource, targetLength) {
  var srcBuf
  var ended

  return u.readNext(function (cb) {
    pull(readSource, u.pullConcat(function (err, buf) {
      if (err) return cb(err)
      srcBuf = buf
      cb(null, read)
    }))
  })

  function read(abort, cb) {
    if (ended) return cb(ended)
    deltaReader.read(1, function (end, dBuf) {
      if (ended = end) return cb(end)
      var cmd = dBuf[0]
      if (cmd & 0x80)
        // skip a variable amount and then pass through a variable amount
        readOffsetSize(cmd, deltaReader, function (err, offset, size) {
          if (err) return earlyEnd(err)
          var buf = srcBuf.slice(offset, offset + size)
          cb(end, buf)
        })
      else if (cmd)
        // insert `cmd` bytes from delta
        deltaReader.read(cmd, cb)
      else
        cb(new Error("unexpected delta opcode 0"))
    })

    function earlyEnd(err) {
      cb(err === true ? new Error('stream ended early') : err)
    }
  }
}

var gitNameRegex = /^(.*) <(([^>@]*)(@[^>]*)?)> (.*) (.*)$/
function parseName(line) {
  var m = gitNameRegex.exec(line)
  if (!m) return null
  return {
    name: m[1],
    email: m[2],
    localpart: m[3],
    feed: u.isRef(m[4]) && m[4] || undefined,
    date: new Date(m[5] * 1000),
    tz: m[6],
  }
}

Git.prototype.getCommit = function (obj, cb) {
  pull(this.readObject(obj), u.pullConcat(function (err, buf) {
    if (err) return cb(err)
    var commit = {
      msg: obj.msg,
      parents: [],
    }
    var authorLine, committerLine
    var lines = buf.toString('utf8').split('\n')
    for (var line; (line = lines.shift()); ) {
      var parts = line.split(' ')
      var prop = parts.shift()
      var value = parts.join(' ')
      switch (prop) {
        case 'tree':
          commit.tree = value
          break
        case 'parent':
          commit.parents.push(value)
          break
        case 'author':
          authorLine = value
          break
        case 'committer':
          committerLine = value
          break
        case 'gpgsig':
          var sigLines = [value]
          while (lines[0] && lines[0][0] == ' ')
            sigLines.push(lines.shift().slice(1))
          commit.gpgsig = sigLines.join('\n')
          break
        default:
          return cb(new TypeError('unknown git object property ' + prop))
      }
    }
    commit.committer = parseName(committerLine)
    if (authorLine !== committerLine) commit.author = parseName(authorLine)
    commit.body = lines.join('\n')
    cb(null, commit)
  }))
}

Git.prototype.getTag = function (obj, cb) {
  pull(this.readObject(obj), u.pullConcat(function (err, buf) {
    if (err) return cb(err)
    var tag = {
      msg: obj.msg,
    }
    var authorLine, tagterLine
    var lines = buf.toString('utf8').split('\n')
    for (var line; (line = lines.shift()); ) {
      var parts = line.split(' ')
      var prop = parts.shift()
      var value = parts.join(' ')
      switch (prop) {
        case 'object':
          tag.object = value
          break
        case 'type':
          if (!types[value])
            return cb(new TypeError('unknown git object type ' + type))
          tag.type = value
          break
        case 'tag':
          tag.tag = value
          break
        case 'tagger':
          tag.tagger = parseName(value)
          break
        default:
          return cb(new TypeError('unknown git object property ' + prop))
      }
    }
    tag.body = lines.join('\n')
    cb(null, tag)
  }))
}

function readCString(reader, cb) {
  var chars = []
  var loop = looper(function () {
    reader.read(1, next)
  })
  function next(err, ch) {
    if (err) return cb(err)
    if (ch[0] === 0) return cb(null, Buffer.concat(chars).toString('utf8'))
    chars.push(ch)
    loop()
  }
  loop()
}

Git.prototype.readTree = function (obj) {
  var self = this
  var reader = Reader()
  reader(this.readObject(obj))
  return function (abort, cb) {
    if (abort) return reader.abort(abort, cb)
    readCString(reader, function (err, str) {
      if (err) return cb(err)
      var parts = str.split(' ')
      var mode = parseInt(parts[0], 8)
      var name = parts.slice(1).join(' ')
      reader.read(20, function (err, hash) {
        if (err) return cb(err)
        cb(null, {
          name: name,
          mode: mode,
          hash: hash.toString('hex'),
          type: mode === 0040000 ? 'tree' :
                mode === 0160000 ? 'commit' : 'blob',
        })
      })
    })
  }
}

Git.prototype.readCommitChanges = function (commit) {
  var self = this
  return u.readNext(function (cb) {
    var done = multicb({pluck: 1})
    commit.parents.forEach(function (rev) {
      var cb = done()
      self.getObjectMsg({
        obj: rev,
        headMsgId: commit.msg.key,
        type: 'commit',
      }, function (err, msg) {
        if (err) return cb(err)
        self.openObject({
          obj: rev,
          msg: msg.key,
        }, function (err, obj) {
          if (err) return cb(err)
          self.getCommit(obj, cb)
        })
      })
    })
    done()(null, commit)
    done(function (err, commits) {
      if (err) return cb(err)
      var done = multicb({pluck: 1})
      commits.forEach(function (commit) {
        var cb = done()
        if (!commit.tree) return cb(null, pull.empty())
        self.getObjectMsg({
          obj: commit.tree,
          headMsgId: commit.msg.key,
          type: 'tree',
        }, function (err, msg) {
          if (err) return cb(err)
          self.openObject({
            obj: commit.tree,
            msg: commit.msg.key,
          }, cb)
        })
      })
      done(function (err, trees) {
        if (err) return cb(err)
        cb(null, self.diffTreesRecursive(trees))
      })
    })
  })
}

Git.prototype.diffTrees = function (objs) {
  var self = this
  return pull(
    kvdiff(objs.map(function (obj) {
      return self.readTree(obj)
    }), 'name'),
    pull.map(function (item) {
      var diff = item.diff || {}
      var head = item.values[item.values.length-1]
      var created = true
      for (var k = 0; k < item.values.length-1; k++)
        if (item.values[k]) created = false
      return {
        name: item.key,
        hash: diff.hash,
        mode: diff.mode,
        type: item.values.map(function (val) { return val.type }),
        deleted: !head,
        created: created
      }
    })
  )
}

Git.prototype.diffTreesRecursive = function (objs) {
  var self = this
  return pull(
    self.diffTrees(objs),
    paramap(function (item, cb) {
      if (!item.type.some(function (t) { return t === 'tree' }))
        return cb(null, [item])
      var done = multicb({pluck: 1})
      item.type.forEach(function (type, i) {
        var cb = done()
        if (type !== 'tree') return cb(null, pull.once(item))
        var hash = item.hash[i]
        self.getObjectMsg({
          obj: hash,
          headMsgId: objs[i].msg.key,
        }, function (err, msg) {
          if (err) return cb(err)
          self.openObject({
            obj: hash,
            msg: msg.key,
          }, cb)
        })
      })
      done(function (err, objs) {
        if (err) return cb(err)
        cb(null, pull(
          self.diffTreesRecursive(objs),
          pull.map(function (f) {
            f.name = item.name + '/' + f.name
            return f
          })
        ))
      })
    }, 4),
    pull.flatten()
  )
}