-
Notifications
You must be signed in to change notification settings - Fork 1
/
github.js
119 lines (107 loc) · 2.82 KB
/
github.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
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
'use strict';
require('gnode');
var utils = require('../../utils');
var path = require('path');
var resolve = require('gh-resolve');
module.exports = function (name, version, cb) {
if (typeof version === 'function') {
cb = version;
version = '';
}
cb = cb || function (err, val) {
if (err) throw new Error(err);
return val;
};
// determine if this looks like a github url and
var slug = name;
if (version) {
slug += '@' + version;
}
resolve(slug, function (err, ref) {
if (err && err.message.indexOf('unable to resolve') !== -1) {
return cb();
}
if (err) return cb(err);
if (ref.type === 'tag') {
name += '#' + ref.sha;
}
if (ref.type === 'branch') {
name += '#' + ref.name;
}
try {
var url = utils.resolveGithubUri(name);
return cb(null, installer(url));
} catch (err) {
if (err.message === 'Invalid github repository') {
return cb(null, null);
}
return cb(new Error(err));
}
});
};
function installer(githubBase) {
var FetchFiles = require('fetch-files');
var writeFile = require('write');
return function (files, dest, cb) {
if (typeof dest === 'function') {
cb = dest;
dest = '';
}
if (typeof files === 'function') {
cb = files;
files = '';
dest = '';
}
files = files || 'manifest.json';
files = Array.isArray(files) ? files : [files];
var downloader = new FetchFiles({destBase: dest});
downloader.preset('github', {
url: githubBase,
fn: function (preset, config) {
var branch = utils.parseGithubUrl(preset.url).branch;
config.pathname = config.url;
config.url = path.join(branch, config.url);
return preset.url;
}
});
files.forEach(function (file) {
downloader.queue(file, {preset: 'github'});
});
downloader.fetch(function (err, res) {
if (err) return cb(err);
utils.async.map(res, function (config, next) {
if (dest) {
config.contents
.pipe(writeFile.stream(config.dest))
.on('error', next)
.on('finish', function () {
next(null, config);
});
} else {
config.contents
.pipe(writeBuffer(function (err, content) {
if (err) return next(err);
config.content = content;
next(null, config);
}))
.on('error', next);
}
}, function (err, results) {
if (err) return cb(err);
cb(null, results);
});
});
};
}
function writeBuffer(cb) {
var through = require('through2');
var buffer = '';
return through()
.on('data', function (data, next) {
buffer += data;
})
.on('error', cb)
.on('finish', function () {
return cb(null, buffer);
});
}