-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (42 loc) · 1.33 KB
/
index.js
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
var hyperquest = require('hyperquest')
var through = require('through2')
var assert = require('assert')
function archiveStream (opts) {
if (typeof opts === 'string') {
opts = { repo: opts }
}
var repo = opts.repo
assert.strictEqual(typeof repo, 'string', '.repo required')
var format = opts.format || 'tarball'
var ref = opts.ref || 'master'
var url = [ 'https://api.github.com/repos', repo, format, ref ].join('/')
var options = {
headers: {
'User-Agent': 'github-archive-stream'
}
}
if (opts.auth) {
assert.strictEqual(typeof opts.auth.user, 'string', '.user required')
assert.strictEqual(typeof opts.auth.token, 'string', '.token required')
options.auth = opts.auth.user + ':' + opts.auth.token
}
var pass = through()
var req = hyperquest.get(url, options)
req.on('response', function (res) {
var redirect = isRedirect(req.request, res)
if (typeof redirect !== 'string') {
return pass.emit('error', new Error(
'Expected redirect url. Error code: ' + res.statusCode
))
}
hyperquest.get(redirect, options).pipe(pass)
})
return pass
}
function isRedirect (req, res) {
var codes = [ 301, 302, 307, 308 ]
return (req.method === 'GET' &&
codes.indexOf(res.statusCode) !== -1 &&
res.headers.location)
}
module.exports = archiveStream