UNPKG

kist

Version:

Lightweight Package Pipeline Processor with Plugin Architecture

60 lines 2.31 kB
import fs from "fs"; import micromatch from "micromatch"; import path from "path"; import { Action } from "../../core/pipeline/Action.js"; export class DirectoryCleanAction extends Action { async execute(options) { const dirPath = options.dirPath; const keepPatterns = options.keep; if (!dirPath) { throw new Error("Missing required option: dirPath."); } if (!fs.existsSync(dirPath)) { this.logWarn(`Directory does not exist, skipping: ${dirPath}`); return; } this.logInfo(`Cleaning directory: ${dirPath}`); try { await this.cleanDirectoryContents(dirPath, keepPatterns); this.logInfo(`Directory cleaned successfully: ${dirPath}`); } catch (error) { this.logError(`Error cleaning directory "${dirPath}":`, error); } } async cleanDirectoryContents(dirPath, keepPatterns) { const files = await fs.promises.readdir(dirPath); for (const file of files) { const curPath = path.join(dirPath, file); const relativePath = path.relative(dirPath, curPath); if (keepPatterns && micromatch.isMatch(relativePath, keepPatterns)) { this.logInfo(`Skipping: ${relativePath}`); continue; } try { const stat = await fs.promises.lstat(curPath); if (stat.isDirectory()) { await fs.promises.rm(curPath, { recursive: true }); this.logInfo(`Deleted directory: ${relativePath}`); } else { await fs.promises.unlink(curPath); this.logInfo(`Deleted file: ${relativePath}`); } } catch (error) { this.logError(`Error deleting: ${relativePath}`, error); } } } describe() { const description = ` Cleans a directory by deleting all its contents while retaining files and directories matching specified glob patterns. If the directory does not exist, the action will skip gracefully. `; return description; } } //# sourceMappingURL=DirectoryCleanAction.js.map