All files / src/install-from-boilerplate add-gitignore-entries.js

0% Statements 0/23
0% Branches 0/4
0% Functions 0/5
0% Lines 0/22

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 52 53 54 55 56 57 58 59                                                                                                                     
const fs = require('node:fs').promises;
const Logger = require('../utils/logger');
 
/**
 * Reads the content of a file or returns an empty string if the file does not exist.
 * @param {string} filePath - The path to the file.
 * @returns {Promise<string>} - The content of the file or an empty string.
 */
async function readFileOrCreateEmpty(filePath) {
    try {
        return await fs.readFile(filePath, 'utf8');
    } catch (error) {
        if (error.code === 'ENOENT') {
            return '';
        }
        throw error;
    }
}
 
/**
 * Updates the .gitignore file with the specified files.
 * @param {string} gitignorePath - The path to the .gitignore file.
 * @param {string[]} filesToAdd - The list of files to add to .gitignore.
 */
async function updateGitignore(gitignorePath, filesToAdd) {
    try {
        // Read the .gitignore file or create an empty one if it doesn't exist
        let gitignoreContent = await readFileOrCreateEmpty(gitignorePath);
 
        // Split the content into lines and remove empty lines
        const gitignoreLines = gitignoreContent.split('\n').filter(line => line.trim() !== '');
 
        // Add files to .gitignore if they are not already present.
        // Strip inline comments from existing lines before comparing, so that
        // entries like "*.lnk  # some comment" are not duplicated.
        filesToAdd.forEach(file => {
            const pattern = file.trim();
            const alreadyPresent = gitignoreLines.some(line => {
                const linePattern = line.trim().split('#')[0].trim();
                return linePattern === pattern;
            });
            if (!alreadyPresent) {
                gitignoreLines.push(pattern);
            }
        });
 
        // Join the lines back into a single string
        const updatedGitignoreContent = gitignoreLines.join('\n') + '\n';
 
        // Write the updated content back to the .gitignore file
        await fs.writeFile(gitignorePath, updatedGitignoreContent, 'utf8');
 
        Logger.success('Updated .gitignore file');
    } catch (error) {
        Logger.error('Error updating .gitignore:', error.message);
    }
}
 
module.exports = { updateGitignore};