1 | const jsonfile = require('jsonfile');
|
2 | const path = require('path');
|
3 |
|
4 | function scriptAlreadyExists(name) {
|
5 | this.name = 'scriptAlreadyExists';
|
6 | this.message = `${name} is already present in the package.json file.`;
|
7 | }
|
8 |
|
9 | scriptAlreadyExists.prototype = new Error();
|
10 | scriptAlreadyExists.prototype.constructor = scriptAlreadyExists;
|
11 |
|
12 | function NoPackageJsonExists() {
|
13 | this.name = 'NoPackageJsonExists';
|
14 | this.message = 'No package.json present';
|
15 | }
|
16 |
|
17 | NoPackageJsonExists.prototype = new Error();
|
18 | NoPackageJsonExists.prototype.constructor = NoPackageJsonExists;
|
19 |
|
20 | const packageJsonFilePath = path.resolve('package.json');
|
21 |
|
22 | try {
|
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 | }
|