diff --git a/cleaner.js b/cleaner.js
index 78dc0ce..07cc10b 100644
--- a/cleaner.js
+++ b/cleaner.js
@@ -1,74 +1,54 @@
-// cleaner.js — Node.js модуль для безопасной очистки комментариев
-const strip = require('strip-comments');
+const strip = require('strip-comments');
const fs = require('fs');
const path = require('path');
-
const SUPPORTED = ['.js', '.css', '.ejs'];
-// Очистка контента по расширению
function cleanContent(content, ext) {
if (!SUPPORTED.includes(ext)) return content;
- // EJS: удаляем только <%# комментарии %>, остальное — strip-comments
if (ext === '.ejs') content = content.replace(/<%#.*?%>/gs, '');
return strip(content, { preserveNewlines: true });
}
-// Обработать один файл
function processFile(inputPath, outputPath = null) {
const ext = path.extname(inputPath).toLowerCase();
if (!SUPPORTED.includes(ext)) return { skipped: inputPath };
-
const content = fs.readFileSync(inputPath, 'utf8');
const cleaned = cleanContent(content, ext);
const target = outputPath || inputPath;
-
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, cleaned, 'utf8');
return { ok: inputPath };
}
-// Обработать папку рекурсивно
function processDirectory(inputDir, outputDir = null) {
const results = { processed: [], skipped: [], errors: [] };
-
function walk(dir, outBase) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const inPath = path.join(dir, entry.name);
const outPath = outBase ? path.join(outBase, path.relative(inputDir, inPath)) : null;
-
if (entry.isDirectory()) {
walk(inPath, outBase ? path.dirname(outPath) : null);
} else {
const ext = path.extname(entry.name).toLowerCase();
if (SUPPORTED.includes(ext)) {
- try {
- processFile(inPath, outPath);
- results.processed.push(entry.name);
- } catch (e) {
- results.errors.push(`${entry.name}: ${e.message}`);
- }
- } else {
- results.skipped.push(entry.name);
- }
+ try { processFile(inPath, outPath); results.processed.push(entry.name); }
+ catch (e) { results.errors.push(`${entry.name}: ${e.message}`); }
+ } else { results.skipped.push(entry.name); }
}
}
}
-
walk(inputDir, outputDir);
return results;
}
-// CLI режим
if (require.main === module) {
const [,, cmd, input, output] = process.argv;
-
if (cmd === 'file' && input) {
const res = processFile(input, output || null);
if (res.ok) console.log(`[OK] ${path.basename(input)}`);
else if (res.skipped) console.log(`[SKIP] ${path.basename(input)}`);
process.exit(0);
}
-
if (cmd === 'dir' && input) {
const res = processDirectory(input, output || null);
console.log(`✅ Обработано: ${res.processed.length}`);
@@ -76,11 +56,7 @@ if (require.main === module) {
if (res.errors.length) console.error(`❌ Ошибки: ${res.errors.join(', ')}`);
process.exit(res.errors.length ? 1 : 0);
}
-
- console.log('Использование:');
- console.log(' node cleaner.js file [output]');
- console.log(' node cleaner.js dir [outputDir]');
+ console.log('Использование:\n node cleaner.js file [output]\n node cleaner.js dir [outputDir]');
process.exit(1);
}
-
-module.exports = { cleanContent, processFile, processDirectory, SUPPORTED };
\ No newline at end of file
+module.exports = { cleanContent, processFile, processDirectory, SUPPORTED };
diff --git a/launcher.ps1 b/launcher.ps1
index d6108c4..420b463 100644
--- a/launcher.ps1
+++ b/launcher.ps1
@@ -1,8 +1,8 @@
-# ==============================================================================
-# LAUNCHER.PS1 - Обработка файлов для Node.js (Windows)
+# ==============================================================================
+# LAUNCHER.PS1 - Обработка файлов для Node.js (Windows PowerShell)
# Использует: Node.js + strip-comments для безопасной очистки
# Поддерживает: .js, .css, .ejs
-# ВАЖНО: Сохраняйте в UTF-8 with BOM
+# ВАЖНО: Файл создан с кодировкой UTF-8 BOM
# ==============================================================================
# --- Настройка путей ---
@@ -23,8 +23,9 @@ $C_GREEN = [ConsoleColor]::Green; $C_RED = [ConsoleColor]::Red
$C_WHITE = [ConsoleColor]::White; $C_GRAY = [ConsoleColor]::DarkGray
$C_MAGENTA = [ConsoleColor]::Magenta
-function Write-Color { param([string]$Text, $Color = $C_WHITE)
- Write-Host $Text -ForegroundColor $Color
+function Write-Color {
+ param([string]$Text, $Color = $C_WHITE)
+ Write-Host $Text -ForegroundColor $Color
}
# --- Проверка зависимостей ---
@@ -63,11 +64,11 @@ function Clean-AllComments {
$result = & node $CleanerScript dir $InputDirectory 2>&1 | Out-String
Write-Host $result
- Write-Color "✅ Очистка завершена" $C_GREEN
+ Write-Color "[OK] Очистка завершена" $C_GREEN
Write-Host ""
}
-# --- Конвертация в .txt (только поддерживаемые расширения) ---
+# --- Конвертация в .txt ---
function Convert-ToTxt {
Write-Color "=== КОНВЕРТАЦИЯ В .TXT ===" $C_CYAN; Write-Host ""
if (-not (Test-Path $InputDirectory)) { Write-Color "[ERR] Папка не найдена" $C_RED; return }
@@ -83,7 +84,6 @@ function Convert-ToTxt {
$Count++
} catch { Write-Color "[ERR] $($_.Name)" $C_RED }
}
-
Write-Color "Конвертировано: $Count" $C_WHITE; Write-Host ""
}
@@ -98,16 +98,21 @@ function Combine-Files {
Write-Color "Найдено: $($TxtFiles.Count)" $C_WHITE; Write-Host ""
if (-not (Test-Path $OutputDirectory)) { New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null }
- $Header = @("ОБЪЕДИНЁННЫЙ ФАЙЛ (Node.js)", "Создан: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')",
- "Источник: $InputDirectory", "Файлов: $($TxtFiles.Count)",
- "Комментарии: $(if ($Global:RemoveComments) { 'УДАЛЕНЫ' } else { 'ОСТАВЛЕНЫ' })", "")
+ $Header = @(
+ "ОБЪЕДИНЁННЫЙ ФАЙЛ (Node.js)",
+ "Создан: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')",
+ "Источник: $InputDirectory",
+ "Файлов: $($TxtFiles.Count)",
+ "Комментарии: $(if ($Global:RemoveComments) { 'УДАЛЕНЫ' } else { 'ОСТАВЛЕНЫ' })",
+ ""
+ )
$Header | Set-Content -Path $CombinedFile -Encoding UTF8
foreach ($File in $TxtFiles | Sort-Object FullName) {
try {
- "=" * 80 | Add-Content -Path $CombinedFile -Encoding UTF8
+ ("=" * 80) | Add-Content -Path $CombinedFile -Encoding UTF8
"ФАЙЛ: $($File.FullName)" | Add-Content -Path $CombinedFile -Encoding UTF8
- "=" * 80 | Add-Content -Path $CombinedFile -Encoding UTF8
+ ("=" * 80) | Add-Content -Path $CombinedFile -Encoding UTF8
$Content = Get-Content -Path $File.FullName -Encoding UTF8 | Where-Object { $_ -match '\S' }
if ($Content) { $Content | Add-Content -Path $CombinedFile -Encoding UTF8 }
"" | Add-Content -Path $CombinedFile -Encoding UTF8
@@ -122,26 +127,40 @@ function Combine-Files {
Write-Host ""
}
-# --- Остальные функции (меню, настройки) ---
+# --- Переключить очистку ---
function Toggle-Comments {
Write-Color "=== НАСТРОЙКА ===" $C_CYAN; Write-Host ""
$Global:RemoveComments = -not $Global:RemoveComments
- Write-Color "Очистка: $(if ($Global:RemoveComments) { 'ВКЛ' } else { 'ВЫКЛ' })" $(if ($Global:RemoveComments) { $C_GREEN } else { $C_YELLOW })
+ $Status = if ($Global:RemoveComments) { "ВКЛ" } else { "ВЫКЛ" }
+ $Color = if ($Global:RemoveComments) { $C_GREEN } else { $C_YELLOW }
+ Write-Color "Очистка комментариев: $Status" $Color
Write-Host ""
}
+# --- Сброс проекта ---
function Clean-All {
Write-Color "=== СБРОС ПРОЕКТА ===" $C_RED; Write-Host ""
- if (Test-Path $DevDirectory) { Remove-Item -Path $DevDirectory -Recurse -Force; Write-Color "[OK] !DEV удалена" $C_GREEN }
- Setup-Folders; Write-Color "[OK] Структура восстановлена" $C_GREEN; Write-Host ""
-}
-
-function Open-Folder {
- if (Test-Path $DevDirectory) { Start-Process "explorer.exe" $DevDirectory; Write-Color "[OK] Открыта !DEV" $C_GREEN }
- else { Write-Color "[ERR] !DEV не найдена" $C_RED }
+ if (Test-Path $DevDirectory) {
+ Remove-Item -Path $DevDirectory -Recurse -Force
+ Write-Color "[OK] !DEV удалена" $C_GREEN
+ }
+ Setup-Folders
+ Write-Color "[OK] Структура восстановлена" $C_GREEN
Write-Host ""
}
+# --- Открыть папку ---
+function Open-Folder {
+ if (Test-Path $DevDirectory) {
+ Start-Process "explorer.exe" $DevDirectory
+ Write-Color "[OK] Открыта !DEV" $C_GREEN
+ } else {
+ Write-Color "[ERR] !DEV не найдена" $C_RED
+ }
+ Write-Host ""
+}
+
+# --- Показать структуру ---
function Show-Structure {
Write-Color "=== СТРУКТУРА ===" $C_CYAN; Write-Host ""
Write-Color "Корень: $ScriptDirectory" $C_WHITE
@@ -153,15 +172,20 @@ function Show-Structure {
Write-Color " output/ ($Out файлов)" $C_GREEN
}
Write-Color "Поддержка: $($SupportedExts -join ', ')" $C_CYAN
- Write-Color "Очистка: $(if ($Global:RemoveComments) { 'ВКЛ' } else { 'ВЫКЛ' })" $(if ($Global:RemoveComments) { $C_GREEN } else { $C_RED })
+ $Status = if ($Global:RemoveComments) { "ВКЛ" } else { "ВЫКЛ" }
+ $Color = if ($Global:RemoveComments) { $C_GREEN } else { $C_RED }
+ Write-Color "Очистка: $Status" $Color
Write-Host ""
}
-function Show-Header { Clear-Host
+# --- Заголовок и меню ---
+function Show-Header {
+ Clear-Host
Write-Color "==================================================" $C_CYAN
Write-Color " ОБРАБОТКА ФАЙЛОВ (Node.js + PowerShell)" $C_CYAN
Write-Color "==================================================" $C_CYAN
- Write-Color "Скрипт: $ScriptDirectory\launcher.ps1" $C_GRAY; Write-Host ""
+ Write-Color "Скрипт: $ScriptDirectory\launcher.ps1" $C_GRAY
+ Write-Host ""
}
function Show-Menu {
@@ -169,15 +193,18 @@ function Show-Menu {
Write-Color "1. [ОЧИСТКА] Удалить комментарии (.js/.css/.ejs)" $C_MAGENTA
Write-Color "2. [КОНВЕРТ] Конвертировать в .txt" $C_CYAN
Write-Color "3. [ОБЪЕДИН] Объединить .txt в один файл" $C_CYAN
- Write-Color "4. [ВСЁ] Очистка → Конвертация → Объединение" $C_GREEN
- Write-Color "5. [НАСТР] Переключить очистку $(if ($Global:RemoveComments) { '[ВКЛ]' } else { '[ВЫКЛ]' })" $C_WHITE
+ Write-Color "4. [ВСЁ] Очистка -> Конвертация -> Объединение" $C_GREEN
+ Write-Color "5. [НАСТР] Очистка $(if ($Global:RemoveComments) { '[ВКЛ]' } else { '[ВЫКЛ]' })" $C_WHITE
Write-Color "6. [ПАПКА] Открыть !DEV" $C_MAGENTA
Write-Color "7. [ИНФО] Показать структуру" $C_WHITE
Write-Color "8. [СБРОС] Полная очистка" $C_RED
- Write-Color "0. [ВЫХОД] Завершить" $C_RED; Write-Host ""
+ Write-Color "0. [ВЫХОД] Завершить" $C_RED
+ Write-Host ""
}
-function Wait-ForUser { Write-Host ""; Write-Color "Нажмите любую клавишу..." $C_GRAY
+function Wait-ForUser {
+ Write-Host ""
+ Write-Color "Нажмите любую клавишу..." $C_GRAY
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
@@ -187,9 +214,11 @@ function Wait-ForUser { Write-Host ""; Write-Color "Нажмите любую к
Setup-Folders
do {
- Show-Header; Show-Menu
+ Show-Header
+ Show-Menu
$Choice = Read-Host "Выберите (0-8)"
Write-Host ""
+
switch ($Choice) {
"1" { Clean-AllComments; Wait-ForUser }
"2" { Convert-ToTxt; Wait-ForUser }