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 137 138 139                                        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 4x   24x 24x 24x 24x   4x 4x            
/**
 * CleanCommand
 * Deletes generated files (.c, .cpp, .h, .hpp) that have matching .cnx sources
 */
 
import { basename, dirname, join, resolve } from "node:path";
import InputExpansion from "../PARSE/1-Discover/InputExpansion";
import PathResolver from "../PARSE/1-Discover/PathResolver";
import NodeFileSystem from "../PARSE/1-Discover/NodeFileSystem";
import Write from "../WRITE/1-Write/Write";
 
/**
 * Command to clean generated output files
 */
class CleanCommand {
  /**
   * Discover CNX files from entry point.
   * Returns null if none found or on error.
   */
  private static discoverCnxFiles(input: string): string[] | null {
    try {
      const cnxFiles = InputExpansion.expandInputs(
        [input],
        NodeFileSystem.instance,
      );
      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 input - Entry point .cnx file
   * @param outDir - Output directory for code files
   * @param headerOutDir - Optional separate output directory for headers
   */
  static execute(input: string, outDir: string, headerOutDir?: string): void {
    if (!outDir) {
      console.log("No output directory specified. Nothing to clean.");
      return;
    }
 
    const cnxFiles = this.discoverCnxFiles(input);
    if (!cnxFiles) return;
 
    const resolvedOutDir = resolve(outDir);
    const resolvedHeaderDir = headerOutDir
      ? resolve(headerOutDir)
      : resolvedOutDir;
 
    const pathResolver = new PathResolver(
      {
        inputs: [dirname(resolve(input))],
        outDir,
        headerOutDir,
      },
      NodeFileSystem.instance,
    );
 
    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 {
    // A file that is not there is not an error for our purposes.
    if (!NodeFileSystem.instance.exists(filePath)) {
      return false;
    }
    try {
      Write.remove(NodeFileSystem.instance, filePath);
      console.log(`  Deleted: ${filePath}`);
      return true;
    } catch (err: unknown) {
      console.error(`  Failed to delete ${filePath}: ${err}`);
      return false;
    }
  }
}
 
export default CleanCommand;