All files / cli ArgParser.ts

96.55% Statements 28/29
90% Branches 9/10
100% Functions 4/4
100% Lines 27/27

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                                                                              31x                                                                                                                                                                                                                                                                                                                       2x   8x 2x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x                             31x     31x 2x 2x     29x     29x 29x 5x 5x 2x   3x         27x   27x                                                
/**
 * ArgParser
 * Parses command-line arguments using yargs
 */
 
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import ConfigPrinter from "./ConfigPrinter";
import IParsedArgs from "./types/IParsedArgs";
 
/**
 * Interface for yargs parsed result
 */
interface IYargsResult {
  _: (string | number)[];
  o?: string;
  output?: string;
  "header-out"?: string;
  "base-path"?: string;
  cpp: boolean;
  include: string[];
  target?: string;
  D: string[];
  parse: boolean;
  clean: boolean;
  config: boolean;
  verbose: boolean;
  debug: boolean;
  preprocess: boolean;
  cache: boolean;
  "pio-install": boolean;
  "pio-uninstall": boolean;
  serve: boolean;
}
 
/**
 * Configure yargs with all options
 */
function configureYargs(args: string[], argv: string[]) {
  return (
    yargs(args)
      .scriptName("cnext")
      .usage(
        `Usage:
  cnext <file.cnx>                          Single file (outputs file.c)
  cnext <file.cnx> -o <output.c>            Single file with explicit output
  cnext <files...> -o <dir>                 Multi-file mode
  cnext <dir>                               Directory mode (recursive)
 
A safer C for embedded systems development.`,
      )
 
      // Output options
      .option("o", {
        alias: "output",
        type: "string",
        describe: "Output file or directory (default: same dir as input)",
        requiresArg: true,
      })
      .option("header-out", {
        type: "string",
        describe: "Output directory for header files",
        requiresArg: true,
      })
      .option("base-path", {
        type: "string",
        describe:
          "Strip path prefix from header output (use with --header-out)",
        requiresArg: true,
      })
 
      // Compilation options
      .option("cpp", {
        type: "boolean",
        describe: "Output .cpp instead of .c (for C++ features like Serial)",
        default: false,
      })
      .option("include", {
        type: "string",
        array: true,
        describe: "Additional include directory (can repeat)",
        requiresArg: true,
        default: [] as string[],
      })
      .option("target", {
        type: "string",
        describe: "Target platform for atomic code gen (ADR-049)",
        requiresArg: true,
      })
      .option("D", {
        type: "string",
        array: true,
        describe: "Define preprocessor macro",
        default: [] as string[],
      })
 
      // Mode flags
      .option("parse", {
        type: "boolean",
        describe: "Parse only, don't generate code",
        default: false,
      })
      .option("clean", {
        type: "boolean",
        describe: "Delete generated files for all .cnx sources",
        default: false,
      })
      .option("config", {
        type: "boolean",
        describe: "Show effective configuration and exit",
        default: false,
      })
 
      // Debug/development options
      .option("verbose", {
        type: "boolean",
        describe: "Show include path discovery",
        default: false,
      })
      .option("debug", {
        type: "boolean",
        describe: "Generate panic-on-overflow helpers (ADR-044)",
        default: false,
      })
      .option("preprocess", {
        type: "boolean",
        describe:
          "Run C preprocessor on headers (use --no-preprocess to disable)",
        default: true,
      })
      .option("cache", {
        type: "boolean",
        describe: "Enable symbol cache (use --no-cache to disable)",
        default: true,
      })
 
      // PlatformIO integration
      .option("pio-install", {
        type: "boolean",
        describe: "Setup PlatformIO integration",
        default: false,
      })
      .option("pio-uninstall", {
        type: "boolean",
        describe: "Remove PlatformIO integration",
        default: false,
      })
 
      // Server mode
      .option("serve", {
        type: "boolean",
        describe: "Start JSON-RPC server on stdin/stdout",
        default: false,
      })
 
      // Config file documentation (shown in help)
      .epilogue(
        `Examples:
  cnext main.cnx                            # Outputs main.c (same dir)
  cnext main.cnx -o build/main.c            # Explicit output path
  cnext src/*.cnx -o build/                 # Multiple files to directory
  cnext src/                                # Compile all .cnx files in src/ (recursive)
 
Target platforms: teensy41, cortex-m7, cortex-m4, cortex-m3, cortex-m0+, cortex-m0, avr
 
Config files (searched in order, JSON format):
  cnext.config.json, .cnext.json, .cnextrc
 
Config options:
  cppRequired    Output .cpp instead of .c (boolean)
  noCache        Disable symbol caching (boolean)
  include        Additional include directories (string[])
  output         Output directory for generated files (string)
  headerOut      Separate directory for header files (string)
  target         Target platform for atomic code gen (string)
  debugMode      Generate panic-on-overflow helpers (boolean)`,
      )
 
      // Version from package.json
      .version(
        "version",
        "Show version",
        `cnext v${ConfigPrinter.getVersion()}`,
      )
      .alias("version", "v")
 
      // Help
      .help("help")
      .alias("help", "h")
 
      // Strict mode - reject unknown options (but allow positional args)
      .strictOptions()
 
      // Fail handler for unknown options
      .fail((msg, err, yargsInstance) => {
        Iif (err) throw err;
        // Check for -I flag (common GCC mistake)
        const hasIFlag = argv.some((arg) => arg.startsWith("-I"));
        if (hasIFlag) {
          console.error("Error: Unknown flag '-I...'");
          console.error("  Did you mean: --include <dir>");
          console.error("");
          console.error("Example:");
          console.error("  cnext src --include path/to/headers");
          process.exit(1);
        }
        console.error(msg);
        console.error("");
        yargsInstance.showHelp();
        process.exit(1);
      })
  );
}
 
/**
 * Parse command-line arguments using yargs
 */
class ArgParser {
  /**
   * Parse command-line arguments into a structured object
   * @param argv - Command-line arguments (typically process.argv)
   * @returns Parsed arguments object
   */
  static parse(argv: string[]): IParsedArgs {
    const args = hideBin(argv);
 
    // Show help and exit 0 when no arguments provided
    if (args.length === 0) {
      configureYargs([], argv).showHelp("log"); // Output to stdout, not stderr
      process.exit(0);
    }
 
    const parsed = configureYargs(args, argv).parseSync() as IYargsResult;
 
    // Parse -D defines into a record
    const defines: Record<string, string | boolean> = {};
    for (const define of parsed.D) {
      const eqIndex = define.indexOf("=");
      if (eqIndex > 0) {
        defines[define.slice(0, eqIndex)] = define.slice(eqIndex + 1);
      } else {
        defines[define] = true;
      }
    }
 
    // Get input files from positional args (everything that isn't an option)
    const inputFiles = parsed._.map(String);
 
    return {
      inputFiles,
      outputPath: parsed.o ?? "",
      includeDirs: parsed.include,
      defines,
      cppRequired: parsed.cpp,
      target: parsed.target,
      preprocess: parsed.preprocess,
      verbose: parsed.verbose,
      noCache: !parsed.cache,
      parseOnly: parsed.parse,
      headerOutDir: parsed["header-out"],
      basePath: parsed["base-path"],
      cleanMode: parsed.clean,
      showConfig: parsed.config,
      pioInstall: parsed["pio-install"],
      pioUninstall: parsed["pio-uninstall"],
      debugMode: parsed.debug,
      serveMode: parsed.serve,
    };
  }
}
 
export default ArgParser;