forked from alibaba/ice
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdownload.js
More file actions
108 lines (94 loc) · 2.57 KB
/
download.js
File metadata and controls
108 lines (94 loc) · 2.57 KB
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
'use strict';
const path = require('path');
const fs = require('fs');
const request = require('request');
const zlib = require('zlib');
const tar = require('tar');
const home = require('user-home');
const rimraf = require('rimraf');
const mkdirp = require('mkdirp');
const npmUtils = require('./npm');
const os = require('os');
module.exports = (options = {}) => {
const template = options.template;
const templateTmpDirPath = path.join(home, '.ice-templates', template);
let templateVersion = '';
return getNpmVersion(template, options.version).then(function(npmVersion) {
templateVersion = npmVersion;
deleteDir(templateTmpDirPath);
return downloadAndFilterNpmFiles(
template,
templateVersion,
templateTmpDirPath
);
});
};
/**
* delete dir
* @param {String} destDir
*/
function deleteDir(destDir) {
rimraf.sync(destDir);
}
/**
* download and filter npm files
*
* @param {Object} options npm, version, destDir
*/
function downloadAndFilterNpmFiles(npm, version, destDir) {
return new Promise(function(resolve, reject) {
const taskComplete = {
// foo: false
};
function end() {
const isDone = Object.values(taskComplete).every((done) => done === true);
if (isDone) {
resolve();
}
}
const npmTarball = `https://registry.npmjs.org/${npm}/-/${npm}-${version}.tgz`;
taskComplete.entryPipe = false;
request
.get(npmTarball)
.on('error', function(err) {
reject(err);
})
.pipe(zlib.Unzip())
.pipe(tar.Parse())
.on('entry', function(entry) {
const templatePathReg = new RegExp(`(package\/template\/)`);
let realPath;
let destPath;
if (templatePathReg.test(entry.path)) {
realPath = entry.path.replace(templatePathReg, '');
destPath = path.join(destDir, 'template', realPath);
} else {
realPath = entry.path.replace('package/', '');
destPath = path.join(destDir, realPath);
}
mkdirp.sync(path.dirname(destPath));
taskComplete[destPath] = false;
entry.pipe(fs.createWriteStream(destPath)).on('close', () => {
taskComplete[destPath] = true;
end();
});
})
.on('end', function() {
taskComplete.entryPipe = true;
end();
});
});
}
/**
* get template version
*
* @param {String} npm
* @param {String} version
*/
function getNpmVersion(npm, version) {
if (version) {
return npmUtils.getNpmLatestSemverVersion(npm, version);
} else {
return npmUtils.getLatestVersion(npm);
}
}