1 | const path = require('path');
|
2 | const fs = require('fs');
|
3 | const request = require('request');
|
4 | const zlib = require('zlib');
|
5 | const tar = require('tar');
|
6 | const home = require('user-home');
|
7 | const rimraf = require('rimraf');
|
8 | const mkdirp = require('mkdirp');
|
9 | const {
|
10 | getNpmRegistry,
|
11 | getNpmLatestSemverVersion,
|
12 | getLatestVersion,
|
13 | } = require('ice-npm-utils');
|
14 |
|
15 |
|
16 | const Parser = tar.Parse;
|
17 |
|
18 | module.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 |
|
39 |
|
40 |
|
41 | function deleteDir(destDir) {
|
42 | rimraf.sync(destDir);
|
43 | }
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 | function downloadAndFilterNpmFiles(npm, version, destDir) {
|
51 | return new Promise((resolve, reject) => {
|
52 | const taskComplete = {
|
53 |
|
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 |
|
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 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 | function getNpmVersion(npm, version) {
|
108 | if (version) {
|
109 | return getNpmLatestSemverVersion(npm, version);
|
110 | }
|
111 | return getLatestVersion(npm);
|
112 | }
|