All files / cli Runner.ts

97.22% Statements 35/36
96.55% Branches 28/29
100% Functions 5/5
97.22% Lines 35/36

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                                                        13x 13x           13x   13x                             13x 3x     13x   13x 3x     13x   13x 13x                   13x 9x       4x   13x         13x 2x       2x 2x                                 13x         11x     2x 2x 1x 1x                     3x 1x 1x 1x 1x 1x   2x 3x   2x                
/**
 * Runner
 * Executes the transpiler with the given configuration
 */
 
import { basename, dirname, resolve } from "node:path";
import { existsSync, statSync, renameSync } from "node:fs";
import Transpiler from "../transpiler/Transpiler";
import ICliConfig from "./types/ICliConfig";
import ResultPrinter from "./ResultPrinter";
import ITranspilerResult from "../transpiler/types/ITranspilerResult";
import InputExpansion from "../transpiler/data/InputExpansion";
 
/** 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 resolvedInput = resolve(config.input);
    const { outDir, explicitOutputFile } = this._determineOutputPath(
      config,
      resolvedInput,
    );
 
    // Infer basePath from entry file's parent directory if not set
    const basePath = config.basePath || dirname(resolvedInput);
 
    const pipeline = new Transpiler({
      input: resolvedInput,
      includeDirs: config.includeDirs,
      outDir,
      headerOutDir: config.headerOutDir,
      basePath,
      preprocess: config.preprocess,
      defines: config.defines,
      cppRequired: config.cppRequired,
      noCache: config.noCache,
      parseOnly: config.parseOnly,
      target: config.target,
      debugMode: config.debugMode,
    });
 
    if (InputExpansion.isCppEntryPoint(resolvedInput)) {
      console.log(`Scanning ${basename(resolvedInput)} for C-Next includes...`);
    }
 
    const result = await pipeline.transpile({ kind: "files" });
 
    if (InputExpansion.isCppEntryPoint(resolvedInput)) {
      this._printCppEntryPointResult(result, resolvedInput);
    }
 
    this._renameOutputIfNeeded(result, explicitOutputFile);
 
    ResultPrinter.print(result);
    process.exit(result.success ? 0 : 1);
  }
 
  /**
   * Determine output directory and explicit filename from config.
   */
  private static _determineOutputPath(
    config: ICliConfig,
    resolvedInput: string,
  ): IOutputPathResult {
    if (!config.outputPath) {
      return { outDir: dirname(resolvedInput), 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) {
      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;
    }
  }
 
  /**
   * Print result message for C/C++ entry point scanning.
   */
  private static _printCppEntryPointResult(
    result: ITranspilerResult,
    resolvedInput: string,
  ): void {
    if (result.filesProcessed === 0) {
      console.log("No C-Next files found in include tree. To get started:");
      console.log("  1. Create a .cnx file (e.g., led.cnx)");
      console.log("  2. Run: cnext led.cnx");
      console.log("  3. Include the generated header in your C/C++ code");
      console.log(`  4. Re-run: cnext ${basename(resolvedInput)}`);
    } else {
      const fileNames = result.files
        .map((f) => basename(f.sourcePath))
        .join(", ");
      console.log(
        `Found ${result.filesProcessed} C-Next source file(s): ${fileNames}`,
      );
    }
  }
}
 
export default Runner;