All files / cli/src/utils files.js

100% Statements 12/12
87.5% Branches 7/8
100% Functions 4/4
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32                                  44x 107x 43x 2x 1x       43x 107x 107x   107x    
/**
 * File-writing helpers shared by the generators.
 */
 
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { dirname, relative } from 'path';
 
/**
 * Write generated files, refusing to overwrite anything unless `force` is
 * set. Every target is checked before the first write, so a refusal leaves
 * the project untouched.
 *
 * @param {Array<{ path: string, content: string }>} files - Absolute paths and contents.
 * @param {{ force?: boolean }} [options]
 * @returns {string[]} The paths written.
 */
export function writeGeneratedFiles(files, { force = false } = {}) {
  if (!force) {
    const existing = files.filter((file) => existsSync(file.path));
    if (existing.length > 0) {
      const list = existing.map((file) => relative(process.cwd(), file.path) || file.path).join(', ');
      throw new Error(`Refusing to overwrite existing file(s): ${list}. Re-run with --force to overwrite.`);
    }
  }
 
  for (const file of files) {
    mkdirSync(dirname(file.path), { recursive: true });
    writeFileSync(file.path, file.content);
  }
  return files.map((file) => file.path);
}