/
ivanby
/
Compote
Обзор
Документация
Войти
/
ivanby
/
Compote
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
1
CI/CD
Аналитика
Безопасность
master
yaga/insert.js
244 строки
9 KB
Иван Быков
Initial commit
19 июн 2026, 08:50
19 июн 2026, 08:50
b4391e5
Код
Авторство
О чём код?
/* */ const toolName = 'insert -> '; //*** начало общий код для всех утилит 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); } //*** конец общий код для всех утилит // собственно код insert.js // проверяем yagaConfig.insert if( !yagaConfig.insert || !yagaConfig.insert.filter || !Array.isArray(yagaConfig.insert.filter) || !yagaConfig.insert.ignore || !Array.isArray(yagaConfig.insert.ignore) ) { console.log(toolName + '\x1b[31mПродолжение невозможно: в ' + yagaConfigYamlPath + ' неккоректно настроен ключ insert\x1b[0m'); process.exit(1); } 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.insert.filter) { try { cndf = (new RegExp(ref)).test(absPath); if(cndf) break; } catch (err) { console.log(toolName + '\x1b[31mПродолжение невозможно: в ' + yagaConfigYamlPath + ' неккоректно настроен ключ insert.filter\x1b[0m'); process.exit(1); } } if(cndf) { let cndi; for(let rei of yagaConfig.insert.ignore) { try { cndi = (new RegExp(rei)).test(absPath); if(cndi) break; } catch (err) { console.log(toolName + '\x1b[31mПродолжение невозможно: в ' + yagaConfigYamlPath + ' неккоректно настроен ключ insert.ignore\x1b[0m'); process.exit(1); } } if(!cndi) srcFiles.push(absPath); } } }); } scanDir(targetDirPath); //console.log(srcFiles); /* quot = ", apos = ', grave = ` */ let insertCache = []; const insertCmdRe = /#?\/\*\*@insert\s+([^\s]+?)(\s+(--quot|--apos|--grave))?\s*\*\//gmi; let insertNoti = toolName + 'Выполняю вставки в ./' + yagaConfig.target_dir + ': '; process.stdout.write(insertNoti); 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; srcText = srcText.replace(insertCmdRe, function(match, p1, p2, p3) { modi = true; // рзбираем p1 if(p1[0] === '.' && p1[1] === '/' ) // это путь относительно текущего srcFile p1 = path.join(path.dirname(srcFile), p1.slice(2)); else if(p1[0] === '.' && p1[1] === '.' && p1[2] === '/' ) // это путь относительно родителя текущего srcFile p1 = path.join(path.dirname(path.dirname(srcFile)), p1.slice(3)); else if(p1[0] === '/' && p1[1] === '/') // это путь относительно projectDir p1 = path.join(projectDir, p1.slice(2)); else if(p1[0] !== '/') // это путь относительно targetDirPath p1 = path.join(targetDirPath, p1); // дефолт -- это абсолютный путь -- '/' if(srcFile === p1) { console.log(); console.log(toolName + '\x1b[31mПродолжение невозможно: попытка перекресной вставки в ' + p1 + '\x1b[0m'); console.log(toolName + '\x1b[31mиз ' + srcFile + '\x1b[0m'); process.exit(1); } let keyCache = p1 + (p3 || ''); let findItmC = insertCache.find(itm=> itm.k === keyCache); if(findItmC) return findItmC.v; let val = ''; try { val = fs.readFileSync( p1 , 'utf8'); } catch (err) { console.log(); console.log(toolName + '\x1b[31mПродолжение невозможно: не могу прочитать ' + p1 + '\x1b[0m'); console.log(toolName + '\x1b[31mв ' + srcFile + '\x1b[0m'); process.exit(1); } if(p3) switch (p3) { case '--grave': val = val.replaceAll("`", "\\`"); break; case '--quot': val = val.replaceAll('"', '\\"'); break; case '--apos': val = val.replaceAll("'", "\\'"); } insertCache.push({k: keyCache, p: p1, v: val}); process.stdout.write('\b'); process.stdout.write(indicator()); return val; }); 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(); // удаляем отработанные файлы // только те, что находятся в targetDirPath insertCache.forEach(itm=>{ if(!itm.p.startsWith(targetDirPath)) return; try { if(fs.existsSync(itm.p)) fs.unlinkSync(itm.p); } catch (err) { console.log(toolName + '\x1b[31mПродолжение невозможно: не могу удалить ' + itm.p + '\x1b[0m'); console.log(err); process.exit(1); } }); process.stdout.write('\b'); process.stdout.write('\x1b[32mготово\x1b[0m'); console.log();