unqommented
Version:
A Node.js utility that quickly identifies files with uncommented code in your codebase. Designed for developers who want to efficiently tell LLMs exactly which files need comments added.
59 lines (55 loc) • 2.2 kB
JavaScript
/**
* @file File system utilities
* @description Provides functions for file system operations and path handling
* @module file-utils
*/
const fs = require('fs');
const path = require('path');
const localVars = require('../config/localVars');
const { qerrors } = require('qerrors');
/**
* @function normalizePath
* @description Ensures that file paths are consistent across different operating systems.
* @rationale This function is crucial for cross-platform compatibility. It replaces both
* forward slashes and backslashes with the operating system's default separator (`path.sep`),
* preventing errors that can arise from inconsistent path formats.
* @param {string} dirPath - The file path to normalize.
* @returns {string} The normalized file path.
*/
function normalizePath(dirPath) {
return typeof dirPath === 'string'
? dirPath.replace(localVars.REGEX_PATTERNS.PATH_ALL_SLASHES, path.sep)
: dirPath;
}
/**
* @function validateDirectory
* @description Validates if a given path is a valid, existing directory.
* @rationale This is a critical prerequisite for any file system operations. It prevents
* errors and unexpected behavior by ensuring that the target directory exists and is accessible.
* @param {string} dirPath - The path to validate.
* @throws {Error} If the path is not a string, does not exist, or is not a directory.
*/
async function validateDirectory(dirPath) {
if (typeof dirPath !== 'string') {
throw new Error(localVars.ERROR_MESSAGES.BASEDIR_NOT_STRING);
}
const normalized = normalizePath(dirPath);
try {
const stats = await fs.promises.stat(normalized);
if (!stats.isDirectory()) {
throw new Error(`${localVars.ERROR_MESSAGES.PATH_NOT_DIR_PREFIX}${normalized}`);
}
} catch (error) {
// Provide a more specific error message for non-existent directories.
if (error.code === 'ENOENT') {
qerrors(error, 'validateDirectory', { dirPath: normalized });
throw new Error(`${localVars.ERROR_MESSAGES.DIR_NOT_EXIST_PREFIX}${normalized}`);
}
qerrors(error, 'validateDirectory', { dirPath: normalized });
throw error;
}
}
module.exports = {
normalizePath,
validateDirectory,
};