/
ivanby
/
Compote
Обзор
Документация
Войти
/
ivanby
/
Compote
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
1
CI/CD
Аналитика
Безопасность
master
yaga/replace.js
208 строк
7 KB
Иван Быков
Initial commit
19 июн 2026, 08:50
19 июн 2026, 08:50
b4391e5
Код
Авторство
О чём код?
#!/usr/bin/env node /* jshint evil: true */ /* */ const toolName = 'replace -> '; //*** начало общий код для всех утилит const fs = require('node:fs'); const path = require('node:path'); const process = require('node:process'); const yaml = require('yaml'); let indicatorCurPos = 0; function indicator() { const indicatorChars = ['|', '/', '–', '\\']; if(indicatorCurPos < indicatorChars.length) indicatorCurPos++; if(indicatorCurPos >= indicatorChars.length) indicatorCurPos = 0; return indicatorChars[indicatorCurPos]; } const projectDir = process.cwd(); // доступен ли yaga.config.yaml const yagaConfigYamlPath = path.join( projectDir, 'yaga.config.yaml'); if (!fs.existsSync(yagaConfigYamlPath)) { console.log(toolName + '\x1b[31mПродолжение невозможно: отсутсвует yaga.config.yaml - ' + yagaConfigYamlPath + '\x1b[0m'); process.exit(1); } // читаем yaga.config.yaml let yagaConfigYaml = ''; try { yagaConfigYaml = fs.readFileSync( yagaConfigYamlPath , 'utf8'); } catch (err) { console.log(toolName + '\x1b[31mПродолжение невозможно: не могу прочитать yaga.config.yaml - ' + yagaConfigYamlPath + '\x1b[0m'); process.exit(1); } // парсим yaga.config.yaml let yagaConfig = ''; try { yagaConfig = yaml.parse(yagaConfigYaml); } catch (err) { console.log(toolName + '\x1b[31mПродолжение невозможно: не могу разобрать yaga.config.yaml - ' + yagaConfigYamlPath + '\x1b[0m'); console.log(err); process.exit(1); } // проверяем yagaConfig.target_dir if(!yagaConfig.target_dir || typeof yagaConfig.target_dir != 'string') { console.log(toolName + '\x1b[31mПродолжение невозможно: неверно указана целевая директория yagaConfig.target_dir - ' + yagaConfig.target_dir + '\x1b[0m'); process.exit(1); } const targetDirPath = path.join(projectDir, yagaConfig.target_dir); // проверяем yagaConfig.target_dir if(!fs.existsSync(targetDirPath)) { console.log(toolName + '\x1b[31mПродолжение невозможно: отсутсвует целевая директория yagaConfig.target_dir - ' + targetDirPath + '\x1b[0m'); process.exit(1); } //*** конец общий код для всех утилит // собственно код replace.js // проверяем yagaConfig.replace if( !yagaConfig.replace || !yagaConfig.replace.filter || !Array.isArray(yagaConfig.replace.filter) || !yagaConfig.replace.ignore || !Array.isArray(yagaConfig.replace.ignore) ) { console.log(toolName + '\x1b[31mПродолжение невозможно: в ' + yagaConfigYamlPath + ' неккоректно настроен ключ replace\x1b[0m'); process.exit(1); } let replaceGlobal; if( yagaConfig.replace.global && Array.isArray(yagaConfig.replace.global) && yagaConfig.replace.global.length ) replaceGlobal = yagaConfig.replace.global; let srcFiles = []; function scanDir(dir) { fs.readdirSync(dir).forEach(file => { const absPath = path.join(dir, file); if (fs.statSync(absPath).isDirectory()) return scanDir(absPath); else { let cndf; for(let ref of yagaConfig.replace.filter) { try { cndf = (new RegExp(ref)).test(absPath); if(cndf) break; } catch (err) { console.log(toolName + '\x1b[31mПродолжение невозможно: в ' + yagaConfigYamlPath + ' неккоректно настроен ключ replace.filter\x1b[0m'); process.exit(1); } } if(cndf) { let cndi; for(let rei of yagaConfig.replace.ignore) { try { cndi = (new RegExp(rei)).test(absPath); if(cndi) break; } catch (err) { console.log(toolName + '\x1b[31mПродолжение невозможно: в ' + yagaConfigYamlPath + ' неккоректно настроен ключ replace.ignore\x1b[0m'); process.exit(1); } } if(!cndi) srcFiles.push(absPath); } } }); } scanDir(targetDirPath); const replaceCmdRe = /#?\/\*\*@replace\s+([\s\S]+?)\*\//gm; let replaceNoti = toolName + 'Выполняю замены в ./' + yagaConfig.target_dir + ': '; process.stdout.write(replaceNoti); const handFiles = ()=>{ for( let srcFile of srcFiles) { let srcText = ''; try { srcText = fs.readFileSync( srcFile , 'utf8'); } catch (err) { console.log(); console.log(toolName + '\x1b[31mПродолжение невозможно: не могу прочитать ' + srcFile + '\x1b[0m'); console.log(err); process.exit(1); } let modi = false; if( replaceGlobal && typeof replaceGlobal === 'object' && !Array.isArray(replaceGlobal) ) { for (const [key, val] of Object.entries(replaceGlobal)) { srcText = srcText.replaceAll(key, val); process.stdout.write('\b'); process.stdout.write(indicator()); } } let replaces = []; srcText = srcText.replace(replaceCmdRe, function(match, p1) { modi = true; try { const fn = new Function('return {' + p1 + '};'); for (const [key, val] of Object.entries(fn())) replaces.push({k: key, v: val}); } catch (err) { console.error(`${toolName}\x1b[31mПродолжение невозможно: ошибка в директиве ${match} в файле ${srcFile}\x1b[0m`); console.log(err); process.exit(1); } process.stdout.write('\b'); process.stdout.write(indicator()); return ''; }); if(replaces.length) { modi = true; for( let itm of replaces) { srcText = srcText.replaceAll(itm.k, itm.v); process.stdout.write('\b'); process.stdout.write(indicator()); } } if(modi) try { fs.writeFileSync( srcFile , srcText, 'utf8'); handFiles(); break; } catch (err) { console.log(); console.log(toolName + '\x1b[31mПродолжение невозможно: не могу записать ' + srcFile + '\x1b[0m'); console.log(err); process.exit(1); } } }; handFiles(); process.stdout.write('\b'); process.stdout.write('\x1b[32mготово\x1b[0m'); console.log();