|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import json |
| 4 | +import os |
| 5 | +import re |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +def main(): |
| 10 | + parser = argparse.ArgumentParser( |
| 11 | + description="Generate VS Code launch.json from configured CMake build targets." |
| 12 | + ) |
| 13 | + parser.add_argument( |
| 14 | + "--build-dir", |
| 15 | + type=str, |
| 16 | + required=True, |
| 17 | + help="Path to the active CMake build directory.", |
| 18 | + ) |
| 19 | + args = parser.parse_args() |
| 20 | + |
| 21 | + workspace_root = Path(__file__).resolve().parent.parent |
| 22 | + build_dir = Path(args.build_dir).resolve() |
| 23 | + |
| 24 | + if not build_dir.exists(): |
| 25 | + print(f"Error: Build directory {build_dir} does not exist.", file=sys.stderr) |
| 26 | + sys.exit(1) |
| 27 | + |
| 28 | + # 1. Read targets from debug_targets.json inside build_dir |
| 29 | + json_path = build_dir / "debug_targets.json" |
| 30 | + if not json_path.exists(): |
| 31 | + print(f"No debug_targets.json found in {build_dir}. Skipping generation.", file=sys.stderr) |
| 32 | + sys.exit(0) |
| 33 | + |
| 34 | + try: |
| 35 | + targets = json.loads(json_path.read_text(encoding="utf-8")) |
| 36 | + except Exception as e: |
| 37 | + print(f"Error reading/parsing {json_path}: {e}", file=sys.stderr) |
| 38 | + sys.exit(1) |
| 39 | + |
| 40 | + new_configs = [] |
| 41 | + |
| 42 | + for target in targets: |
| 43 | + name = target.get("name") |
| 44 | + device = target.get("device") |
| 45 | + exec_path_str = target.get("executable") |
| 46 | + |
| 47 | + if not name or not device or not exec_path_str: |
| 48 | + continue |
| 49 | + |
| 50 | + exec_path = Path(exec_path_str) |
| 51 | + |
| 52 | + # Derive SVD file path |
| 53 | + rel_svd = "" |
| 54 | + if device.startswith("STM32"): |
| 55 | + # The naming convention for SVDs is STM32 + first 4 chars of model + .svd |
| 56 | + # e.g., STM32F407VE -> STM32F407.svd |
| 57 | + svd_name = f"{device[:9]}.svd" |
| 58 | + svd_path = workspace_root / "modules" / "stm32" / "scripts" / svd_name |
| 59 | + if svd_path.exists(): |
| 60 | + rel_svd = "${workspaceFolder}/" + str(svd_path.resolve().relative_to(workspace_root.resolve())) |
| 61 | + |
| 62 | + # Convert absolute paths to workspace-relative using VS Code variable |
| 63 | + try: |
| 64 | + rel_exec = "${workspaceFolder}/" + str(exec_path.resolve().relative_to(workspace_root.resolve())) |
| 65 | + except ValueError: |
| 66 | + rel_exec = str(exec_path) |
| 67 | + |
| 68 | + # Create launch configuration |
| 69 | + config = { |
| 70 | + "name": f"Cortex-Debug (JLink): {name}", |
| 71 | + "cwd": "${workspaceFolder}", |
| 72 | + "executable": rel_exec, |
| 73 | + "request": "launch", |
| 74 | + "type": "cortex-debug", |
| 75 | + "servertype": "jlink", |
| 76 | + "interface": "swd", |
| 77 | + "runToEntryPoint": "reset_entry", |
| 78 | + "device": device, |
| 79 | + "internalConsoleOptions": "openOnSessionStart", |
| 80 | + "showDevDebugOutput": "both", |
| 81 | + "preLaunchCommands": [ |
| 82 | + "set mem inaccessible-by-default off" |
| 83 | + ], |
| 84 | + "preResetCommands": [ |
| 85 | + "monitor reset 0" |
| 86 | + ], |
| 87 | + } |
| 88 | + |
| 89 | + if rel_svd: |
| 90 | + config["svdFile"] = rel_svd |
| 91 | + |
| 92 | + new_configs.append(config) |
| 93 | + |
| 94 | + print(f"Generated {len(new_configs)} debug configurations for build directory {build_dir.name}.") |
| 95 | + |
| 96 | + # 2. Read existing launch.json, filter/merge, and write back |
| 97 | + launch_json_path = workspace_root / ".vscode" / "launch.json" |
| 98 | + existing_launch = {"version": "0.2.0", "configurations": []} |
| 99 | + |
| 100 | + if launch_json_path.exists(): |
| 101 | + try: |
| 102 | + raw_content = launch_json_path.read_text(encoding="utf-8") |
| 103 | + # Strip comments and trailing commas to parse with standard json |
| 104 | + clean_content = re.sub(r'//.*', '', raw_content) |
| 105 | + clean_content = re.sub(r',\s*([\]}])', r'\1', clean_content) |
| 106 | + existing_launch = json.loads(clean_content) |
| 107 | + except Exception as e: |
| 108 | + print(f"Warning: Could not parse existing launch.json ({e}). Overwriting.", file=sys.stderr) |
| 109 | + |
| 110 | + # Filter out existing cortex-debug configurations to avoid duplication/stale entries |
| 111 | + non_cortex_configs = [ |
| 112 | + c for c in existing_launch.get("configurations", []) |
| 113 | + if c.get("type") != "cortex-debug" |
| 114 | + ] |
| 115 | + |
| 116 | + # Merge |
| 117 | + merged_configs = non_cortex_configs + new_configs |
| 118 | + existing_launch["configurations"] = merged_configs |
| 119 | + |
| 120 | + # Ensure .vscode dir exists |
| 121 | + launch_json_path.parent.mkdir(parents=True, exist_ok=True) |
| 122 | + |
| 123 | + # Write back |
| 124 | + try: |
| 125 | + with open(launch_json_path, "w", encoding="utf-8") as f: |
| 126 | + f.write("// Auto-generated debug configurations. Do not edit manually.\n") |
| 127 | + f.write("// Run CMake configure to update.\n") |
| 128 | + json.dump(existing_launch, f, indent=4) |
| 129 | + f.write("\n") |
| 130 | + print(f"Successfully updated {launch_json_path}") |
| 131 | + except Exception as e: |
| 132 | + print(f"Error: Could not write to {launch_json_path} ({e})", file=sys.stderr) |
| 133 | + sys.exit(1) |
| 134 | + |
| 135 | +if __name__ == "__main__": |
| 136 | + main() |
0 commit comments