All files / cli PlatformIOCommand.ts

100% Statements 104/104
95.65% Branches 44/46
100% Functions 16/16
100% Lines 102/102

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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340                                    3x       75x         121x 79x                   47x 35x           104x               53x   53x 2x 2x 2x     51x                               36x 36x 36x 36x 36x         1x             34x     34x 2x 2x       32x     36x 2x     30x             36x                                                                                       36x 36x       36x 36x 6x   24x 24x     30x 30x 6x     24x 24x 24x 24x 24x 24x 24x 24x 24x     24x                       5x 5x   5x                   24x 24x 24x 8x         16x 16x   16x                                         30x 30x 30x   30x 1x 1x     29x                 30x 30x               17x   17x   17x 17x 7x 7x 7x 7x   1x 1x     9x     15x 15x 15x 11x 11x 11x   4x     15x 12x 12x 12x 12x 12x   3x 3x                     15x 15x 15x   15x 12x 20x 12x 12x     12x                
/**
 * PlatformIOCommand
 * Setup and uninstall PlatformIO integration
 */
 
import { resolve } from "node:path";
import NodeFileSystem from "../cnx/PARSE/1-Discover/NodeFileSystem";
import Write from "../cnx/WRITE/1-Write/Write";
import IFileConfig from "./types/IFileConfig";
import CONFIG_FILE_NAMES from "../cnx/types/CONFIG_FILE_NAMES";
import type IFileSystem from "../cnx/types/IFileSystem";
import ConfigLoader from "./ConfigLoader";
import type TConfigObject from "./types/TConfigObject";
import PlatformIOIni from "../cnx/PARSE/1-Discover/PlatformIOIni";
import type IPlatformIOIniOption from "../cnx/PARSE/1-Discover/types/IPlatformIOIniOption";
import packageJson from "../../package.json" with { type: "json" };
 
/** The pre-build script `--pio-install` writes. */
const BUILD_SCRIPT = "cnx_build.py";
 
/** The `extra_scripts` entry that runs the script `name` before a build. */
function entryOf(name: string): string {
  return `pre:${name}`;
}
 
/** Every `extra_scripts` option in `pioIni`, as PlatformIO reads the file. */
function extraScripts(pioIni: string): IPlatformIOIniOption[] {
  return PlatformIOIni.layout(pioIni).options.filter(
    (option) => option.key === "extra_scripts",
  );
}
 
/**
 * Whether `pioIni` runs the script `name`: an `extra_scripts` item is its
 * entry, read as PlatformIO reads the list. `pre:my_cnx_build.py`, a comment
 * naming the file, and a commented-out entry do not count.
 */
function hasEntry(pioIni: string, name: string): boolean {
  return extraScripts(pioIni).some((option) =>
    PlatformIOIni.list(option.value).includes(entryOf(name)),
  );
}
 
/** `name` in the project being configured. */
function inProject(name: string): string {
  return resolve(process.cwd(), name);
}
 
/**
 * The project's platformio.ini. Exits with error if not in a PlatformIO
 * project directory.
 */
function getPioIniPath(fs: IFileSystem): string {
  const pioIniPath = inProject("platformio.ini");
 
  if (!fs.exists(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;
}
 
/**
 * PlatformIO integration commands
 */
class PlatformIOCommand {
  /**
   * Setup PlatformIO integration
   * Creates cnx_build.py and modifies platformio.ini
   *
   * A config it cannot read, or that holds no config object, stops it before
   * anything is written (#2221 review): it used to write on, dropping the
   * settings or shadowing the file.
   */
  static install(fs: IFileSystem = NodeFileSystem.instance): void {
    const pioIniPath = getPioIniPath(fs);
    const scriptPath = inProject(BUILD_SCRIPT);
    const pioIni = fs.readFile(pioIniPath);
    const scripts = extraScripts(pioIni).at(0);
    if (
      scripts !== undefined &&
      !hasEntry(pioIni, BUILD_SCRIPT) &&
      PlatformIOIni.isOneLine(pioIni, scripts) === undefined
    ) {
      PlatformIOCommand.stopBeforeWriting(
        [
          `extra_scripts = ${scripts.value} in [${scripts.section}] names a value only the build machine knows, so it is not known how to add the hook`,
        ],
        `Add ${entryOf(BUILD_SCRIPT)} to it by hand, then run cnx --pio-install again.`,
      );
    }
    const config = ConfigLoader.inDirectory(process.cwd(), fs);
    // #2221 review: a config it cannot read was only a warning, so install
    // wrote on: a crash half-installed, or a cnx.config.json shadowing it
    if (config.unreadable.length > 0) {
      PlatformIOCommand.stopBeforeWriting(
        config.unreadable.map((file) => file.reason),
      );
    }
    const existing: TConfigObject =
      config.kind === "found"
        ? ConfigLoader.objectOf(config)
        : { kind: "object", config: {} };
    if (existing.kind === "invalid") {
      PlatformIOCommand.stopBeforeWriting([existing.reason]);
    }
    const configPath =
      config.kind === "found"
        ? config.path
        : resolve(process.cwd(), CONFIG_FILE_NAMES[0]);
 
    // Create cnx_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_cnx():
    """Transpile from main.cnx entry point — cnx follows includes"""
    entry = Path("src/main.cnx")
    if not entry.exists():
        return
 
    print("Transpiling from main.cnx...")
 
    try:
        # ADR-049: the environment being built names the target. Without it,
        # "pio run -e X" in a project whose default_envs names Y would get Y's.
        result = subprocess.run(
            ["cnx", str(entry), "--pio-env", env["PIOENV"]],
            check=True,
            capture_output=True,
            text=True
        )
        # Warnings go to stderr, which a successful run would otherwise drop
        if result.stderr:
            print(result.stderr.rstrip())
        if result.stdout:
            lines = result.stdout.strip().split("\n")
            for line in lines:
                if line.startswith(("Compiled", "Target", "Collected", "Generated")):
                    print(f"  {line}")
        print("  ✓ Transpilation complete")
    except subprocess.CalledProcessError as e:
        print(f"  ✗ Transpilation failed")
        print(e.stderr)
        sys.exit(1)
    except FileNotFoundError:
        # Not on PATH: say what is missing, not a Python traceback (#2174)
        print("  ✗ cnx not found on PATH: npm i -g ${packageJson.name}")
        sys.exit(1)
 
# Run transpilation at import time (before compilation starts)
transpile_cnx()
`;
 
    Write.file(fs, scriptPath, buildScript);
    console.log(`✓ Created: ${scriptPath}`);
 
    // An already-configured platformio.ini is left as it is; the config is
    // set up either way (#2221 review: a reinstall used to return first)
    const alreadyConfigured = hasEntry(pioIni, BUILD_SCRIPT);
    if (alreadyConfigured) {
      console.log("✓ PlatformIO already configured for cnx");
    } else {
      Write.file(fs, pioIniPath, PlatformIOCommand.withBuildScript(pioIni));
      console.log(`✓ Modified: ${pioIniPath}`);
    }
 
    this.setupConfig(configPath, existing.config, fs);
    if (alreadyConfigured) {
      return;
    }
 
    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.");
  }
 
  /**
   * Stop before anything is written, with each reason install cannot go on
   * and what to do about it: the one way install refuses (#2221 review,
   * #2174 review).
   */
  private static stopBeforeWriting(
    reasons: readonly string[],
    remedy = "Fix it and run --pio-install again.",
  ): never {
    for (const reason of reasons) {
      console.error(`Error: ${reason}; nothing was written. ${remedy}`);
    }
    process.exit(1);
  }
 
  /**
   * `pioIni` with the pre-build script added to its first `extra_scripts`,
   * in the form that list is written in, else on a new `extra_scripts` line
   * opening the first `[env:*]` section. TODO(#2273): every other env builds
   * without the hook.
   */
  private static withBuildScript(pioIni: string): string {
    const entry = entryOf(BUILD_SCRIPT);
    const scripts = extraScripts(pioIni).at(0);
    if (scripts !== undefined) {
      return PlatformIOIni.withItems(pioIni, scripts, [
        ...PlatformIOIni.list(scripts.value),
        entry,
      ]);
    }
    const env = PlatformIOIni.layout(pioIni).sections.find((section) =>
      section.name.startsWith("env:"),
    );
    return env === undefined
      ? pioIni
      : PlatformIOIni.withOption(pioIni, env, "extra_scripts", entry);
  }
 
  /**
   * Give the project's config PlatformIO-appropriate defaults
   * - Appends .pio/libdeps to include array
   * - Sets headerOut to "include" if not already set
   *
   * #2165: the file updated is this directory's config, under whichever name
   * it has. Writing `cnx.config.json` regardless shadowed a project's `.cnxrc`,
   * silently, since the walk takes the first name. An ancestor's config is
   * never this project's to shadow: `platformio.ini` makes this directory its
   * own root (#2261, which closed #2235).
   */
  private static setupConfig(
    configPath: string,
    config: IFileConfig,
    fs: IFileSystem,
  ): void {
    const pioInclude = ".pio/libdeps";
    const includes = config.include ?? [];
    const hasPioInclude = includes.includes(pioInclude);
    // A reinstall of a project already set up writes nothing (#2221 review)
    if (hasPioInclude && config.headerOut) {
      console.log(`✓ ${configPath} already has the PlatformIO defaults`);
      return;
    }
 
    const updated: IFileConfig = {
      ...config,
      // Append .pio/libdeps to include array if not already present
      include: hasPioInclude ? includes : [...includes, pioInclude],
      // Set headerOut only if not already set
      headerOut: config.headerOut || "include",
    };
 
    // Write config (with pretty formatting)
    Write.file(fs, configPath, JSON.stringify(updated, null, 2) + "\n");
    console.log(`✓ Updated: ${configPath}`);
  }
 
  /**
   * Remove PlatformIO integration
   * Deletes cnx_build.py and removes its extra_scripts entry from platformio.ini
   */
  static uninstall(fs: IFileSystem = NodeFileSystem.instance): void {
    const pioIniPath = getPioIniPath(fs);
 
    let hasChanges = false;
 
    const scriptPath = inProject(BUILD_SCRIPT);
    if (fs.exists(scriptPath)) {
      try {
        Write.remove(fs, scriptPath);
        console.log(`✓ Removed: ${scriptPath}`);
        hasChanges = true;
      } catch (err) {
        console.error(`Error removing ${scriptPath}:`, err);
        process.exit(1);
      }
    } else {
      console.log(`✓ ${BUILD_SCRIPT} not found (already removed)`);
    }
 
    const pioIni = fs.readFile(pioIniPath);
    const cleaned = PlatformIOCommand.withoutBuildScript(pioIni);
    if (cleaned !== pioIni) {
      Write.file(fs, pioIniPath, cleaned);
      console.log(`✓ Modified: ${pioIniPath}`);
      hasChanges = true;
    } else {
      console.log("✓ platformio.ini already clean (no cnx 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: cnx --pio-install");
    } else {
      console.log("");
      console.log("No cnx integration found - nothing to remove.");
    }
  }
 
  /**
   * `pioIni` with no `extra_scripts` item running the script, every other item
   * left in place (#2174 review: removing the line
   * `extra_scripts = pre:cnx_build.py` left the indented scripts below it with
   * no key).
   */
  private static withoutBuildScript(pioIni: string): string {
    const entry = entryOf(BUILD_SCRIPT);
    const options = extraScripts(pioIni);
    let cleaned = pioIni;
    // Last first, so each option's line numbers still hold when it is edited
    for (let index = options.length - 1; index >= 0; index -= 1) {
      const items = PlatformIOIni.list(options[index].value);
      const kept = items.filter((item) => item !== entry);
      Eif (kept.length < items.length) {
        cleaned = PlatformIOIni.withItems(cleaned, options[index], kept);
      }
    }
    return cleaned === pioIni
      ? pioIni
      : // Clean up multiple consecutive blank lines
        cleaned.replaceAll(/\n\n\n+/g, "\n\n");
  }
}
 
export default PlatformIOCommand;