-
Notifications
You must be signed in to change notification settings - Fork 234
/
utils.js
111 lines (99 loc) · 2.45 KB
/
utils.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
import fs from 'fs';
import path from 'path';
import https from 'https';
import child_process from 'child_process';
import { rimrafSync, copydirSync } from 'sander';
const tmpDirName = 'tmp';
const degitConfigName = 'degit.json';
export { degitConfigName };
export class DegitError extends Error {
constructor(message, opts) {
super(message);
Object.assign(this, opts);
}
}
export function tryRequire(file, opts) {
try {
if (opts && opts.clearCache === true) {
delete require.cache[require.resolve(file)];
}
return require(file);
} catch (err) {
return null;
}
}
export function exec(command) {
return new Promise((fulfil, reject) => {
child_process.exec(command, (err, stdout, stderr) => {
if (err) {
reject(err);
return;
}
fulfil({ stdout, stderr });
});
});
}
export function mkdirp(dir) {
const parent = path.dirname(dir);
if (parent === dir) return;
mkdirp(parent);
try {
fs.mkdirSync(dir);
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
}
export function fetch(url, dest) {
return new Promise((fulfil, reject) => {
https
.get(url, response => {
const code = response.statusCode;
if (code >= 400) {
reject({ code, message: response.statusMessage });
} else if (code >= 300) {
fetch(response.headers.location, dest).then(fulfil, reject);
} else {
response
.pipe(fs.createWriteStream(dest))
.on('finish', () => fulfil())
.on('error', reject);
}
})
.on('error', reject);
});
}
export function stashFiles(dir, dest) {
const tmpDir = path.join(dir, tmpDirName);
rimrafSync(tmpDir);
mkdirp(tmpDir);
fs.readdirSync(dest).forEach(file => {
const filePath = path.join(dest, file);
const targetPath = path.join(tmpDir, file);
const isDir = fs.lstatSync(filePath).isDirectory();
if (isDir) {
copydirSync(filePath).to(targetPath);
rimrafSync(filePath);
} else {
fs.copyFileSync(filePath, targetPath);
fs.unlinkSync(filePath);
}
});
}
export function unstashFiles(dir, dest) {
const tmpDir = path.join(dir, tmpDirName);
fs.readdirSync(tmpDir).forEach(filename => {
const tmpFile = path.join(tmpDir, filename);
const targetPath = path.join(dest, filename);
const isDir = fs.lstatSync(tmpFile).isDirectory();
if (isDir) {
copydirSync(tmpFile).to(targetPath);
rimrafSync(tmpFile);
} else {
if (filename !== 'degit.json') {
fs.copyFileSync(tmpFile, targetPath);
}
fs.unlinkSync(tmpFile);
}
});
rimrafSync(tmpDir);
}