README.md 추가 및 CLI 도구에 대한 사용법 설명: 파일 이름 변환기 기능 구현, 디렉토리 목록 가져오기 기능 추가

This commit is contained in:
2024-12-17 02:57:18 +09:00
parent 2794eb1c45
commit 7afcf19178
7 changed files with 188 additions and 1342 deletions

117
normalize.js Normal file → Executable file
View File

@@ -1,14 +1,57 @@
#!/usr/bin/env node
const fs = require("fs").promises;
const path = require("path");
const chokidar = require("chokidar");
const minimist = require("minimist");
// 무시할 파일/디렉토리를 결정하는 함수
// Parse command-line arguments
const args = minimist(process.argv.slice(2), {
alias: { d: 'directory', f: 'file', v: 'verbose', h: 'help' }
});
// Function to display help message
function displayHelp() {
console.log(`
Usage: node index.js [options]
Options:
-d, --directory Specify a directory to process
-f, --file Specify a file to process
-v, --verbose Enable verbose logging
-h, --help Display this help message
`);
}
// Check for help flag or no arguments
if (args.help || (!args.directory && !args.file)) {
displayHelp();
process.exit(0);
}
// Main processing logic
async function processPath(targetPath) {
if (!targetPath) {
console.error("Please provide a path using -d or -f");
process.exit(1);
}
try {
const stats = await fs.lstat(targetPath);
if (stats.isDirectory()) {
await processDirectory(targetPath);
} else if (stats.isFile()) {
await normalizeFileName(targetPath);
}
} catch (error) {
console.error(`Error processing path "${targetPath}":`, error);
}
}
// Function to determine if a file/directory should be ignored
function shouldIgnore(itemName) {
const ignoredItems = [".git", "node_modules", ".env"];
return ignoredItems.includes(itemName);
}
// 파일 이름을 정규화하는 함수
// Function to normalize file names
async function normalizeFileName(filePath) {
const dir = path.dirname(filePath);
const oldName = path.basename(filePath);
@@ -18,21 +61,25 @@ async function normalizeFileName(filePath) {
const newPath = path.join(dir, newName);
try {
await fs.rename(filePath, newPath);
if (args.verbose) {
console.log(`Renamed: "${oldName}" -> "${newName}"`);
}
return newPath;
} catch (error) {
console.error(`이름 변경 실패 ("${oldName}"):`, error);
console.error(`Failed to rename "${oldName}":`, error);
return filePath;
}
}
return filePath;
}
// 디렉토리를 재귀적으로 처리하는 함수
// Function to process directories recursively
async function processDirectory(dirPath) {
// console.log(`디렉토리 처리 시작: "${dirPath}"`);
if (args.verbose) {
console.log(`Processing directory: "${dirPath}"`);
}
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
@@ -46,55 +93,13 @@ async function processDirectory(dirPath) {
}
await normalizeFileName(dirPath);
} catch (error) {
console.error(`디렉토리 처리 중 오류 발생 ("${dirPath}"):`, error);
console.error(`Error processing directory "${dirPath}":`, error);
}
}
// 디렉토리를 감시하는 함수
function watchDirectory(directory) {
const watcher = chokidar.watch(directory, {
ignored: (pathStr) => {
const baseName = path.basename(pathStr);
return shouldIgnore(baseName);
},
persistent: true,
ignoreInitial: false, // 초기 파일 추가 이벤트를 감지
awaitWriteFinish: {
stabilityThreshold: 200, // 파일이 완전히 작성될 때까지 대기 (ms)
pollInterval: 100,
},
depth: Infinity, // 하위 디렉토리까지 감시
});
watcher
.on("add", async (filePath) => {
// console.log(`파일 추가됨: "${filePath}"`);
await normalizeFileName(filePath);
})
.on("change", async (filePath) => {
// console.log(`파일 변경됨: "${filePath}"`);
await normalizeFileName(filePath);
})
.on("unlink", (filePath) => {
// console.log(`파일 삭제됨: "${filePath}"`);
})
.on("addDir", async (dirPath) => {
// console.log(`디렉토리 추가됨: "${dirPath}"`);
await processDirectory(dirPath); // 새 디렉토리를 추가되자마자 처리
})
.on("unlinkDir", (dirPath) => {
// console.log(`디렉토리 삭제됨: "${dirPath}"`);
})
.on("error", (error) => console.error(`Watcher error: ${error}`))
.on("ready", () => {
console.log("초기 스캔 완료. 변경 감시 중...");
});
console.log(`감시 시작: "${directory}"`);
}
// 명령줄 인자로 경로를 받거나 기본값 사용
const targetPath = process.argv[2] || "./convert";
// 디렉토리 감시 시작
watchDirectory(targetPath);
// Process the given path based on arguments
if (args.directory) {
processPath(args.directory);
} else if (args.file) {
processPath(args.file);
}