import fs from 'node:fs' import path from 'node:path' import { PlataDirs, PlataFiles } from '../../libs/tools' export namespace tools { export namespace files { export async function mkdirIfNotExists(dir: string) { try { const p = path.resolve(dir) if (!fs.existsSync(p)) { fs.mkdirSync(p, { recursive: true }) } } catch (err) { console.error(err) process.exit(1) } } export async function copyFileIfNotExists(source: string, destination: string) { try { const s = path.resolve(source) const d = path.resolve(destination) if (!fs.existsSync(d)) { fs.copyFileSync(s, d) } } catch (err) { console.error(err) process.exit(1) } } export async function copyFileToProject(projectFolder: string, templateFile: string, fileName: string): Promise { const s = path.resolve(PlataDirs.getPlataTempleteDir('create-cli', `${templateFile}.ts`)) let d = path.resolve(Plata.ProjectDir, projectFolder) await mkdirIfNotExists(d) d = path.join(d, fileName) await copyFileIfNotExists(s, d) return d } export async function deployFileToProject(projectFolder: string, templateFile: string, fileName: string, args: any) { const fileInProject = await copyFileToProject(projectFolder, templateFile, fileName) const content: any = await PlataFiles.readFileSync(fileInProject, (line) => { if (line === '//@ts-nocheck') { return '' } if (line === '') { return '' } // Procura por texto para subistituir esse texto que esta no formato ç__PARAMETRO__ç let lastIndex = 0 while(lastIndex !== -1) { lastIndex = line.indexOf('$__', lastIndex) if (lastIndex !== -1) { const pIndex = line.indexOf('__$', lastIndex) const param = line.slice(lastIndex + 3, pIndex) line = line.replace(new RegExp(`\\$__${param}__\\$`, 'g'), args[param]) } } return line }) if (content.err !== undefined) { console.log(content.err) process.exit(1) } else { fs.writeFileSync(fileInProject, content) } } } export namespace args { export type argsCallBack = (command: string, args: string[]) => Promise export async function forEachArg(callback: argsCallBack) { let args = process.argv.slice(process.argv.indexOf('--') + 1) while(args.length !== 0) { const command = args.shift() if (command !== undefined) { args = await callback(command, args) } } } } }