All files / cli CleanCommand.ts

100% Statements 40/40
100% Branches 16/16
100% Functions 4/4
100% Lines 39/39

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                                      9x 9x 9x 1x 1x   7x   1x 1x                         14x 14x 28x     28x 20x     14x                             10x 1x 1x     9x 9x   7x 7x       10x           10x   10x 7x 7x     7x               7x               7x 2x   5x                 28x 28x 28x 28x     8x 4x   4x 4x            
/**
 * CleanCommand
 * Deletes generated files (.c, .cpp, .h, .hpp) that have matching .cnx sources
 */
 
import { basename, join, resolve } from "node:path";
import { unlinkSync } from "node:fs";
import InputExpansion from "../transpiler/data/InputExpansion";
import PathResolver from "../transpiler/data/PathResolver";
 
/**
 * Command to clean generated output files
 */
class CleanCommand {
  /**
   * Discover CNX files from inputs.
   * Returns null if none found or on error.
   */
  private static discoverCnxFiles(inputs: string[]): string[] | null {
    try {
      const cnxFiles = InputExpansion.expandInputs(inputs);
      if (cnxFiles.length === 0) {
        console.log("No .cnx files found. Nothing to clean.");
        return null;
      }
      return cnxFiles;
    } catch (error) {
      console.error(`Error: ${error}`);
      return null;
    }
  }
 
  /**
   * Delete generated files for a given set of extensions.
   */
  private static deleteGeneratedFiles(
    baseName: string,
    relativePath: string | null,
    targetDir: string,
    extensions: string[],
  ): number {
    let count = 0;
    for (const ext of extensions) {
      const outputPath = relativePath
        ? join(targetDir, relativePath.replace(/\.cnx$|\.cnext$/, ext))
        : join(targetDir, baseName + ext);
      if (this.deleteIfExists(outputPath)) {
        count++;
      }
    }
    return count;
  }
 
  /**
   * Execute the clean command
   *
   * @param inputs - Input files or directories (source locations)
   * @param outDir - Output directory for code files
   * @param headerOutDir - Optional separate output directory for headers
   */
  static execute(
    inputs: string[],
    outDir: string,
    headerOutDir?: string,
  ): void {
    if (!outDir) {
      console.log("No output directory specified. Nothing to clean.");
      return;
    }
 
    const cnxFiles = this.discoverCnxFiles(inputs);
    if (!cnxFiles) return;
 
    const resolvedOutDir = resolve(outDir);
    const resolvedHeaderDir = headerOutDir
      ? resolve(headerOutDir)
      : resolvedOutDir;
 
    const pathResolver = new PathResolver({
      inputs,
      outDir,
      headerOutDir,
    });
 
    let deletedCount = 0;
 
    for (const cnxFile of cnxFiles) {
      const baseName = basename(cnxFile).replace(/\.cnx$|\.cnext$/, "");
      const relativePath = pathResolver.getRelativePathFromInputs(cnxFile);
 
      // Delete code files (.c and .cpp)
      deletedCount += this.deleteGeneratedFiles(
        baseName,
        relativePath,
        resolvedOutDir,
        [".c", ".cpp"],
      );
 
      // Delete header files (.h and .hpp)
      deletedCount += this.deleteGeneratedFiles(
        baseName,
        relativePath,
        resolvedHeaderDir,
        [".h", ".hpp"],
      );
    }
 
    if (deletedCount === 0) {
      console.log("No generated files found to delete.");
    } else {
      console.log(`Deleted ${deletedCount} generated file(s).`);
    }
  }
 
  /**
   * Delete a file if it exists
   * @returns true if file was deleted, false otherwise
   */
  private static deleteIfExists(filePath: string): boolean {
    try {
      unlinkSync(filePath);
      console.log(`  Deleted: ${filePath}`);
      return true;
    } catch (err: unknown) {
      // ENOENT means file doesn't exist - not an error for our purposes
      if ((err as NodeJS.ErrnoException).code === "ENOENT") {
        return false;
      }
      console.error(`  Failed to delete ${filePath}: ${err}`);
      return false;
    }
  }
}
 
export default CleanCommand;