UNPKG

1.17 kBJavaScriptView Raw
1const jsonfile = require('jsonfile');
2const path = require('path');
3
4function scriptAlreadyExists(name) {
5 this.name = 'scriptAlreadyExists';
6 this.message = `${name} is already present in the package.json file.`;
7}
8
9scriptAlreadyExists.prototype = new Error();
10scriptAlreadyExists.prototype.constructor = scriptAlreadyExists;
11
12function NoPackageJsonExists() {
13 this.name = 'NoPackageJsonExists';
14 this.message = 'No package.json present';
15}
16
17NoPackageJsonExists.prototype = new Error();
18NoPackageJsonExists.prototype.constructor = NoPackageJsonExists;
19
20const packageJsonFilePath = path.resolve('package.json');
21
22try {
23 const key = process.argv[2];
24 const value = process.argv[3];
25 const packageJson = jsonfile.readFileSync(packageJsonFilePath);
26 if (!packageJson.scripts) packageJson.scripts = {};
27 if (packageJson.scripts[key]) {
28 console.error('cuketractor script already exists');
29 }
30 packageJson.scripts[key] = value;
31 jsonfile.writeFileSync(packageJsonFilePath, packageJson, { spaces: 2 });
32} catch (e) {
33 if (e.message === 'ENOENT, no such file or directory \'package.json\'') {
34 throw new NoPackageJsonExists();
35 } else {
36 throw e;
37 }
38}