UNPKG

can-algorithm

Version:

Cortex Algorithm Numeral - Intelligent development automation tool

110 lines (85 loc) 3.04 kB
const fs = require('fs').promises; const path = require('path'); const crypto = require('crypto'); async function backupFile(filePath) { const backupDir = path.join(process.cwd(), '.can', 'backups'); await fs.mkdir(backupDir, { recursive: true }); const timestamp = new Date().getTime(); const backupName = `${path.basename(filePath)}.${timestamp}.backup`; const backupPath = path.join(backupDir, backupName); await fs.copyFile(filePath, backupPath); return backupPath; } async function safeWriteFile(filePath, content) { const tempPath = `${filePath}.tmp`; await fs.writeFile(tempPath, content); try { await fs.access(filePath); await backupFile(filePath); } catch {} await fs.rename(tempPath, filePath); } async function findFiles(pattern, startDir = process.cwd()) { const results = []; async function search(dir) { const entries = await fs.readdir(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); if (entry.name === 'node_modules' || entry.name === '.git') continue; if (entry.isDirectory()) { await search(fullPath); } else if (entry.name.match(pattern)) { results.push(fullPath); } } } await search(startDir); return results; } async function getFileHash(filePath) { const content = await fs.readFile(filePath); return crypto.createHash('sha256').update(content).digest('hex'); } async function compareFiles(file1, file2) { const hash1 = await getFileHash(file1); const hash2 = await getFileHash(file2); return hash1 === hash2; } async function createDirectory(dirPath) { await fs.mkdir(dirPath, { recursive: true }); } async function removeDirectory(dirPath) { const entries = await fs.readdir(dirPath, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dirPath, entry.name); if (entry.isDirectory()) { await removeDirectory(fullPath); } else { await fs.unlink(fullPath); } } await fs.rmdir(dirPath); } async function copyDirectory(src, dest) { await createDirectory(dest); const entries = await fs.readdir(src, { withFileTypes: true }); for (const entry of entries) { const srcPath = path.join(src, entry.name); const destPath = path.join(dest, entry.name); if (entry.isDirectory()) { await copyDirectory(srcPath, destPath); } else { await fs.copyFile(srcPath, destPath); } } } module.exports = { backupFile, safeWriteFile, findFiles, getFileHash, compareFiles, createDirectory, removeDirectory, copyDirectory };