UNPKG

2.69 kBJavaScriptView Raw
1const path = require('path');
2const fs = require('fs');
3const request = require('request');
4const zlib = require('zlib');
5const tar = require('tar');
6const home = require('user-home');
7const rimraf = require('rimraf');
8const mkdirp = require('mkdirp');
9const {
10 getNpmRegistry,
11 getNpmLatestSemverVersion,
12 getLatestVersion,
13} = require('ice-npm-utils');
14
15
16const Parser = tar.Parse;
17
18module.exports = (options = {}) => {
19 const template = options.template;
20
21 const templateTmpDirPath = path.join(home, '.ice-templates', template);
22
23 let templateVersion = '';
24 return getNpmVersion(template, options.version).then((npmVersion) => {
25 templateVersion = npmVersion;
26
27 deleteDir(templateTmpDirPath);
28
29 return downloadAndFilterNpmFiles(
30 template,
31 templateVersion,
32 templateTmpDirPath
33 );
34 });
35};
36
37/**
38 * delete dir
39 * @param {String} destDir
40 */
41function deleteDir(destDir) {
42 rimraf.sync(destDir);
43}
44
45/**
46 * download and filter npm files
47 *
48 * @param {Object} options npm, version, destDir
49 */
50function downloadAndFilterNpmFiles(npm, version, destDir) {
51 return new Promise((resolve, reject) => {
52 const taskComplete = {
53 // foo: false
54 };
55 function end() {
56 const isDone = Object.values(taskComplete).every((done) => done === true);
57
58 if (isDone) {
59 resolve();
60 }
61 }
62
63 const npmTarball = `${getNpmRegistry(npm)}/${npm}/-/${npm}-${version}.tgz`;
64 taskComplete.entryPipe = false;
65 request
66 .get(npmTarball)
67 .on('error', (err) => {
68 reject(err);
69 })
70 .pipe(zlib.createGunzip())
71 .pipe(new Parser())
72 .on('entry', (entry) => {
73 /* eslint-disable-next-line no-useless-escape */
74 const templatePathReg = new RegExp('(package\/template\/)');
75
76 let realPath;
77 let destPath;
78
79 if (templatePathReg.test(entry.path)) {
80 realPath = entry.path.replace(templatePathReg, '');
81 destPath = path.join(destDir, 'template', realPath);
82 } else {
83 realPath = entry.path.replace('package/', '');
84 destPath = path.join(destDir, realPath);
85 }
86
87 mkdirp.sync(path.dirname(destPath));
88 taskComplete[destPath] = false;
89 entry.pipe(fs.createWriteStream(destPath)).on('close', () => {
90 taskComplete[destPath] = true;
91 end();
92 });
93 })
94 .on('end', () => {
95 taskComplete.entryPipe = true;
96 end();
97 });
98 });
99}
100
101/**
102 * get template version
103 *
104 * @param {String} npm
105 * @param {String} version
106 */
107function getNpmVersion(npm, version) {
108 if (version) {
109 return getNpmLatestSemverVersion(npm, version);
110 }
111 return getLatestVersion(npm);
112}