UNPKG

devghost

Version:

👻 Find dead code, dead imports, and dead dependencies before they haunt your project

223 lines • 7.37 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.findProjectRoot = findProjectRoot; exports.getAllFiles = getAllFiles; exports.readPackageJson = readPackageJson; exports.getFileStats = getFileStats; exports.getDirectorySize = getDirectorySize; exports.hasIgnoreComment = hasIgnoreComment; exports.isFileIgnored = isFileIgnored; exports.removeLineFromFile = removeLineFromFile; exports.matchesIgnorePattern = matchesIgnorePattern; const fs = __importStar(require("node:fs")); const path = __importStar(require("node:path")); const glob_1 = require("glob"); /** * Find the project root by looking for package.json */ function findProjectRoot(startDir = process.cwd()) { let currentDir = startDir; while (currentDir !== path.parse(currentDir).root) { const packageJsonPath = path.join(currentDir, 'package.json'); if (fs.existsSync(packageJsonPath)) { return currentDir; } currentDir = path.dirname(currentDir); } return null; } /** * Get all TypeScript/JavaScript files in a directory recursively */ async function getAllFiles(dir, extensions = ['.ts', '.tsx', '.js', '.jsx']) { const patterns = extensions.map((ext) => `**/*${ext}`); const files = []; for (const pattern of patterns) { const matches = await (0, glob_1.glob)(pattern, { cwd: dir, absolute: true, ignore: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/.next/**'], }); files.push(...matches); } return [...new Set(files)]; // Remove duplicates } /** * Read and parse package.json */ function readPackageJson(projectRoot) { const packageJsonPath = path.join(projectRoot, 'package.json'); if (!fs.existsSync(packageJsonPath)) { return null; } try { const content = fs.readFileSync(packageJsonPath, 'utf-8'); return JSON.parse(content); } catch (error) { console.error('Error reading package.json:', error); return null; } } /** * Get file statistics (size and line count) */ function getFileStats(filePath) { try { const content = fs.readFileSync(filePath, 'utf-8'); const stats = fs.statSync(filePath); return { size: stats.size, lines: content.split('\n').length, }; } catch (_error) { return { size: 0, lines: 0 }; } } /** * Calculate the total size of a directory (used for node_modules) */ function getDirectorySize(dirPath) { if (!fs.existsSync(dirPath)) { return 0; } let totalSize = 0; try { const files = fs.readdirSync(dirPath); for (const file of files) { const filePath = path.join(dirPath, file); const stats = fs.statSync(filePath); if (stats.isDirectory()) { totalSize += getDirectorySize(filePath); } else { totalSize += stats.size; } } } catch (_error) { // Permission errors or other issues return 0; } return totalSize; } /** * Check if a file has a devghost-ignore comment * @param fileContent - The file content as a string * @param line - 1-indexed line number (line 1 = first line) */ function hasIgnoreComment(fileContent, line) { const lines = fileContent.split('\n'); // Convert 1-indexed to 0-indexed for array access const lineIndex = line - 1; // Check the line before if (lineIndex > 0) { const previousLine = lines[lineIndex - 1]; if (previousLine?.includes('devghost-ignore-next-line')) { return true; } } // Check if entire file is ignored if (lines[0]?.includes('devghost-ignore-file')) { return true; } return false; } /** * Check if entire file should be ignored */ function isFileIgnored(filePath) { try { const content = fs.readFileSync(filePath, 'utf-8'); const firstLine = content.split('\n')[0]; return firstLine.includes('devghost-ignore-file'); } catch (_error) { return false; } } /** * Remove a specific line from a file (for auto-fix) */ function removeLineFromFile(filePath, lineNumber) { try { const content = fs.readFileSync(filePath, 'utf-8'); const lines = content.split('\n'); if (lineNumber < 0 || lineNumber >= lines.length) { return false; } lines.splice(lineNumber, 1); fs.writeFileSync(filePath, lines.join('\n'), 'utf-8'); return true; } catch (error) { console.error(`Error removing line from ${filePath}:`, error); return false; } } /** * Check if a file matches ignore patterns */ function matchesIgnorePattern(filePath, patterns) { const normalizedPath = filePath.replace(/\\/g, '/'); for (const pattern of patterns) { const normalizedPattern = pattern.replace(/\\/g, '/'); // Handle '**/dir/**' pattern – match any path containing '/dir/' if (normalizedPattern.startsWith('**/') && normalizedPattern.endsWith('/**')) { const segment = normalizedPattern.slice(3, -3); // remove leading '**/' and trailing '/**' if (normalizedPath.includes(`/${segment}/`)) { return true; } continue; } // Handle '**/dir' pattern – match any path ending with '/dir' if (normalizedPattern.startsWith('**/')) { const segment = normalizedPattern.slice(3); if (normalizedPath.endsWith(`/${segment}`) || normalizedPath.includes(`/${segment}/`)) { return true; } continue; } // Simple substring or exact match if (normalizedPath.includes(normalizedPattern.replace('**/', '')) || normalizedPath.endsWith(normalizedPattern)) { return true; } } return false; } //# sourceMappingURL=fs.js.map