-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
74 lines (56 loc) · 2.41 KB
/
index.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
const fs = require('fs');
const path = require('path');
const packlist = require('npm-packlist');
const archiver = require('archiver-promise');
const sanitizeFilename = require('sanitize-filename');
function interpolate (str, map) {
if (!str) return;
return str.replace(/\${([^}]+)}/g, (_, prop) => map[prop]);
}
async function pack (source, destination, name, ignore) {
const filePath = path.join(destination, `${name}.zip`);
if (!fs.existsSync(destination)) fs.mkdirSync(destination);
if (fs.existsSync(filePath)) fs.rmSync(filePath);// archiver doesn't work if same name file exists.
const files = await packlist({ path: source });
const archive = archiver(filePath);
files.filter(function (file) {
return !file.match(ignore);
}).forEach(function (file) {
archive.file(path.join(source, file), { name: file });
});
return archive.finalize();
}
module.exports = function (name, devDeps, destination) {
const ROOT_DIR = process.cwd();
const TEMP_DIR = path.join(ROOT_DIR, '.npm-zip-tmp');
const PACKAGE_JSON_PATH = path.join(ROOT_DIR, 'package.json');
const packageJson = require(PACKAGE_JSON_PATH);
name = interpolate(name, {
name: packageJson.name,
version: packageJson.version,
timestamp: Date.now()
});
name = sanitizeFilename(name || packageJson.name);
destination = destination ? path.join(ROOT_DIR, destination) : ROOT_DIR;
if (!fs.existsSync(TEMP_DIR)) fs.mkdirSync(TEMP_DIR);
console.info('Backing up `package.json`...');
fs.copyFileSync(PACKAGE_JSON_PATH, path.join(TEMP_DIR, 'package.json'));
console.info('Backup completed');
// add `bundledDependencies` to package.json to let packlist includes it
packageJson.bundledDependencies = Object.keys(packageJson.dependencies);
if (devDeps) {
packageJson.bundledDependencies.concat(Object.keys(packageJson.devDependencies));
}
fs.writeFileSync(PACKAGE_JSON_PATH, JSON.stringify(packageJson, null, 4));
console.info(`Packing dependencies: ${packageJson.bundledDependencies.join(', ')}`);
return pack(ROOT_DIR, destination, name, '.npm-zip-tmp/').then(function () {
console.info('Finished packing');
console.info('Restoring backed up file(s)...');
const sourceFile = path.join(TEMP_DIR, 'package.json');
if (fs.existsSync(sourceFile)) {
fs.renameSync(sourceFile, PACKAGE_JSON_PATH);
}
fs.rmSync(TEMP_DIR, { recursive: true });
console.info('Restored');
});
};