UNPKG

@tokens-studio/sdk

Version:
85 lines 3.28 kB
import path from 'node:path'; import fs from 'node:fs/promises'; import chalk from 'chalk'; import { prompt } from '../utils/prompt.js'; export async function writeFilesToFs(files, args, config) { const folderPath = path.resolve(args['--config'] ?? '', config.output ?? ''); let yesToAll = !!process.env.CI; // in CI we always want to override const writeFileToFs = async (file) => { const filePath = `${path.resolve(folderPath, file.filename.replace(/\//g, path.sep))}`; const dirPath = path.dirname(filePath); try { await fs.lstat(dirPath); } catch (_err) { await fs.mkdir(dirPath, { recursive: true }); } let fileExists = false; try { const stats = await fs.lstat(filePath); if (stats) fileExists = true; } catch (_e) { // } let shouldWrite = true; if (fileExists && !yesToAll) { const { overwriteFile } = await prompt([ { name: 'overwriteFile', type: 'select', label: '', message: `File ${chalk.cyanBright(filePath)} already exists, do you want to overwrite it?`, choices: [ { value: 'all', label: 'Yes to all', }, { value: 'yes', label: 'Yes', }, { value: 'no', label: 'No', }, ], initial: 'all', }, ], {}, { name: 'overwriteFile', value: 'all' }); if (overwriteFile === 'all') { yesToAll = true; } // We only test prompt's fallback /* v8 ignore next 3 */ if (overwriteFile === 'no' || overwriteFile === 'yes') { shouldWrite = false; } } if (shouldWrite) { await fs.writeFile(filePath, file.contents); } }; // This could be done in parallel but due to the synchronous nature of prompts // this is a rather big pain in the butt to parallelize because you have to file up a queuing/interrupt system.. // so not really worth it for the code complexity // If needed, we can break out of the for loop if the user hits "Yes to all" // and parallelize the remaining files if performance is an issue. let filesDoneIndex = 0; for (const file of files) { await writeFileToFs(file); filesDoneIndex++; if (yesToAll) { // we can now parallelize the remaining files break; } } if (filesDoneIndex !== files.length && yesToAll) { await Promise.all(files.slice(filesDoneIndex).map(writeFileToFs)); // we still have some remaining files but we can parallize them } // eslint-disable-next-line no-console console.log(`\nSuccessfully pulled files into ${chalk.cyan(folderPath)}`); } //# sourceMappingURL=write-sets-to-fs.js.map