All files / bin utils.js

73.42% Statements 210/286
79.59% Branches 39/49
88.88% Functions 8/9
73.42% Lines 210/286

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 42x 42x     42x 42x 42x 42x 42x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 154x 154x 154x 154x 154x 154x 154x 154x 6x 6x 37x 37x 37x 154x 36x 36x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 148x 111x 111x 154x 256x 256x 256x 256x 256x 256x 256x 256x 256x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x       2x       2x 2x 2x 2x 2x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 258x 258x 258x 258x 258x 6x 6x 6x 6x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 34x 6x 6x 34x 4x   252x 252x 498x 498x 4x 4x 494x 494x 494x 2x 2x 498x 246x 246x 246x 258x 256x 256x 256x 256x 256x 256x 2x 2x 2x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 30x 30x 28x 28x 2x 2x 2x 2x 2x 2x 30x 256x 256x 256x 256x 256x 256x 256x 256x 256x 3x 3x 3x           3x 256x 256x 256x 256x 256x 256x 256x 256x                                                                                                                          
import fs from 'fs';
import path from 'path';
import readline from 'node:readline';
import { execSync } from 'child_process';
import { red, yellow, gray } from './colors.js';
 
/**
 * Helper to parse input names into PascalCase and kebab-case.
 * Supports camelCase, kebab-case, snake_case, and PascalCase.
 * @param {string} inputName - The input name from CLI.
 * @returns {{capitalizedName: string, folderFileName: string}}
 */
export function parseName(inputName) {
  let processedName = inputName;
  if (inputName === inputName.toUpperCase() && inputName !== inputName.toLowerCase()) {
    processedName = inputName.toLowerCase();
  }
  const parts = processedName.split(/(?<=[a-z0-9])(?=[A-Z])|[-_]/).filter(Boolean);
  const capitalizedName = parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('');
  const folderFileName = parts.map((part) => part.toLowerCase()).join('-');
  return { capitalizedName, folderFileName };
}
 
/**
 * Checks if git status is clean or prompts user if there are unstaged changes.
 *
 * Scoped to the project directory rather than to whatever the shell's working
 * directory happens to be: the guard exists to protect the files the command
 * is about to write, and those live under the project root. Reading
 * `process.cwd()` instead meant a command run from a subdirectory reported the
 * status of an unrelated enclosing repository.
 *
 * Git's own stderr is discarded. Outside a repository git writes
 * `fatal: not a git repository` to stderr, which `execSync` forwards to the
 * parent by default -- so every `avenx init` in a plain directory printed a
 * fatal-looking line above its own output while in fact succeeding.
 * @param {string} [cwd] - The project root to inspect. Defaults to the process's directory.
 * @returns {boolean|Promise<boolean>} True to proceed, false when the user declined.
 */
export function checkGitStatus(cwd = process.cwd()) {
  try {
    const output = execSync('git status --porcelain', {
      cwd,
      encoding: 'utf8',
      stdio: ['ignore', 'pipe', 'ignore'],
    });
 
    if (!output.trim()) {
      return true;
    }
 
    console.warn(yellow('⚠️ You have unstaged changes in your repository.'));
 
    if (!process.stdin.isTTY || !process.stdout.isTTY) {
      return true;
    }
 
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });
 
    return new Promise((resolve) => {
      rl.question('Do you want to proceed? (y/N) ', (answer) => {
        rl.close();
 
        if (answer.trim().toLowerCase() === 'y') {
          resolve(true);
        } else {
          console.log(gray('Operation cancelled.'));
          resolve(false);
        }
      });
    });
  } catch {
    return true;
  }
}
 
/**
 * Prompts the user with a question on the command line.
 * @param {string} query - The question query.
 * @param {string} [defaultValue] - The default response.
 * @param {function(string): (boolean|string)} [validator] - Optional function validating input.
 * @returns {Promise<string>}
 */
export function promptQuestion(query, defaultValue, validator = null) {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
 
  return new Promise((resolve) => {
    const ask = () => {
      rl.question(query, (answer) => {
        let trimmed = answer.trim();
        if (trimmed === '' && defaultValue !== undefined) {
          trimmed = defaultValue;
        }
        if (validator) {
          const valid = validator(trimmed);
          if (valid === true) {
            rl.close();
            resolve(trimmed);
          } else {
            console.log(red(`❌ ${valid}`));
            ask();
          }
        } else {
          rl.close();
          resolve(trimmed);
        }
      });
    };
    ask();
  });
}
 
/**
 * Reads a template, checking custom template overrides in templatesDir and templates/ folder first.
 * @param {string} baseDir
 * @param {object} config
 * @param {string} frameworkDir
 * @param {string} subfolder
 * @param {string} filename
 * @param {string|null} [templateName]
 * @returns {string}
 */
export function readTemplate(baseDir, config, frameworkDir, subfolder, filename, templateName = null) {
  const dirs = [config?.templatesDir || '.avenxtemplates', 'templates'].filter(
    (dir, idx, self) => dir && self.indexOf(dir) === idx
  );
 
  if (templateName) {
    const ext = path.extname(filename);
    const basename = filename.replace(/\.template$/, '');
 
    for (const dir of dirs) {
      const candidatePaths = [
        path.join(baseDir, dir, subfolder, templateName, filename),
        path.join(baseDir, dir, subfolder, `${templateName}.${filename}`),
        path.join(baseDir, dir, subfolder, `${basename}.${templateName}.template`),
        path.join(baseDir, dir, templateName, filename),
        path.join(baseDir, dir, `${templateName}.${filename}`),
        path.join(baseDir, dir, `${templateName}.${subfolder}${ext}.template`),
        path.join(baseDir, dir, `${templateName}${ext}.template`),
      ];
 
      for (const candidatePath of candidatePaths) {
        if (fs.existsSync(candidatePath)) {
          return fs.readFileSync(candidatePath, 'utf-8');
        }
      }
    }
  }
 
  for (const dir of dirs) {
    const localStructuredPath = path.join(baseDir, dir, subfolder, filename);
    if (fs.existsSync(localStructuredPath)) {
      return fs.readFileSync(localStructuredPath, 'utf-8');
    }
 
    const localFlatPath = path.join(baseDir, dir, filename);
    if (fs.existsSync(localFlatPath)) {
      return fs.readFileSync(localFlatPath, 'utf-8');
    }
  }
 
  const globalPath = path.join(frameworkDir, 'templates', subfolder, filename);
  return fs.readFileSync(globalPath, 'utf-8');
}
 
/**
 * Reports a CLI error and marks the process as failed.
 * @param {string} message
 */
export function fail(message) {
  console.error(red(`❌ Error: ${message}`));
  process.exitCode = 1;
}
 
/**
 * Stops generation if any target path already exists.
 * @param {string} baseDir
 * @param {string} type
 * @param {string} name
 * @param {string[]} targetPaths
 * @returns {boolean}
 */
export function abortIfGeneratedPathExists(baseDir, type, name, targetPaths) {
  const existingPath = targetPaths.find((targetPath) => fs.existsSync(targetPath));
  if (!existingPath) {
    return false;
  }
 
  fail(
    `${type} '${name}' already exists at ${path.relative(baseDir, existingPath)}. ` +
      'Remove the existing file or choose a different name.',
  );
  return true;
}
 
/**
 * Cross-platform directory watcher with recursive support fallback.
 * Node 18 on Linux does not support fs.watch(dir, { recursive: true }).
 * @param {string} dirPath - Directory to watch.
 * @param {Function} callback - Event callback (eventType, filename).
 * @returns {{close: Function}|object} FSWatcher or compatible watcher object with close() method.
 */
export function watchDirectory(dirPath, callback) {
  try {
    return fs.watch(dirPath, { recursive: true }, callback);
  } catch (err) {
    if (err && err.code === 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM') {
      return createRecursiveWatcherFallback(dirPath, callback);
    }
    throw err;
  }
}
 
/**
 * Fallback recursive watcher for platforms/Node versions lacking native recursive watch.
 * Walks directory tree and registers individual fs.watch instances.
 * @param {string} rootPath - Root directory to watch.
 * @param {Function} callback - Event callback.
 * @returns {{close: Function}}
 */
function createRecursiveWatcherFallback(rootPath, callback) {
  const watchers = new Map();

  function scanAndWatch(currentDir) {
    if (!fs.existsSync(currentDir)) return;

    if (!watchers.has(currentDir)) {
      try {
        const watcher = fs.watch(currentDir, (eventType, filename) => {
          const relativeDir = path.relative(rootPath, currentDir);
          const relativeFile = filename
            ? (relativeDir ? path.join(relativeDir, filename) : filename).replace(/\\/g, '/')
            : (relativeDir ? relativeDir.replace(/\\/g, '/') : '');

          const fullPath = filename ? path.join(currentDir, filename) : currentDir;
          try {
            if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
              scanAndWatch(fullPath);
            }
          } catch {
            // Ignore stat errors on deleted / inaccessible entries
          }

          callback(eventType, relativeFile);
        });

        watchers.set(currentDir, watcher);
      } catch {
        // Ignore watch errors on transient dirs or permission errors
      }
    }

    try {
      const entries = fs.readdirSync(currentDir, { withFileTypes: true });
      for (const entry of entries) {
        if (entry.isDirectory()) {
          scanAndWatch(path.join(currentDir, entry.name));
        }
      }
    } catch {
      // Ignore read errors on inaccessible dirs
    }
  }

  scanAndWatch(rootPath);

  return {
    close() {
      for (const watcher of watchers.values()) {
        try {
          watcher.close();
        } catch {
          // Ignore close errors
        }
      }
      watchers.clear();
    },
  };
}