All files / cli PlatformIOCommand.ts

100% Statements 73/73
95.45% Branches 21/22
100% Functions 4/4
100% Lines 73/73

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                                            20x 20x   20x 2x 2x 2x     18x                       13x         13x                                                                     13x 13x     13x     13x 1x 1x       11x   1x           10x           11x 11x     11x   11x 11x 11x 11x 11x 11x 11x 11x 11x     11x                 11x 11x   11x   11x 10x 10x 10x   6x 6x     6x         11x 11x 10x       11x 10x       11x 11x               7x   7x     7x 4x 4x 4x 4x   1x 1x     2x       5x     5x     2x                 2x 2x 2x   3x         5x 3x 3x 3x 3x 3x   2x 2x            
/**
 * PlatformIOCommand
 * Setup and uninstall PlatformIO integration
 */
 
import { resolve } from "node:path";
import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
import IFileConfig from "./types/IFileConfig";
 
/**
 * Resolved paths for PlatformIO project.
 */
interface IPioProjectPaths {
  pioIniPath: string;
  scriptPath: string;
}
 
/**
 * Get PlatformIO project paths and validate that platformio.ini exists.
 * Exits with error if not in a PlatformIO project directory.
 */
function getPioProjectPaths(): IPioProjectPaths {
  const pioIniPath = resolve(process.cwd(), "platformio.ini");
  const scriptPath = resolve(process.cwd(), "cnext_build.py");
 
  if (!existsSync(pioIniPath)) {
    console.error("Error: platformio.ini not found in current directory");
    console.error("Run this command from your PlatformIO project root");
    process.exit(1);
  }
 
  return { pioIniPath, scriptPath };
}
 
/**
 * PlatformIO integration commands
 */
class PlatformIOCommand {
  /**
   * Setup PlatformIO integration
   * Creates cnext_build.py and modifies platformio.ini
   */
  static install(): void {
    const { pioIniPath, scriptPath } = getPioProjectPaths();
 
    // Create cnext_build.py script
    // Issue #833: Run transpilation at import time (before compilation),
    // not as a pre-action on buildprog (which runs after compilation)
    const buildScript = String.raw`Import("env")
import subprocess
import sys
from pathlib import Path
 
def transpile_cnext():
    """Transpile from main.cnx entry point — cnext follows includes"""
    entry = Path("src/main.cnx")
    if not entry.exists():
        return
 
    print("Transpiling from main.cnx...")
 
    try:
        result = subprocess.run(
            ["cnext", str(entry)],
            check=True,
            capture_output=True,
            text=True
        )
        if result.stdout:
            lines = result.stdout.strip().split("\n")
            for line in lines:
                if line.startswith(("Compiled", "Collected", "Generated")):
                    print(f"  {line}")
        print("  ✓ Transpilation complete")
    except subprocess.CalledProcessError as e:
        print(f"  ✗ Transpilation failed")
        print(e.stderr)
        sys.exit(1)
 
# Run transpilation at import time (before compilation starts)
transpile_cnext()
`;
 
    writeFileSync(scriptPath, buildScript, "utf-8");
    console.log(`✓ Created: ${scriptPath}`);
 
    // Read platformio.ini
    let pioIni = readFileSync(pioIniPath, "utf-8");
 
    // Check if extra_scripts is already present
    if (pioIni.includes("cnext_build.py")) {
      console.log("✓ PlatformIO already configured for c-next");
      return;
    }
 
    // Add extra_scripts line to [env:*] section or create it
    if (pioIni.includes("extra_scripts")) {
      // Append to existing extra_scripts
      pioIni = pioIni.replace(
        /extra_scripts\s*=\s*(.+)/,
        "extra_scripts = $1\n    pre:cnext_build.py",
      );
    } else {
      // Add new extra_scripts line after first [env:*] section
      pioIni = pioIni.replace(
        /(\[env:[^\]]+\])/,
        "$1\nextra_scripts = pre:cnext_build.py",
      );
    }
 
    writeFileSync(pioIniPath, pioIni, "utf-8");
    console.log(`✓ Modified: ${pioIniPath}`);
 
    // Setup cnext.config.json for PlatformIO
    this.setupConfig();
 
    console.log("");
    console.log("✓ PlatformIO integration configured!");
    console.log("");
    console.log("Next steps:");
    console.log("  1. Create src/main.cnx as your entry point");
    console.log("  2. Use #include to pull in other .cnx files");
    console.log("  3. Run: pio run");
    console.log("");
    console.log(
      "The transpiler will follow includes from main.cnx automatically.",
    );
    console.log("Commit both .cnx and generated .c files to version control.");
  }
 
  /**
   * Setup cnext.config.json with PlatformIO-appropriate defaults
   * - Appends .pio/libdeps to include array
   * - Sets headerOut to "include" if not already set
   */
  private static setupConfig(): void {
    const configPath = resolve(process.cwd(), "cnext.config.json");
    const pioInclude = ".pio/libdeps";
 
    let config: IFileConfig = {};
 
    if (existsSync(configPath)) {
      try {
        const content = readFileSync(configPath, "utf-8");
        config = JSON.parse(content) as IFileConfig;
      } catch (e) {
        const msg = e instanceof Error ? e.message : String(e);
        console.log(
          `⚠ Could not parse existing cnext.config.json (${msg}), creating new one`,
        );
        config = {};
      }
    }
 
    // Append .pio/libdeps to include array if not already present
    const includes = config.include ?? [];
    if (!includes.includes(pioInclude)) {
      config.include = [...includes, pioInclude];
    }
 
    // Set headerOut only if not already set
    if (!config.headerOut) {
      config.headerOut = "include";
    }
 
    // Write config (with pretty formatting)
    writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
    console.log(`✓ Updated: ${configPath}`);
  }
 
  /**
   * Remove PlatformIO integration
   * Deletes cnext_build.py and removes extra_scripts from platformio.ini
   */
  static uninstall(): void {
    const { pioIniPath, scriptPath } = getPioProjectPaths();
 
    let hasChanges = false;
 
    // Remove cnext_build.py if it exists
    if (existsSync(scriptPath)) {
      try {
        unlinkSync(scriptPath);
        console.log(`✓ Removed: ${scriptPath}`);
        hasChanges = true;
      } catch (err) {
        console.error(`Error removing ${scriptPath}:`, err);
        process.exit(1);
      }
    } else {
      console.log("✓ cnext_build.py not found (already removed)");
    }
 
    // Read platformio.ini
    let pioIni = readFileSync(pioIniPath, "utf-8");
 
    // Check if extra_scripts includes cnext_build.py
    if (pioIni.includes("cnext_build.py")) {
      // Remove the cnext_build.py reference
      // Handle both standalone and appended cases
      pioIni = pioIni
        // Remove standalone "extra_scripts = pre:cnext_build.py" line (with newline)
        .replace(/^extra_scripts[ \t]*=[ \t]*pre:cnext_build\.py[ \t]*\n/m, "")
        // Remove from multi-line extra_scripts (e.g., "    pre:cnext_build.py")
        // Use explicit whitespace chars to avoid backtracking with \s+
        .replaceAll(/[\n\t ]+pre:cnext_build\.py/g, "")
        // Clean up multiple consecutive blank lines
        .replaceAll(/\n\n\n+/g, "\n\n");
 
      writeFileSync(pioIniPath, pioIni, "utf-8");
      console.log(`✓ Modified: ${pioIniPath}`);
      hasChanges = true;
    } else {
      console.log(
        "✓ platformio.ini already clean (no c-next integration found)",
      );
    }
 
    if (hasChanges) {
      console.log("");
      console.log("✓ PlatformIO integration removed!");
      console.log("");
      console.log("Your .cnx files remain untouched.");
      console.log("To re-enable integration: cnext --pio-install");
    } else {
      console.log("");
      console.log("No c-next integration found - nothing to remove.");
    }
  }
}
 
export default PlatformIOCommand;