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
|
#!/usr/bin/env node
var DHT = require('bittorrent-dht')
var exec = require('child_process').exec
var fs = require('fs')
var magnet = require('magnet-uri')
var spawn = require('child_process').spawn
var Swarm = require('bittorrent-swarm')
var ut_gitswarm = require('ut_gitswarm')
var WebTorrent = require('webtorrent')
// We use console.warn (stderr) because git ignores our writes to stdout.
var url = process.argv[3].replace(/^gitswarm:/i, 'git:')
function die (error) {
console.error(error)
process.exit(1)
}
exec('git ls-remote ' + url + ' HEAD', function (err, stdout, stderr) {
var targetdir = process.env['GIT_DIR']
if (err !== null) {
die(err)
}
var lines = stdout.split('\n')
if (lines.length !== 2) {
die("Didn't get back a single HEAD ref: " + lines)
}
var line = lines[0].split('\t')
var ref = line[0]
var head = line[1]
if (head !== 'HEAD') {
die("Couldn't parse the ref line: " + ref, head)
}
if (ref.length !== 40) {
die('Was expecting a 40-byte sha: ' + ref)
}
console.warn('Okay, we want to get: ' + ref)
process.stdin.setEncoding('utf8');
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk === 'capabilities\n') {
process.stdout.write('fetch\n\n')
}
if (chunk === 'list\n') {
process.stdout.write(ref + ' refs/heads/master\n\n')
}
})
process.stdout.on('error', function () {
// stdout was closed
})
var dht = new DHT({
bootstrap: ['three.printf.net:6882']
})
var magnetUri = 'magnet:?xt=urn:btih:' + ref
var parsed = magnet(magnetUri)
dht.on('ready', function () {
dht.lookup(parsed.infoHash)
})
dht.on('peer', function (addr, hash, from) {
swarm.addPeer(addr)
})
var swarm = new Swarm(parsed.infoHash, 'cafebabecafebabecafecafebabecafebabecafe')
swarm.on('wire', function (wire) {
wire.use(ut_gitswarm())
wire.ut_gitswarm.on('handshake', function () {
wire.ut_gitswarm.ask(parsed.infoHash)
})
wire.ut_gitswarm.on('receivedTorrent', function (infoHash) {
var client = new WebTorrent({
dht: {
bootstrap: ['three.printf.net:6882']
},
tracker: false
})
client.download(infoHash, function (torrent) {
torrent.on('done', function (done) {
var filename = torrent.storage.path + '/' + torrent.files[0].path
var unpack = spawn('git', ['index-pack', '--stdin', '-v', '--fix-thin'])
var stream = fs.createReadStream(filename)
stream.on('open', function () {
stream.pipe(unpack.stdin)
})
unpack.on('exit', function (code) {
var stream = fs.createWriteStream(targetdir + '/refs/heads/master')
stream.once('open', function (fd) {
stream.write(ref + '\n')
stream.end()
// These writes are actually necessary for git to finish checkout.
process.stdout.write('\n\n')
process.exit()
})
})
})
})
})
})
})
|