All files / cli Runner.ts

97.72% Statements 43/44
96.55% Branches 28/29
100% Functions 5/5
97.72% Lines 43/44

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                                                                    13x 13x 13x         13x                             13x 10x   10x 10x             13x 13x   13x 14x 14x   14x 2x   12x       13x               13x 13x   1x 1x     12x 1x 1x     11x                   11x 6x       5x   11x         11x 2x       3x 3x 1x     1x 1x   2x                                 10x         8x     2x 2x 1x 1x            
/**
 * Runner
 * Executes the transpiler with the given configuration
 */
 
import { dirname, resolve } from "node:path";
import { existsSync, statSync, renameSync } from "node:fs";
import InputExpansion from "../transpiler/data/InputExpansion";
import Transpiler from "../transpiler/Transpiler";
import ICliConfig from "./types/ICliConfig";
import ResultPrinter from "./ResultPrinter";
import ITranspilerResult from "../transpiler/types/ITranspilerResult";
 
/** Result of categorizing inputs into directories and files */
interface ICategorizedInputs {
  srcDirs: string[];
  explicitFiles: string[];
}
 
/** Result of determining output path */
interface IOutputPathResult {
  outDir: string;
  explicitOutputFile: string | null;
}
 
/**
 * Execute the transpiler
 */
class Runner {
  /**
   * Execute the transpiler with the given configuration
   * @param config - CLI configuration
   */
  static async execute(config: ICliConfig): Promise<void> {
    const { srcDirs, explicitFiles } = this._categorizeInputs(config.inputs);
    const files = this._expandInputFiles(config.inputs);
    const { outDir, explicitOutputFile } = this._determineOutputPath(
      config,
      files,
    );
 
    const pipeline = new Transpiler({
      inputs: [...srcDirs, ...explicitFiles],
      includeDirs: config.includeDirs,
      outDir,
      headerOutDir: config.headerOutDir,
      basePath: config.basePath,
      preprocess: config.preprocess,
      defines: config.defines,
      cppRequired: config.cppRequired,
      noCache: config.noCache,
      parseOnly: config.parseOnly,
      target: config.target,
      debugMode: config.debugMode,
    });
 
    const result = await pipeline.run();
    this._renameOutputIfNeeded(result, explicitOutputFile);
 
    ResultPrinter.print(result);
    process.exit(result.success ? 0 : 1);
  }
 
  /**
   * Categorize inputs into directories and explicit files.
   */
  private static _categorizeInputs(inputs: string[]): ICategorizedInputs {
    const srcDirs: string[] = [];
    const explicitFiles: string[] = [];
 
    for (const input of inputs) {
      const resolvedPath = resolve(input);
      const isDir =
        existsSync(resolvedPath) && statSync(resolvedPath).isDirectory();
      if (isDir) {
        srcDirs.push(resolvedPath);
      } else {
        explicitFiles.push(resolvedPath);
      }
    }
 
    return { srcDirs, explicitFiles };
  }
 
  /**
   * Expand input paths to .cnx files.
   */
  private static _expandInputFiles(inputs: string[]): string[] {
    let files: string[];
    try {
      files = InputExpansion.expandInputs(inputs);
    } catch (error) {
      console.error(`Error: ${error}`);
      process.exit(1);
    }
 
    if (files.length === 0) {
      console.error("Error: No .cnx files found");
      process.exit(1);
    }
 
    return files;
  }
 
  /**
   * Determine output directory and explicit filename from config.
   */
  private static _determineOutputPath(
    config: ICliConfig,
    files: string[],
  ): IOutputPathResult {
    if (!config.outputPath) {
      return { outDir: dirname(files[0]), explicitOutputFile: null };
    }
 
    const isExplicitFile =
      /\.(c|cpp)$/.test(config.outputPath) && !config.outputPath.endsWith("/");
 
    const stats = existsSync(config.outputPath)
      ? statSync(config.outputPath)
      : null;
 
    // Directory path
    if (stats?.isDirectory() || config.outputPath.endsWith("/")) {
      return { outDir: config.outputPath, explicitOutputFile: null };
    }
 
    // Explicit output file
    Eif (isExplicitFile) {
      if (files.length > 1) {
        console.error(
          "Error: Cannot use explicit output filename with multiple input files",
        );
        console.error("Use a directory path instead: -o <directory>/");
        process.exit(1);
      }
      return {
        outDir: dirname(config.outputPath),
        explicitOutputFile: resolve(config.outputPath),
      };
    }
 
    // Default: treat as directory
    return { outDir: config.outputPath, explicitOutputFile: null };
  }
 
  /**
   * Rename output file if explicit filename was specified.
   */
  private static _renameOutputIfNeeded(
    result: ITranspilerResult,
    explicitOutputFile: string | null,
  ): void {
    if (
      !explicitOutputFile ||
      !result.success ||
      result.outputFiles.length === 0
    ) {
      return;
    }
 
    const generatedFile = result.outputFiles[0];
    if (generatedFile !== explicitOutputFile) {
      renameSync(generatedFile, explicitOutputFile);
      result.outputFiles[0] = explicitOutputFile;
    }
  }
}
 
export default Runner;