All files / src/install-from-boilerplate add-scripts-keys.js

77.77% Statements 14/18
55.55% Branches 5/9
100% Functions 1/1
77.77% Lines 14/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 522x 2x 2x                 1x   1x         1x 1x   1x       1x 14x 14x       1x 1x           2x                          
const fs = require('node:fs');
const path = require('node:path');
const Logger = require('../utils/logger');
 
/**
 * Adds scripts to the package.json file.
 *
 * @param {Object} scriptKeys - An object containing the scripts to add.
 * @param {Object} [overwriteKeys={}] - An object specifying which scripts to overwrite if they already exist.
 */
function addScriptsKeys(scriptKeys, overwriteKeys = {}) {
    const packageJsonPath = path.resolve(process.cwd(), 'package.json');
 
    Iif (!fs.existsSync(packageJsonPath)) {
        Logger.error('Error reading package.json: file not found');
        return;
    }
 
    try {
        const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
 
        Iif (!packageJson.scripts) {
            packageJson.scripts = {};
        }
 
        for (const [key, value] of Object.entries(scriptKeys)) {
            Eif (!packageJson.scripts[key] || overwriteKeys[key]) {
                packageJson.scripts[key] = value;
            }
        }
 
        fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n', 'utf8');
        Logger.success('Scripts added to package.json successfully!');
    } catch (error) {
        Logger.error('Error updating package.json:', error);
    }
}
 
module.exports = addScriptsKeys;
 
/*
 
// Example usage:
const configScriptsKeys = {  ...  };
const overwriteConfig = { "edit": true }; // Overwrite only "edit" script
 
addScriptsKeys(configScriptsKeys); // Do not overwrite any existing scripts
 
addScriptsKeys(configScriptsKeys, overwriteConfig);  // Overwrite specified existing scripts
 
*/