summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
authorBEAST <macbook@Macbooks-MacBook-Pro-2.local>2026-11-16 19:23:09 +0530
committerBEAST <macbook@Macbooks-MacBook-Pro-2.local>2026-11-16 19:23:09 +0530
commit7764125350e66e464dded24ca8cf69a7e1ecef8d (patch)
treee01f8b3a15fe905d6e5ccc3da6822df238b49030 /tools
Add local project files
Diffstat (limited to 'tools')
-rw-r--r--tools/ensure-python.ps1208
-rw-r--r--tools/ensure-python.sh173
-rwxr-xr-xtools/new-nrl-opmode.bat29
-rw-r--r--tools/new-nrl-opmode.sh19
-rw-r--r--tools/nrl_new_opmode.py307
5 files changed, 736 insertions, 0 deletions
diff --git a/tools/ensure-python.ps1 b/tools/ensure-python.ps1
new file mode 100644
index 0000000..7d97666
--- /dev/null
+++ b/tools/ensure-python.ps1
@@ -0,0 +1,208 @@
+<#
+=====================================================================
+ ensure-python.ps1 - Detect a usable Python 3, installing one if
+ none is found, then print its path/command on stdout.
+
+ Used by the Windows launcher (new-nrl-project.bat).
+ A brand-new student who has never installed Python can double-click the
+ launcher and have it "just work": this script installs Python 3 via
+ winget (built into Win10/11) and falls back to the official python.org
+ silent installer on older Windows.
+
+ Contract:
+ - stdout : exactly ONE line, the interpreter to run (e.g. a full path
+ to python.exe, or "py" when the launcher is on PATH).
+ - stderr : all human-readable progress / status / error text.
+ - exit 0 : interpreter found/installed; its path is on stdout.
+ - exit 1 : no interpreter could be found or installed.
+=====================================================================
+#>
+$ErrorActionPreference = 'Stop'
+
+# Anything we want the user to read goes to stderr so stdout stays clean
+# for the single interpreter path the .bat captures.
+function Say([string]$msg) { [Console]::Error.WriteLine($msg) }
+
+# Emit the chosen interpreter on stdout and exit success.
+function Emit([string]$exe) {
+ Write-Output $exe
+ exit 0
+}
+
+# Resolve a candidate to its real python.exe IFF it is a Python 3 that ALSO
+# has tkinter -- the wizard's folder picker needs it. Prints the resolved
+# path, or $null when the candidate is missing / not Python 3 / has no tkinter.
+function Resolve-Usable([string]$exe, [string[]]$prefix) {
+ # Probe inside a job with a timeout. A Microsoft Store "python.exe" alias
+ # stub (present by default when no real Python is installed) HANGS when
+ # invoked -- it tries to open the Store -- so a plain call could freeze the
+ # launcher. An installed interpreter prints its path in well under a second;
+ # anything that hasn't answered in time is treated as unusable.
+ $job = $null
+ try {
+ $job = Start-Job -ScriptBlock {
+ param($e, $p)
+ $o = & $e @p -c "import sys, tkinter; print(sys.executable)" 2>$null
+ if ($LASTEXITCODE -eq 0) { $o }
+ } -ArgumentList $exe, $prefix
+ if (Wait-Job $job -Timeout 30) {
+ $out = Receive-Job $job
+ if ($out) {
+ return ([string]($out | Where-Object { $_ } | Select-Object -Last 1)).Trim()
+ }
+ } else {
+ Stop-Job $job -ErrorAction SilentlyContinue
+ }
+ } catch {
+ } finally {
+ if ($job) { Remove-Job $job -Force -ErrorAction SilentlyContinue }
+ }
+ return $null
+}
+
+# ----- 1) Detect an existing, USABLE interpreter ---------------------------
+# We require a "real" Python 3 WITH tkinter. PlatformIO's bundled Python is
+# deliberately NOT accepted here: it ships without tkinter, so the wizard's
+# folder picker would silently break. When only that exists we install a real
+# Python below instead.
+function Find-Python {
+ if (Get-Command py -ErrorAction SilentlyContinue) {
+ $p = Resolve-Usable 'py' @('-3'); if ($p) { return $p }
+ }
+ $python = Get-Command python -ErrorAction SilentlyContinue
+ if ($python) {
+ $p = Resolve-Usable $python.Source @(); if ($p) { return $p }
+ }
+ return $null
+}
+
+# Search the well-known per-user install locations for an interpreter that a
+# fresh install just dropped (PATH is NOT refreshed in this session). Each
+# candidate is validated with Resolve-Usable so we only return a tkinter-
+# capable Python 3.
+function Find-FreshlyInstalled {
+ $roots = @(
+ (Join-Path $env:LOCALAPPDATA 'Programs\Python'), # python.org / winget per-user
+ (Join-Path $env:LOCALAPPDATA 'Python'), # Windows Python Install Manager (pythoncore-*)
+ 'C:\Program Files\Python*',
+ 'C:\Python3*'
+ )
+ foreach ($root in $roots) {
+ $exes = Get-ChildItem -Path $root -Filter 'python.exe' -Recurse -ErrorAction SilentlyContinue |
+ Sort-Object FullName -Descending
+ foreach ($exe in $exes) {
+ $p = Resolve-Usable $exe.FullName @(); if ($p) { return $p }
+ }
+ }
+ return $null
+}
+
+# Discover the latest STABLE Python from python.org's release index, verifying
+# that the Windows amd64 installer actually exists for it (newest first). This
+# keeps us on the current release instead of a hard-coded, ageing version.
+# Returns @{ Version='3.14.6'; Minor='3.14'; Url='https://.../python-3.14.6-amd64.exe' } or $null.
+function Get-LatestPython {
+ try {
+ $ProgressPreference = 'SilentlyContinue'
+ $idx = Invoke-WebRequest -Uri 'https://www.python.org/ftp/python/' -UseBasicParsing -TimeoutSec 20
+ # Match only pure X.Y.Z folders -> pre-releases like 3.15.0a1/ are excluded.
+ $vers = [regex]::Matches($idx.Content, 'href="(\d+\.\d+\.\d+)/"') |
+ ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique |
+ Sort-Object { [version]$_ } -Descending
+ foreach ($v in ($vers | Select-Object -First 12)) {
+ $url = "https://www.python.org/ftp/python/$v/python-$v-amd64.exe"
+ try {
+ $h = Invoke-WebRequest -Uri $url -Method Head -UseBasicParsing -TimeoutSec 15
+ if ($h.StatusCode -eq 200) {
+ return @{ Version = $v; Minor = (($v -split '\.')[0..1] -join '.'); Url = $url }
+ }
+ } catch {} # no binary installer for this version (e.g. security-only) -> try next
+ }
+ } catch {}
+ return $null
+}
+
+$found = Find-Python
+if ($found) { Emit $found }
+
+# ----- 2) No usable Python found: install one ------------------------------
+# (Reached when there is no Python at all, OR only PlatformIO's bundled Python,
+# which lacks the tkinter the wizard's folder picker needs.)
+Say ''
+Say '[setup] No usable Python 3 (with tkinter) was found on this PC.'
+Say '[setup] Installing Python 3 automatically (one-time, ~1-2 min)...'
+Say ''
+
+$installed = $false
+
+# Discover the LATEST stable Python from python.org's release listing, so we
+# don't pin to an ageing version. Returns @{Version; Minor; Url} or $null.
+$latest = Get-LatestPython
+if ($latest) { Say "[setup] Latest stable Python is $($latest.Version)." }
+
+# a) Preferred: winget (built into Windows 10 1709+/11, no admin needed).
+# Target the latest minor line (e.g. Python.Python.3.14) so we don't pin
+# to an old one; fall back to a recent id if discovery failed.
+$winget = Get-Command winget -ErrorAction SilentlyContinue
+if ($winget) {
+ $wingetId = if ($latest) { "Python.Python.$($latest.Minor)" } else { 'Python.Python.3.13' }
+ Say "[setup] Using winget to install $wingetId ..."
+ try {
+ # Route winget's chatter to stderr so stdout stays a clean interpreter path.
+ & winget install -e --id $wingetId --scope user `
+ --accept-source-agreements --accept-package-agreements 2>&1 |
+ ForEach-Object { Say ([string]$_) }
+ if ($LASTEXITCODE -eq 0) { $installed = $true }
+ else { Say "[setup] winget exited with code $LASTEXITCODE; trying the python.org installer..." }
+ } catch {
+ Say "[setup] winget failed ($($_.Exception.Message)); trying the python.org installer..."
+ }
+}
+
+# b) Fallback: download the official python.org installer (latest) silently.
+if (-not $installed) {
+ $ver = if ($latest) { $latest.Version } else { '3.13.1' }
+ $url = if ($latest) { $latest.Url } else { "https://www.python.org/ftp/python/$ver/python-$ver-amd64.exe" }
+ $dest = Join-Path $env:TEMP "python-$ver-amd64.exe"
+ Say "[setup] Downloading the official Python $ver installer..."
+ try {
+ $ProgressPreference = 'SilentlyContinue'
+ Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing
+ Say '[setup] Running the installer silently (per-user)...'
+ $p = Start-Process -FilePath $dest -Wait -PassThru -ArgumentList `
+ '/quiet','InstallAllUsers=0','PrependPath=1','Include_launcher=1'
+ if ($p.ExitCode -eq 0) { $installed = $true }
+ else { Say "[setup] Installer exited with code $($p.ExitCode)." }
+ } catch {
+ Say "[setup] Could not download/run the python.org installer: $($_.Exception.Message)"
+ }
+}
+
+if (-not $installed) {
+ Say ''
+ Say '[error] Automatic install of Python 3 failed.'
+ Say ' Please install Python 3 from https://www.python.org/downloads/'
+ Say ' and tick "Add python.exe to PATH" during setup, then re-run.'
+ exit 1
+}
+
+# ----- 3) Re-resolve the just-installed interpreter (PATH not refreshed) ----
+$fresh = Find-FreshlyInstalled
+if (-not $fresh) {
+ # winget may have updated this process's environment block; try detection again.
+ $fresh = Find-Python
+}
+if ($fresh) {
+ Say '[setup] Python 3 installed successfully.'
+ # The installer adds Python to PATH, but already-open terminals (and new tabs
+ # of an existing one) keep the OLD PATH. Tell the user so `python` "not found"
+ # in a stale window isn't mistaken for a failed install. The wizard itself
+ # runs fine right now -- it uses the full path below, not PATH.
+ Say "[setup] To use the 'python' command yourself, open a NEW terminal window."
+ Emit $fresh
+}
+
+Say ''
+Say '[error] Python 3 was installed but could not be located automatically.'
+Say ' Please close this window and re-run -- it should be found now.'
+exit 1
diff --git a/tools/ensure-python.sh b/tools/ensure-python.sh
new file mode 100644
index 0000000..0d69ffe
--- /dev/null
+++ b/tools/ensure-python.sh
@@ -0,0 +1,173 @@
+#!/usr/bin/env bash
+# ===================================================================
+# ensure-python.sh - Detect a usable Python 3, installing one if
+# none is found, then print its path on stdout.
+#
+# Used by the Unix launcher (new-nrl-project.sh).
+# A brand-new student on macOS can double-click the .command launcher
+# and have it "just work": this script installs Python 3 via Homebrew
+# (if present) or the official python.org universal2 .pkg.
+#
+# Contract:
+# - stdout : exactly ONE line, the interpreter to run.
+# - stderr : all human-readable progress / status / error text.
+# - exit 0 : interpreter found/installed; its path is on stdout.
+# - exit 1 : no interpreter could be found or installed.
+# ===================================================================
+set -euo pipefail
+
+# Human-readable text goes to stderr so stdout stays a clean interpreter path.
+say() { printf '%s\n' "$*" >&2; }
+
+# Resolve a candidate to its real interpreter path IFF it is a Python 3 that
+# ALSO has tkinter (the wizard's folder picker needs it). Echoes the path, or
+# nothing (non-zero) when the candidate is missing / not Python 3 / no tkinter.
+#
+# Probed UNDER A TIMEOUT: on macOS, invoking python3 without the Xcode Command
+# Line Tools pops a GUI dialog and BLOCKS (the Windows Store-stub equivalent),
+# so a hanging probe could freeze the launcher. macOS ships no coreutils
+# `timeout`, so we background the probe (its stdout redirected straight to a
+# temp file) and poll it, killing anything that hasn't answered in 20s.
+resolve_usable() {
+ local exe="$1"; shift
+ local tmp out pid i=0
+ tmp="$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/nrl-ensurepy.$$")"
+ "$exe" "$@" -c 'import sys, tkinter; print(sys.executable)' >"$tmp" 2>/dev/null &
+ pid=$!
+ while kill -0 "$pid" 2>/dev/null; do
+ if [ "$i" -ge 20 ]; then
+ kill -TERM "$pid" 2>/dev/null || true
+ sleep 1
+ kill -KILL "$pid" 2>/dev/null || true
+ wait "$pid" 2>/dev/null || true
+ rm -f "$tmp"
+ return 1
+ fi
+ sleep 1
+ i=$((i + 1))
+ done
+ if wait "$pid"; then
+ out="$(tail -n1 "$tmp" 2>/dev/null || true)"
+ rm -f "$tmp"
+ [ -n "$out" ] && { printf '%s\n' "$out"; return 0; }
+ fi
+ rm -f "$tmp"
+ return 1
+}
+
+# Detect a "real" Python 3 WITH tkinter: python3 -> py -3. PlatformIO's bundled
+# Python is deliberately NOT accepted -- it lacks tkinter, so the folder picker
+# would break; when only that exists we install a real Python instead.
+find_python() {
+ if command -v python3 >/dev/null 2>&1; then
+ if p="$(resolve_usable python3)"; then printf '%s\n' "$p"; return 0; fi
+ fi
+ if command -v py >/dev/null 2>&1; then
+ if p="$(resolve_usable py -3)"; then printf '%s\n' "$p"; return 0; fi
+ fi
+ return 1
+}
+
+if pyexe="$(find_python)"; then
+ printf '%s\n' "$pyexe"
+ exit 0
+fi
+
+# Discover the latest STABLE Python from python.org whose macOS installer .pkg
+# actually exists (newest first), so we don't pin to an ageing version. Echoes
+# X.Y.Z, or nothing on failure (the caller then uses a hard-coded fallback).
+get_latest_python() {
+ local listing v
+ listing="$(curl -fsSL https://www.python.org/ftp/python/ 2>/dev/null || true)"
+ [ -z "$listing" ] && return 1
+ # X.Y.Z folders only, newest first; pre-releases (3.15.0a1) lack this exact shape.
+ for v in $(printf '%s\n' "$listing" \
+ | grep -oE 'href="[0-9]+\.[0-9]+\.[0-9]+/"' \
+ | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' \
+ | sort -t. -k1,1nr -k2,2nr -k3,3nr -u | head -n 12); do
+ if curl -fsI "https://www.python.org/ftp/python/${v}/python-${v}-macos11.pkg" >/dev/null 2>&1; then
+ printf '%s\n' "$v"; return 0
+ fi
+ done
+ return 1
+}
+
+# ----- No usable Python found: install one --------------------------------
+# (No Python at all, OR only PlatformIO's bundled Python without tkinter.)
+say ''
+say '[setup] No usable Python 3 (with tkinter) was found on this Mac.'
+
+uname_s="$(uname -s 2>/dev/null || echo unknown)"
+if [ "$uname_s" != "Darwin" ]; then
+ # Linux / other: keep the previous behavior (don't silently apt/dnf-install).
+ say '[error] Python 3 not found. Please install Python 3 and re-run.'
+ exit 1
+fi
+
+say '[setup] Installing Python 3 automatically (one-time)...'
+say ''
+installed=0
+
+# a) Preferred: Homebrew, if the student already has it. Install python-tk too
+# so tkinter (the folder picker) is present; then verify before accepting.
+if command -v brew >/dev/null 2>&1; then
+ say '[setup] Using Homebrew to install Python 3 (with tkinter) ...'
+ # >&2 so brew's progress doesn't pollute our single-line stdout contract.
+ if brew install python python-tk >&2; then
+ hash -r 2>/dev/null || true
+ if find_python >/dev/null 2>&1; then
+ installed=1
+ else
+ say '[setup] Homebrew Python lacks tkinter; falling back to the python.org installer...'
+ fi
+ fi
+fi
+
+# b) Fallback: the official python.org universal2 installer package (bundles tkinter).
+if [ "$installed" -ne 1 ]; then
+ ver="$(get_latest_python || true)"
+ [ -z "$ver" ] && ver='3.13.1' # last-resort fallback if discovery fails
+ url="https://www.python.org/ftp/python/${ver}/python-${ver}-macos11.pkg"
+ pkg="${TMPDIR:-/tmp}/python-${ver}-macos11.pkg"
+ say "[setup] Downloading the official Python ${ver} installer..."
+ if curl -fL -o "$pkg" "$url"; then
+ say '[setup] Installing (you may be asked for your Mac password)...'
+ # >&2 so `installer` chatter doesn't pollute our single-line stdout contract.
+ if sudo installer -pkg "$pkg" -target / >&2; then installed=1; fi
+ else
+ say '[setup] Could not download the python.org installer.'
+ fi
+fi
+
+if [ "$installed" -ne 1 ]; then
+ say ''
+ say '[error] Automatic install of Python 3 failed.'
+ say ' Please install Python 3 from https://www.python.org/downloads/ and re-run.'
+ exit 1
+fi
+
+# ----- Re-resolve the just-installed interpreter --------------------------
+# The python.org .pkg symlinks python3 into /usr/local/bin; brew into its prefix.
+hash -r 2>/dev/null || true
+if pyexe="$(find_python)"; then
+ say '[setup] Python 3 installed successfully.'
+ # Already-open terminals keep the OLD PATH, so `python3` may look "not found"
+ # there even though the install worked. The wizard runs fine now (full path).
+ say "[setup] To use the 'python3' command yourself, open a NEW terminal window."
+ printf '%s\n' "$pyexe"
+ exit 0
+fi
+for cand in /usr/local/bin/python3 /opt/homebrew/bin/python3 \
+ /Library/Frameworks/Python.framework/Versions/Current/bin/python3; do
+ if [ -x "$cand" ] && p="$(resolve_usable "$cand")"; then
+ say '[setup] Python 3 installed successfully.'
+ say "[setup] To use the 'python3' command yourself, open a NEW terminal window."
+ printf '%s\n' "$p"
+ exit 0
+ fi
+done
+
+say ''
+say '[error] Python 3 was installed but could not be located automatically.'
+say ' Please close this window and re-run -- it should be found now.'
+exit 1
diff --git a/tools/new-nrl-opmode.bat b/tools/new-nrl-opmode.bat
new file mode 100755
index 0000000..c2f37ce
--- /dev/null
+++ b/tools/new-nrl-opmode.bat
@@ -0,0 +1,29 @@
+@echo off
+rem ===================================================================
+rem NRL - Create a New OpMode (double-click launcher, Windows)
+rem Scaffolds a robot OpMode from a minimal template, then opens it.
+rem ===================================================================
+setlocal
+title NRL - Create a New OpMode
+
+rem This .bat lives in <repo>\tools\ ; the generator sits next to it.
+set "SCRIPT=%~dp0nrl_new_opmode.py"
+
+rem Find a usable Python 3 (real py/python); if none is found, ensure-python.ps1
+rem installs one automatically and prints its path.
+set "PYEXE="
+for /f "usebackq delims=" %%i in (`powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ensure-python.ps1"`) do set "PYEXE=%%i"
+if not defined PYEXE goto no_python
+"%PYEXE%" "%SCRIPT%" --open %*
+goto end
+
+:no_python
+echo.
+echo [error] Python 3 was not found and could not be installed automatically.
+echo Install Python 3 from https://www.python.org/downloads/ and re-run,
+echo ticking "Add python.exe to PATH" during setup.
+
+:end
+echo.
+if not defined NRL_NO_PAUSE pause
+endlocal
diff --git a/tools/new-nrl-opmode.sh b/tools/new-nrl-opmode.sh
new file mode 100644
index 0000000..6fb5400
--- /dev/null
+++ b/tools/new-nrl-opmode.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# ===================================================================
+# NRL - Create a New OpMode (launcher, macOS / Linux)
+# Scaffolds a robot OpMode from a minimal template, then opens it.
+# Usage: bash tools/new-nrl-opmode.sh (or chmod +x and run it)
+# ===================================================================
+set -euo pipefail
+
+here="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
+script="$here/nrl_new_opmode.py"
+
+# Find a usable Python 3; if none is found, ensure-python.sh installs one
+# automatically and prints its path.
+pyexe="$(bash "$here/ensure-python.sh")" || {
+ echo "[error] Python 3 was not found and could not be installed automatically." >&2
+ echo " Install Python 3 from https://www.python.org/downloads/ and re-run." >&2
+ exit 1
+}
+exec "$pyexe" "$script" --open "$@"
diff --git a/tools/nrl_new_opmode.py b/tools/nrl_new_opmode.py
new file mode 100644
index 0000000..113fe54
--- /dev/null
+++ b/tools/nrl_new_opmode.py
@@ -0,0 +1,307 @@
+#!/usr/bin/env python3
+"""
+NRL — Create a New OpMode
+=========================
+
+Scaffolds a fresh robot OpMode from a minimal template so a student never
+starts from a blank file. Writes <Name>.cpp into RobotFirmware/opmodes/ with
+empty init()/loop()/stop() overrides and the REGISTER_OPMODE line already
+filled in (that line is what makes the OpMode show up on the Controller menu).
+
+This is the "guided new file" companion to the in-editor snippets
+(type `nrlteleop` / `nrlauto` + Tab inside any opmodes/*.cpp).
+
+Run it
+------
+Interactive (recommended): py -3 tools/nrl_new_opmode.py
+Or via VS Code: Ctrl+Shift+P -> Tasks: Run Task -> "NRL: New OpMode"
+Non-interactive: py -3 tools/nrl_new_opmode.py --name Drive --type teleop --yes
+
+Requires Python 3.7+ (stdlib only). PlatformIO already ships a Python.
+"""
+
+import argparse
+import os
+import re
+import shutil
+import sys
+from pathlib import Path
+
+WORKSPACE_FILE = "NRL_Update_1.code-workspace"
+
+# A valid C++ identifier (also used as the file name). Must start with a
+# letter, then letters/digits/underscores — no spaces or punctuation.
+_IDENT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
+
+
+# --------------------------------------------------------------------------- #
+# Validation / prompting
+# --------------------------------------------------------------------------- #
+def valid_opmode_name(name: str):
+ """Return (ok, message). Must be a legal C++ class/file identifier."""
+ name = name.strip()
+ if not name:
+ return False, "OpMode name cannot be empty."
+ if not _IDENT_RE.match(name):
+ return False, ("OpMode name must start with a letter and contain only "
+ "letters, numbers, or underscores (no spaces).")
+ if len(name) > 40:
+ return False, "OpMode name must be 40 characters or fewer."
+ return True, ""
+
+
+def valid_type(value: str):
+ """Return (ok, normalized, message). Accepts teleop/auto (any case)."""
+ v = str(value).strip().lower()
+ if v in ("teleop", "tele", "t"):
+ return True, "TELEOP", ""
+ if v in ("auto", "a"):
+ return True, "AUTO", ""
+ return False, "", "Type must be 'teleop' or 'auto'."
+
+
+def _interactive() -> bool:
+ return sys.stdin is not None and sys.stdin.isatty()
+
+
+def ask(prompt: str, default: str = None, validate=None) -> str:
+ """Prompt until a valid answer is given. `validate` returns (ok, ..., message)."""
+ suffix = f" [{default}]" if default not in (None, "") else ""
+ while True:
+ try:
+ raw = input(f"{prompt}{suffix}: ").strip()
+ except (EOFError, KeyboardInterrupt):
+ print("\nCancelled.")
+ sys.exit(1)
+ if not raw and default is not None:
+ raw = default
+ if validate is not None:
+ result = validate(raw)
+ ok, message = (result[0], result[-1]) if isinstance(result, tuple) else (bool(result), "")
+ if not ok:
+ print(f" ! {message}")
+ continue
+ elif not raw:
+ print(" ! A value is required.")
+ continue
+ return raw
+
+
+# --------------------------------------------------------------------------- #
+# Template
+# --------------------------------------------------------------------------- #
+def render_opmode(name: str, optype: str, display: str) -> str:
+ """Minimal skeleton — empty init/loop/stop + REGISTER_OPMODE. Mirrors the
+ nrlteleop/nrlauto editor snippets so both paths produce the same shape."""
+ if optype == "AUTO":
+ loop_comment = "// Runs at 100 Hz for ~60 s — telemetry and sensor reads go here."
+ # AUTO routines belong in start(), not loop(): queued there they run
+ # exactly once instead of restarting 100 times a second.
+ start_block = (
+ " void start() override {\n"
+ " // Runs once when the match starts — queue your routine\n"
+ " // with runAction(...) here.\n"
+ " }\n\n"
+ )
+ else:
+ # The ownership rule belongs here, not only in NRLOpMode.h: the clash it
+ # prevents (loop() silently overwriting an action) only shows up in
+ # TELEOP, where loop() drives hardware every tick.
+ loop_comment = (
+ "// Runs at 100 Hz until STOP — read gamepad1, drive motors here.\n"
+ " //\n"
+ " // Control each part in ONE place: loop() or an action, not\n"
+ " // both. Actions run before loop() each tick, so loop() would\n"
+ " // overwrite them. To share one part, step aside while a\n"
+ " // sequence plays: if (!isActionRunning()) { ... }"
+ )
+ start_block = ""
+ return f"""#include "NRL.h"
+
+// Declare your hardware here (file-scope), e.g.:
+// static HexaDCMotor leftMotor {{{{ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM }}}};
+
+class {name} : public NRLOpMode {{
+public:
+ void init() override {{
+ // Runs once when INIT is pressed — begin() your hardware here.
+ }}
+
+{start_block} void loop() override {{
+ {loop_comment}
+ }}
+
+ void stop() override {{
+ // Runs once on STOP — stop your motors/servos here.
+ }}
+}};
+
+REGISTER_OPMODE({name}, "{display}", {optype});
+"""
+
+
+# --------------------------------------------------------------------------- #
+# VS Code open (mirrors nrl_new_project.find_vscode)
+# --------------------------------------------------------------------------- #
+def find_vscode() -> str:
+ """Locate the real VS Code CLI, preferring a genuine VS Code install over
+ look-alikes (Cursor, VSCodium). Override with the NRL_VSCODE env var."""
+ candidates = []
+ override = os.environ.get("NRL_VSCODE")
+ if override:
+ candidates.append(override)
+
+ if sys.platform == "win32":
+ for base in (os.environ.get("LOCALAPPDATA", ""),
+ os.environ.get("ProgramFiles", ""),
+ os.environ.get("ProgramFiles(x86)", "")):
+ if base:
+ candidates.append(os.path.join(base, "Programs", "Microsoft VS Code", "bin", "code.cmd"))
+ candidates.append(os.path.join(base, "Microsoft VS Code", "bin", "code.cmd"))
+ elif sys.platform == "darwin":
+ candidates += [
+ "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code",
+ os.path.expanduser("~/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"),
+ ]
+ else:
+ candidates += ["/usr/bin/code", "/usr/local/bin/code",
+ "/usr/share/code/bin/code", "/snap/bin/code"]
+
+ for name in ("code", "code.cmd", "code.exe"):
+ found = shutil.which(name)
+ if found:
+ candidates.append(found)
+
+ for c in candidates:
+ if c and os.path.exists(c) and "cursor" not in c.lower():
+ return c
+ return ""
+
+
+def try_open_in_vscode(path: Path) -> bool:
+ """Open (and focus) the new file in VS Code, reusing the current window."""
+ import subprocess
+ code = find_vscode()
+ if not code:
+ return False
+ try:
+ if sys.platform == "win32":
+ subprocess.Popen(f'"{code}" -r "{path}"', shell=True)
+ else:
+ subprocess.Popen([code, "-r", str(path)])
+ return True
+ except OSError:
+ return False
+
+
+# --------------------------------------------------------------------------- #
+# Main
+# --------------------------------------------------------------------------- #
+def parse_args(argv):
+ p = argparse.ArgumentParser(
+ prog="nrl_new_opmode",
+ description="Create a new NRL robot OpMode from a minimal template.",
+ )
+ p.add_argument("--name", help="OpMode name (also the class and file name).")
+ p.add_argument("--type", help="OpMode type: teleop or auto.")
+ p.add_argument("--display", help="Name shown on the Controller (defaults to the OpMode name).")
+ p.add_argument("--open", action="store_true",
+ help="Open the new file in VS Code when done.")
+ p.add_argument("-y", "--yes", action="store_true",
+ help="Skip the confirmation prompt.")
+ return p.parse_args(argv)
+
+
+def resolve_repo_root() -> Path:
+ repo_root = Path(__file__).resolve().parent.parent
+ if not (repo_root / "RobotFirmware" / "opmodes").is_dir():
+ sys.exit(
+ f"[error] Can't find RobotFirmware/opmodes under {repo_root}. "
+ "Run this script from inside the NRL project (tools/nrl_new_opmode.py)."
+ )
+ return repo_root
+
+
+def main(argv=None):
+ args = parse_args(sys.argv[1:] if argv is None else argv)
+ repo_root = resolve_repo_root()
+ interactive = _interactive()
+ can_prompt = interactive and not args.yes
+
+ print("=" * 60)
+ print(" NRL · Create a New OpMode")
+ print("=" * 60)
+
+ # --- Name ---
+ if args.name is not None:
+ ok, msg = valid_opmode_name(args.name)
+ if not ok:
+ sys.exit(f"[error] {msg}")
+ name = args.name.strip()
+ elif can_prompt:
+ name = ask("OpMode name (e.g. DriveStraight)", validate=valid_opmode_name).strip()
+ else:
+ sys.exit("[error] --name is required (pass --name, or run in a terminal without --yes).")
+
+ # --- Type ---
+ if args.type is not None:
+ ok, optype, msg = valid_type(args.type)
+ if not ok:
+ sys.exit(f"[error] {msg}")
+ elif can_prompt:
+ optype = valid_type(ask("Type (teleop/auto)", default="teleop", validate=valid_type))[1]
+ else:
+ sys.exit("[error] --type is required (pass --type teleop|auto, or run without --yes).")
+
+ # --- Display name ---
+ if args.display is not None and args.display.strip():
+ display = args.display.strip()
+ elif can_prompt:
+ display = ask("Controller display name", default=name).strip()
+ else:
+ display = name
+ # Keep the display label clean for the firmware C-string literal.
+ display = display.replace('"', "'")
+
+ target = repo_root / "RobotFirmware" / "opmodes" / f"{name}.cpp"
+
+ # --- Summary ---
+ print("\n" + "-" * 60)
+ print(f" OpMode name : {name}")
+ print(f" Type : {optype}")
+ print(f" Display name : {display} (shown on the Controller)")
+ print(f" File : {target}")
+ print("-" * 60)
+
+ if target.exists():
+ sys.exit(f"[error] {target.name} already exists. Choose a different name "
+ "(or delete the old file first).")
+
+ if not args.yes:
+ if not interactive:
+ sys.exit("[error] Refusing to create without confirmation; pass --yes.")
+ if ask("Create this OpMode? (y/n)", default="y").strip().lower() not in ("y", "yes"):
+ print("Cancelled.")
+ return 1
+
+ # --- Write ---
+ try:
+ target.write_text(render_opmode(name, optype, display), encoding="utf-8")
+ except OSError as exc:
+ sys.exit(f"[error] Could not write {target}: {exc}")
+
+ print("\n[ done ] OpMode created.\n")
+ print("Next steps:")
+ print(f" 1. Edit {target}")
+ print(" 2. Click Build/Upload in PlatformIO to flash it to the robot")
+ print(f" 3. On the Controller, pick \"{display}\" from the menu\n")
+
+ if args.open and not try_open_in_vscode(target):
+ print(f"(VS Code not found — open {target} manually,")
+ print(" or set the NRL_VSCODE environment variable to your code.cmd path.)")
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())