git ssb

0+

cel / pull-git-remote-helper



Tree: 3c171bbc3d5ef7865c87b937a3d17d5283674419

Files: 3c171bbc3d5ef7865c87b937a3d17d5283674419 / lib / pkt-line.js

2955 bytesRaw
1var buffered = require('pull-buffered')
2var util = require('./util')
3
4function rev(str) {
5 return str === '0000000000000000000000000000000000000000' ? null : str
6}
7
8// from pull-stream/source.js
9function abortCb(cb, abort, onAbort) {
10 cb(abort)
11 onAbort && onAbort(abort === true ? null: abort)
12 return
13}
14
15function pktLineEncode(read) {
16 var ended
17 return function (end, cb) {
18 if (ended) return cb(ended)
19 read(end, function (end, data) {
20 if (ended = end) {
21 cb(end)
22 } else {
23 if (data)
24 data += '\n'
25 else
26 data = ''
27 var len = data ? data.length + 4 : 0
28 var hexLen = ('000' + len.toString(16)).substr(-4)
29 var pkt = hexLen + data
30 // console.error('>', JSON.stringify(pkt))
31 cb(end, pkt)
32 }
33 })
34 }
35}
36
37function pktLineDecode(read, options) {
38 var b = buffered(read)
39 var readPrefix = b.chunks(4)
40 var ended
41
42 function readPackLine(abort, cb) {
43 if (ended) return cb(ended)
44 readPrefix(abort, function (end, buf) {
45 if (ended = end) return cb(end)
46 var len = parseInt(buf, 16)
47 if (!len)
48 return cb(null, new Buffer(''))
49 b.chunks(len - 4)(null, function (end, buf) {
50 if (ended = end) return cb(end)
51 cb(end, buf)
52 })
53 })
54 }
55
56 function readPackLineStr(abort, cb) {
57 if (ended) return cb(ended)
58 readPackLine(abort, function (end, buf) {
59 if (ended = end) return cb(end)
60 // trim newline
61 var len = buf.length
62 if (buf[len - 1] == 0xa)
63 len--
64 var line = buf.toString('ascii', 0, len)
65 cb(null, line)
66 })
67 }
68
69 function readUpdate(abort, cb) {
70 readPackLine(abort, function (end, line) {
71 if (end) return cb(end)
72 if (options.verbosity >= 2)
73 console.error('line', line.toString('ascii'))
74 if (!line.length) return cb(true)
75 var args = util.split3(line.toString('ascii'))
76 var args2 = util.split2(args[2], '\0')
77 var caps = args2[1]
78 if (caps && options.verbosity >= 2)
79 console.error('update capabilities:', caps)
80 cb(null, {
81 old: rev(args[0]),
82 new: rev(args[1]),
83 name: args2[0]
84 })
85 })
86 }
87
88 function havesWants(onEnd) {
89 return function readWant(abort, cb) {
90 readPackLineStr(abort, function (end, line) {
91 if (end) return abortCb(cb, end, onEnd)
92 if (options.verbosity >= 2)
93 console.error('line', line)
94 if (!line.length || line == 'done')
95 return abortCb(cb, true, onEnd)
96 var args = util.split3(line)
97 var caps = args[2]
98 if (caps && options.verbosity >= 2)
99 console.error('want capabilities:', caps)
100 cb(null, {
101 type: args[0],
102 hash: args[1],
103 })
104 })
105 }
106 }
107
108 b.pktLines = readPackLine
109 b.updates = readUpdate
110 b.wants = b.haves = havesWants
111
112 return b
113}
114
115exports.encode = pktLineEncode
116exports.decode = pktLineDecode
117

Built with git-ssb-web