diff --git a/.gitignore b/.gitignore index e462d2ae..d4de3eb1 100644 --- a/.gitignore +++ b/.gitignore @@ -164,3 +164,5 @@ vscode-plugin # fastled binary before `maturin build`. Bundled into the wheel as # -.data/scripts/. /wheel-data/ +.clud/loop/ +.claude/worktrees/ diff --git a/Cargo.lock b/Cargo.lock index 22510de6..a6932d2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -716,6 +716,30 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "ctcb-core" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d666d682b69add1b1bea317cb3184018f21a0ff95f3a9d1b44887bd5b01961" +dependencies = [ + "anyhow", + "serde", + "serde_json", + "thiserror 2.0.18", +] + +[[package]] +name = "ctcb-manifest" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97c47fc9cd2017787aad53c7a11fb8529291cadb369dc15ad041eb81fbc06221" +dependencies = [ + "anyhow", + "ctcb-core", + "serde", + "serde_json", +] + [[package]] name = "ctor" version = "0.2.9" @@ -1035,9 +1059,11 @@ dependencies = [ "axum", "clap", "crossterm", + "ctcb-manifest", "dirs 5.0.1", "flate2", "notify", + "pyo3", "reqwest 0.12.28", "serde", "serde_json", @@ -1056,7 +1082,11 @@ dependencies = [ name = "fastled-py" version = "2.0.7" dependencies = [ + "fastled-cli", "pyo3", + "serde_json", + "strsim", + "zip", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b8d61ff4..1be7bf9d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ flate2 = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" anyhow = "1" +ctcb-manifest = "0.4.1" dirs = "5" strsim = "0.11" crossterm = "0.28" diff --git a/crates/fastled-cli/Cargo.toml b/crates/fastled-cli/Cargo.toml index 17fdf79f..361ca331 100644 --- a/crates/fastled-cli/Cargo.toml +++ b/crates/fastled-cli/Cargo.toml @@ -18,6 +18,7 @@ path = "src/main.rs" [dependencies] clap = { workspace = true } +pyo3 = { workspace = true, features = ["auto-initialize"] } notify = { workspace = true } sha2 = { workspace = true } reqwest = { workspace = true } @@ -28,6 +29,7 @@ flate2 = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } anyhow = { workspace = true } +ctcb-manifest = { workspace = true } strsim = { workspace = true } crossterm = { workspace = true } tokio = { workspace = true } diff --git a/crates/fastled-cli/src/build.rs b/crates/fastled-cli/src/build.rs index 4b1eec97..20377ad3 100644 --- a/crates/fastled-cli/src/build.rs +++ b/crates/fastled-cli/src/build.rs @@ -1,24 +1,14 @@ //! Build orchestration for WASM compilation. //! -//! Ports the high-level build request / result abstraction from -//! `build_types.py` and `build_service.py` to Rust. -//! -//! The actual WASM compilation remains in Python. [`run_build`] delegates -//! to `python -m fastled.app --just-compile` as a subprocess, keeping the -//! Rust layer as a thin orchestration shell. -//! -//! This module is included as a library component; the CLI main loop will -//! integrate it in a later phase for captured-output builds. +//! The Rust CLI now drives the Python build service in-process through PyO3 +//! instead of shelling out through `python -m fastled.app`. -// The CLI currently uses `run_python_compile()` in main.rs (inherited stdio). -// This module provides a captured-output alternative for future use. -#![allow(dead_code)] - -use std::path::PathBuf; -use std::process::Command; +use std::path::{Path, PathBuf}; use std::time::Instant; use anyhow::{Context, Result}; +use pyo3::prelude::*; +use pyo3::types::{PyDict, PyModule}; // --------------------------------------------------------------------------- // Types @@ -33,22 +23,18 @@ pub enum BuildMode { } impl BuildMode { - /// Return the CLI flag string that the Python CLI expects. - pub fn as_flag(&self) -> &'static str { + /// Return the Python enum member name. + pub fn py_member_name(&self) -> &'static str { match self { - BuildMode::Quick => "--quick", - BuildMode::Debug => "--debug", - BuildMode::Release => "--release", + BuildMode::Quick => "QUICK", + BuildMode::Debug => "DEBUG", + BuildMode::Release => "RELEASE", } } /// Return a human-readable label. pub fn label(&self) -> &'static str { - match self { - BuildMode::Quick => "QUICK", - BuildMode::Debug => "DEBUG", - BuildMode::Release => "RELEASE", - } + self.py_member_name() } } @@ -80,71 +66,194 @@ impl BuildRequest { } } -/// Mirrors `BuildResult` from `build_types.py`. +/// Mirrors the useful fields returned from `build_types.BuildResult`. #[derive(Debug)] pub struct BuildResult { /// Whether the compilation succeeded. pub success: bool, /// Directory that received the compiled artefacts. pub output_dir: PathBuf, - /// Wall-clock seconds spent in the Python subprocess. + /// Wall-clock seconds spent inside the in-process Python build call. pub duration_secs: f64, - /// Combined stdout + stderr from the Python subprocess. + /// Python-side sketch compilation time. + pub sketch_time_secs: f64, + /// Strategy selected by the build service (`cold` or `incremental`). + pub strategy: String, + /// Final summary line from the Python build result. pub output: String, } // --------------------------------------------------------------------------- -// Subprocess helper +// Python bridge helpers // --------------------------------------------------------------------------- -/// Locate a Python executable. -/// -/// Priority order (mirrors `find_python` in `main.rs`): -/// 1. `VIRTUAL_ENV/Scripts/python.exe` (Windows) or `VIRTUAL_ENV/bin/python` -/// 2. `python` on PATH -/// 3. `python3` on PATH -fn find_python() -> String { - if let Ok(venv) = std::env::var("VIRTUAL_ENV") { - #[cfg(windows)] - let candidate = format!("{}/Scripts/python.exe", venv); - #[cfg(not(windows))] - let candidate = format!("{}/bin/python", venv); - - if std::path::Path::new(&candidate).exists() { - return candidate; - } +fn workspace_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(Path::parent) + .map(Path::to_path_buf) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR"))) +} + +fn workspace_python_source() -> Option { + let src_dir = workspace_root().join("src"); + src_dir.is_dir().then_some(src_dir) +} + +fn py_path(py: Python<'_>, path: &Path) -> PyResult> { + let pathlib = PyModule::import(py, "pathlib")?; + let cls = pathlib.getattr("Path")?; + Ok(cls + .call1((path.to_string_lossy().as_ref(),))? + .into_any() + .unbind()) +} + +fn py_fspath(value: &Bound<'_, PyAny>) -> PyResult { + let py = value.py(); + let os = PyModule::import(py, "os")?; + let fspath = os.getattr("fspath")?; + let path_value = fspath.call1((value,))?; + let path_str: String = path_value.extract()?; + Ok(PathBuf::from(path_str)) +} + +fn ensure_workspace_src_on_sys_path(py: Python<'_>) -> PyResult<()> { + let Some(src_dir) = workspace_python_source() else { + return Ok(()); + }; + let src_text = src_dir.to_string_lossy().into_owned(); + let sys = PyModule::import(py, "sys")?; + let sys_path = sys.getattr("path")?; + let contains: bool = sys_path + .call_method1("__contains__", (src_text.as_str(),))? + .extract()?; + if !contains { + sys_path.call_method1("insert", (0, src_text.as_str()))?; } + Ok(()) +} + +fn run_build_embedded(request: &BuildRequest) -> Result { + let start = Instant::now(); + Python::with_gil(|py| -> Result { + ensure_workspace_src_on_sys_path(py) + .context("failed to add workspace Python sources to sys.path")?; + + let build_service_mod = PyModule::import(py, "fastled.build_service") + .context("import fastled.build_service")?; + let build_types_mod = + PyModule::import(py, "fastled.build_types").context("import fastled.build_types")?; + let types_mod = PyModule::import(py, "fastled.types").context("import fastled.types")?; + + let build_mode = types_mod + .getattr("BuildMode") + .context("BuildMode enum missing")? + .getattr(request.build_mode.py_member_name()) + .with_context(|| { + format!("BuildMode.{} missing", request.build_mode.py_member_name()) + })?; + + let request_kwargs = PyDict::new(py); + request_kwargs + .set_item("sketch_dir", py_path(py, &request.sketch_dir)?) + .context("set sketch_dir")?; + request_kwargs + .set_item("build_mode", &build_mode) + .context("set build_mode")?; + request_kwargs + .set_item("profile", request.profile) + .context("set profile")?; + match &request.fastled_path { + Some(path) => request_kwargs + .set_item("fastled_path", py_path(py, path)?) + .context("set fastled_path")?, + None => request_kwargs + .set_item("fastled_path", py.None()) + .context("set fastled_path none")?, + } + request_kwargs + .set_item("force_clean", request.force_clean) + .context("set force_clean")?; + + let build_request = build_types_mod + .getattr("BuildRequest") + .context("BuildRequest class missing")? + .call((), Some(&request_kwargs)) + .context("construct BuildRequest")?; + + let service = build_service_mod + .getattr("BuildService") + .context("BuildService class missing")? + .call0() + .context("construct BuildService")?; + + let result = service + .call_method1("build", (build_request,)) + .context("BuildService.build failed")?; + + let success: bool = result + .getattr("success") + .context("missing build result success")? + .extract() + .context("extract build success")?; + let output: String = result + .getattr("stdout") + .context("missing build result stdout")? + .extract() + .context("extract build stdout")?; + let strategy: String = result + .getattr("strategy") + .context("missing build strategy")? + .extract() + .context("extract build strategy")?; + let sketch_time_secs: f64 = result + .getattr("sketch_time") + .context("missing sketch_time")? + .extract() + .context("extract sketch_time")?; + let output_dir = py_fspath(&result.getattr("output_dir").context("missing output_dir")?) + .context("extract output_dir")?; + + Ok(BuildResult { + success, + output_dir, + duration_secs: start.elapsed().as_secs_f64(), + sketch_time_secs, + strategy, + output, + }) + }) +} - if Command::new("python") +fn run_build_subprocess(request: &BuildRequest, reason: &str) -> Result { + use std::process::Command; + + let python = if Command::new("python") .args(["--version"]) .output() .map(|o| o.status.success()) .unwrap_or(false) { - return "python".to_string(); - } - - "python3".to_string() -} - -// --------------------------------------------------------------------------- -// Public API -// --------------------------------------------------------------------------- + "python" + } else { + "python3" + }; -/// Run a WASM build by calling the Python CLI as a subprocess. -/// -/// Delegates to `python -m fastled.app --just-compile [flags]`. -/// The actual Emscripten / WASM compilation stays entirely in Python; this -/// function only constructs the command, measures elapsed time, and wraps the -/// result. -pub fn run_build(request: &BuildRequest) -> Result { - let python = find_python(); let output_dir = request.output_dir(); - - let mut cmd = Command::new(&python); + let mut cmd = Command::new(python); cmd.args(["-m", "fastled.app", "--just-compile"]); cmd.arg(&request.sketch_dir); - cmd.arg(request.build_mode.as_flag()); + + match request.build_mode { + BuildMode::Quick => {} + BuildMode::Debug => { + cmd.arg("--debug"); + } + BuildMode::Release => { + cmd.arg("--release"); + } + } if request.profile { cmd.arg("--profile"); @@ -153,7 +262,11 @@ pub fn run_build(request: &BuildRequest) -> Result { cmd.arg("--fastled-path"); cmd.arg(fp); } + if request.force_clean { + cmd.arg("--purge"); + } + eprintln!("fastled: falling back to subprocess build path: {reason}"); let start = Instant::now(); let output = cmd .output() @@ -174,10 +287,25 @@ pub fn run_build(request: &BuildRequest) -> Result { success: output.status.success(), output_dir, duration_secs, + sketch_time_secs: duration_secs, + strategy: "unknown".to_string(), output: combined, }) } +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// Run a WASM build through the Python build service without the legacy +/// `fastled.app` CLI trampoline. +pub fn run_build(request: &BuildRequest) -> Result { + match run_build_embedded(request) { + Ok(result) => Ok(result), + Err(err) => run_build_subprocess(request, &format!("{err:#}")), + } +} + // --------------------------------------------------------------------------- // Unit tests // --------------------------------------------------------------------------- @@ -185,17 +313,16 @@ pub fn run_build(request: &BuildRequest) -> Result { #[cfg(test)] mod tests { use super::*; - use std::path::PathBuf; // ------------------------------------------------------------------ // BuildMode // ------------------------------------------------------------------ #[test] - fn test_build_mode_flags() { - assert_eq!(BuildMode::Quick.as_flag(), "--quick"); - assert_eq!(BuildMode::Debug.as_flag(), "--debug"); - assert_eq!(BuildMode::Release.as_flag(), "--release"); + fn test_build_mode_member_names() { + assert_eq!(BuildMode::Quick.py_member_name(), "QUICK"); + assert_eq!(BuildMode::Debug.py_member_name(), "DEBUG"); + assert_eq!(BuildMode::Release.py_member_name(), "RELEASE"); } #[test] @@ -273,6 +400,13 @@ mod tests { assert_eq!(req.build_mode, BuildMode::Release); } + #[test] + fn test_workspace_python_source_points_at_repo_src() { + let src_dir = workspace_python_source().expect("workspace src dir"); + assert!(src_dir.ends_with("src")); + assert!(src_dir.is_dir()); + } + // ------------------------------------------------------------------ // BuildResult // ------------------------------------------------------------------ @@ -283,11 +417,15 @@ mod tests { success: true, output_dir: PathBuf::from("/tmp/my_sketch/fastled_js"), duration_secs: 2.5, + sketch_time_secs: 1.75, + strategy: "cold".to_string(), output: "Build OK".to_string(), }; assert!(result.success); assert_eq!(result.duration_secs, 2.5); + assert_eq!(result.sketch_time_secs, 1.75); + assert_eq!(result.strategy, "cold"); assert_eq!(result.output, "Build OK"); } } diff --git a/crates/fastled-cli/src/install.rs b/crates/fastled-cli/src/install.rs index 4c55764b..c9d805c0 100644 --- a/crates/fastled-cli/src/install.rs +++ b/crates/fastled-cli/src/install.rs @@ -8,94 +8,14 @@ use std::fs; use std::io::{BufReader, BufWriter, Write}; use std::path::{Path, PathBuf}; +use std::process::Command; use anyhow::{bail, Context, Result}; -use serde::Deserialize; -use std::collections::BTreeMap; +use ctcb_manifest::{PartRef, PlatformManifest}; +use serde_json::{json, Value}; use crate::archive; -// --------------------------------------------------------------------------- -// Manifest schema -// --------------------------------------------------------------------------- -// -// The clang-tool-chain-bins emscripten manifest is served in two different -// shapes depending on platform. Linux/macOS nests version entries under a -// `versions` key: -// -// { "latest": "4.0.21", -// "versions": { "4.0.21": { "href": "...", "sha256": "...", "parts": [...] }, ... } } -// -// Windows inlines version entries at the top level alongside `latest`: -// -// { "latest": "4.0.19", -// "4.0.19": { "href": "...", "sha256": "...", "parts": [...] } } -// -// Our `PlatformManifest` accepts both via a custom Deserialize. - -#[derive(Debug, Deserialize)] -struct PartRef { - href: String, - sha256: String, -} - -#[derive(Debug, Deserialize)] -struct VersionInfo { - href: String, - sha256: String, - parts: Option>, -} - -#[derive(Debug)] -struct PlatformManifest { - latest: String, - versions: BTreeMap, -} - -impl<'de> Deserialize<'de> for PlatformManifest { - fn deserialize>(deserializer: D) -> Result { - let raw: serde_json::Value = Deserialize::deserialize(deserializer)?; - let obj = raw - .as_object() - .ok_or_else(|| serde::de::Error::custom("expected JSON object at manifest root"))?; - - let latest = obj - .get("latest") - .and_then(|v| v.as_str()) - .ok_or_else(|| serde::de::Error::custom("missing 'latest' key"))? - .to_string(); - - let mut versions = BTreeMap::new(); - - // Prefer the nested-`versions` shape (Linux / macOS manifests) when - // present. Fall back to top-level inline entries (Windows). - if let Some(serde_json::Value::Object(versions_obj)) = obj.get("versions") { - for (key, value) in versions_obj { - let info: VersionInfo = serde_json::from_value(value.clone()).map_err(|e| { - serde::de::Error::custom(format!( - "bad version entry '{key}' (nested versions): {e}" - )) - })?; - versions.insert(key.clone(), info); - } - } else { - for (key, value) in obj { - if key == "latest" { - continue; - } - let info: VersionInfo = serde_json::from_value(value.clone()).map_err(|e| { - serde::de::Error::custom(format!( - "bad version entry '{key}' (inline versions): {e}" - )) - })?; - versions.insert(key.clone(), info); - } - } - - Ok(PlatformManifest { latest, versions }) - } -} - const EMSCRIPTEN_MANIFEST_BASE_URL: &str = "https://raw.githubusercontent.com/zackees/clang-tool-chain-bins/main/assets/emscripten"; @@ -254,21 +174,6 @@ pub fn ensure_emscripten_installed() -> Result { fs::create_dir_all(&staging)?; archive::extract_tar_zst(&archive_path, &staging)?; - // Restore execute bits on Unix — some tar implementations (and the - // umask of the extracting process) strip the +x bit from binaries - // under bin/, emscripten/, and libexec/. emcc.py then hits - // PermissionError when it tries to exec clang. Mirror the - // belt-and-suspenders chmod from the previous Python implementation. - #[cfg(unix)] - { - for subdir in ["bin", "emscripten", "libexec"] { - let dir = staging.join(subdir); - if dir.is_dir() { - add_executable_bits_recursive(&dir)?; - } - } - } - fs::write(staging.join("done.txt"), "ok\n")?; if install_dir.exists() { @@ -281,29 +186,6 @@ pub fn ensure_emscripten_installed() -> Result { Ok(install_dir) } -/// Recursively chmod every file under `dir` to include +x for user / group / -/// other (no-op on Windows). Used right after emscripten extraction so the -/// shipped binaries (clang, wasm-ld, etc.) are actually executable. -#[cfg(unix)] -fn add_executable_bits_recursive(dir: &Path) -> Result<()> { - use std::os::unix::fs::PermissionsExt; - for entry in fs::read_dir(dir).with_context(|| format!("read_dir {}", dir.display()))? { - let entry = entry?; - let path = entry.path(); - let file_type = entry.file_type()?; - if file_type.is_dir() { - add_executable_bits_recursive(&path)?; - } else if file_type.is_file() { - let mode = entry.metadata()?.permissions().mode(); - let new_mode = mode | 0o111; - if new_mode != mode { - fs::set_permissions(&path, fs::Permissions::from_mode(new_mode))?; - } - } - } - Ok(()) -} - // --------------------------------------------------------------------------- // esbuild // --------------------------------------------------------------------------- @@ -609,3 +491,691 @@ fn find_zip_start(bytes: &[u8]) -> Option { .position(|w| w == local) .or_else(|| bytes.windows(4).position(|w| w == end)) } + +// --------------------------------------------------------------------------- +// User-facing install flow +// --------------------------------------------------------------------------- + +const DEFAULT_INSTALL_EXAMPLE: &str = "wasm"; +const AUTO_DEBUG_VSIX_URL: &str = + "https://github.com/zackees/vscode-auto-debug/releases/latest/download/auto-debug.vsix"; + +#[derive(Clone, Copy, Debug)] +pub struct InstallOptions { + pub dry_run: bool, + pub no_interactive: bool, +} + +#[derive(Clone, Copy, Debug)] +pub struct InstallOutcome { + pub launch_after: bool, +} + +fn prompt_yes_no(prompt: &str, default: bool) -> Result { + let default_hint = if default { "[Y/n]" } else { "[y/N]" }; + print!("{prompt} {default_hint} "); + std::io::stdout().flush().context("flush prompt")?; + + let mut input = String::new(); + std::io::stdin() + .read_line(&mut input) + .context("read prompt response")?; + let trimmed = input.trim().to_ascii_lowercase(); + if trimmed.is_empty() { + return Ok(default); + } + Ok(matches!(trimmed.as_str(), "y" | "yes")) +} + +fn command_exists(command: &str) -> bool { + Command::new(command) + .arg("--version") + .output() + .map(|output| output.status.success()) + .unwrap_or(false) +} + +fn detect_supported_ide() -> Option<(&'static str, &'static str)> { + if command_exists("code") { + Some(("code", "VSCode")) + } else if command_exists("cursor") { + Some(("cursor", "Cursor")) + } else { + None + } +} + +fn find_vscode_project_upward(max_levels: usize) -> Option { + let mut current = std::env::current_dir().ok()?; + for _ in 0..max_levels { + let parent = current.parent()?.to_path_buf(); + if parent == current { + break; + } + current = parent; + if current.join(".vscode").is_dir() { + return Some(current); + } + } + None +} + +fn generate_vscode_project() -> Result<()> { + let vscode_dir = std::env::current_dir() + .context("current dir")? + .join(".vscode"); + fs::create_dir_all(&vscode_dir).with_context(|| format!("create {}", vscode_dir.display()))?; + println!("Created .vscode directory at {}", vscode_dir.display()); + Ok(()) +} + +fn validate_vscode_project(no_interactive: bool) -> Result<()> { + let current_dir = std::env::current_dir().context("current dir")?; + if current_dir.join(".vscode").is_dir() { + return Ok(()); + } + + if let Some(parent_path) = find_vscode_project_upward(5) { + if no_interactive { + bail!( + "No .vscode directory found in current directory.\nFound .vscode in parent: {}\nIn non-interactive mode, cannot change directory.\nPlease cd there and run the command again.", + parent_path.display() + ); + } + let use_parent = prompt_yes_no( + &format!( + "Found a .vscode project in {}. Install there?", + parent_path.display() + ), + true, + )?; + if use_parent { + std::env::set_current_dir(&parent_path) + .with_context(|| format!("cd {}", parent_path.display()))?; + return Ok(()); + } + } + + if detect_supported_ide().is_none() { + bail!("No supported IDE found (VSCode or Cursor). Please install VSCode or Cursor first."); + } + + if no_interactive { + bail!( + "No .vscode directory found in current directory or parent directories.\nIn non-interactive mode, cannot create a new project.\nPlease create a .vscode directory or run without --no-interactive." + ); + } + + println!("No .vscode directory found in current directory or parent directories."); + if prompt_yes_no( + "Would you like to generate a VSCode project with FastLED configuration?", + true, + )? { + generate_vscode_project()?; + return Ok(()); + } + + bail!("installation cancelled"); +} + +fn detect_fastled_project() -> bool { + let Ok(cwd) = std::env::current_dir() else { + return false; + }; + let library_json = cwd.join("library.json"); + let Ok(text) = fs::read_to_string(library_json) else { + return false; + }; + serde_json::from_str::(&text) + .ok() + .and_then(|value| value.get("name").and_then(Value::as_str).map(str::to_owned)) + .map(|name| name == "FastLED") + .unwrap_or(false) +} + +fn is_fastled_repository() -> bool { + let Ok(cwd) = std::env::current_dir() else { + return false; + }; + let required_markers = [ + cwd.join("src").join("FastLED.h"), + cwd.join("examples").join("Blink").join("Blink.ino"), + cwd.join("ci").join("ci-compile.py"), + cwd.join("src").join("platforms"), + cwd.join("library.json"), + ]; + if required_markers.iter().any(|path| !path.exists()) { + return false; + } + + let Ok(text) = fs::read_to_string(cwd.join("library.json")) else { + return false; + }; + let Ok(value) = serde_json::from_str::(&text) else { + return false; + }; + if value.get("name").and_then(Value::as_str) != Some("FastLED") { + return false; + } + if !value + .get("repository") + .and_then(|repo| repo.get("url")) + .and_then(Value::as_str) + .map(|url| url.contains("FastLED/FastLED")) + .unwrap_or(false) + { + return false; + } + + let tests_dir = cwd.join("tests"); + if !tests_dir.is_dir() { + return false; + } + fs::read_dir(tests_dir) + .ok() + .into_iter() + .flat_map(|entries| entries.flatten()) + .any(|entry| { + entry.path().is_file() + && entry.file_name().to_string_lossy().starts_with("test_") + && entry.path().extension().and_then(|ext| ext.to_str()) == Some("cpp") + }) +} + +fn check_existing_arduino_content() -> bool { + fn has_ino_file(dir: &Path) -> bool { + let Ok(entries) = fs::read_dir(dir) else { + return false; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + if has_ino_file(&path) { + return true; + } + continue; + } + if path.extension().and_then(|ext| ext.to_str()) == Some("ino") { + return true; + } + } + false + } + + let Ok(cwd) = std::env::current_dir() else { + return false; + }; + cwd.join("examples").exists() || has_ino_file(&cwd) +} + +fn read_json_file(path: &Path, default: Value) -> Value { + fs::read_to_string(path) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .unwrap_or(default) +} + +fn write_json_file(path: &Path, value: &Value) -> Result<()> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?; + } + let mut text = serde_json::to_string_pretty(value).context("serialize JSON")?; + text.push('\n'); + fs::write(path, text).with_context(|| format!("write {}", path.display()))?; + Ok(()) +} + +fn update_launch_json_for_arduino() -> Result<()> { + let cwd = std::env::current_dir().context("current dir")?; + let launch_json_path = cwd.join(".vscode").join("launch.json"); + let mut data = read_json_file( + &launch_json_path, + json!({"version": "0.2.0", "configurations": []}), + ); + + if !data.is_object() { + data = json!({"version": "0.2.0", "configurations": []}); + } + + let arduino_config = json!({ + "name": "Auto Debug (Smart File Detection)", + "type": "auto-debug", + "request": "launch", + "map": { + "*.ino": "Arduino: Run .ino with FastLED", + "*.py": "Python: Current File (UV)" + } + }); + + let configs = data + .as_object_mut() + .expect("launch.json root object") + .entry("configurations") + .or_insert_with(|| Value::Array(Vec::new())); + if !configs.is_array() { + *configs = Value::Array(Vec::new()); + } + let configs_array = configs.as_array_mut().expect("configurations array"); + let exists = configs_array.iter().any(|cfg| { + cfg.get("name").and_then(Value::as_str) + == arduino_config.get("name").and_then(Value::as_str) + }); + if !exists { + configs_array.insert(0, arduino_config); + } + + write_json_file(&launch_json_path, &data)?; + println!("Updated {}", launch_json_path.display()); + Ok(()) +} + +fn generate_fastled_tasks() -> Result<()> { + let cwd = std::env::current_dir().context("current dir")?; + let tasks_json_path = cwd.join(".vscode").join("tasks.json"); + let mut data = read_json_file(&tasks_json_path, json!({"version": "2.0.0", "tasks": []})); + + if !data.is_object() { + data = json!({"version": "2.0.0", "tasks": []}); + } + + let fastled_tasks = vec![ + json!({ + "type": "shell", + "label": "Run FastLED (Debug)", + "command": "fastled", + "args": ["${file}", "--debug", "--app"], + "options": {"cwd": "${workspaceFolder}"}, + "group": {"kind": "build", "isDefault": true}, + "presentation": { + "echo": true, + "reveal": "always", + "focus": true, + "panel": "new", + "showReuseMessage": false, + "clear": true + }, + "detail": "Run FastLED with debug mode and app visualization", + "problemMatcher": [] + }), + json!({ + "type": "shell", + "label": "Run FastLED (Quick)", + "command": "fastled", + "args": ["${file}", "--quick"], + "options": {"cwd": "${workspaceFolder}"}, + "group": "build", + "presentation": { + "echo": true, + "reveal": "always", + "focus": true, + "panel": "new", + "showReuseMessage": false, + "clear": true + }, + "detail": "Run FastLED with quick build mode", + "problemMatcher": [] + }), + ]; + + let tasks = data + .as_object_mut() + .expect("tasks.json root object") + .entry("tasks") + .or_insert_with(|| Value::Array(Vec::new())); + if !tasks.is_array() { + *tasks = Value::Array(Vec::new()); + } + let tasks_array = tasks.as_array_mut().expect("tasks array"); + let existing_labels: Vec = tasks_array + .iter() + .filter_map(|task| task.get("label").and_then(Value::as_str).map(str::to_owned)) + .collect(); + + for task in fastled_tasks { + let Some(label) = task.get("label").and_then(Value::as_str) else { + continue; + }; + if !existing_labels.iter().any(|existing| existing == label) { + tasks_array.push(task); + } + } + + write_json_file(&tasks_json_path, &data)?; + println!("Updated {}", tasks_json_path.display()); + Ok(()) +} + +fn fastled_repository_settings() -> Value { + json!({ + "terminal.integrated.defaultProfile.windows": "Git Bash", + "terminal.integrated.shellIntegration.enabled": false, + "terminal.integrated.profiles.windows": { + "Command Prompt": {"path": "C:\\Windows\\System32\\cmd.exe"}, + "Git Bash": { + "path": "C:\\Program Files\\Git\\bin\\bash.exe", + "args": ["--cd=."] + } + }, + "files.eol": "\n", + "files.autoDetectEol": false, + "files.insertFinalNewline": true, + "files.trimFinalNewlines": true, + "editor.tabSize": 4, + "editor.insertSpaces": true, + "editor.detectIndentation": true, + "editor.formatOnSave": false, + "debug.defaultDebuggerType": "cppdbg", + "debug.toolBarLocation": "docked", + "debug.console.fontSize": 14, + "debug.console.lineHeight": 19, + "python.defaultInterpreterPath": "uv", + "python.debugger": "debugpy", + "[cpp]": { + "editor.defaultFormatter": "llvm-vs-code-extensions.vscode-clangd", + "debug.defaultDebuggerType": "cppdbg" + }, + "[c]": { + "editor.defaultFormatter": "ms-vscode.cpptools", + "debug.defaultDebuggerType": "cppdbg" + }, + "[ino]": { + "editor.defaultFormatter": "ms-vscode.cpptools", + "debug.defaultDebuggerType": "cppdbg" + }, + "clangd.arguments": [ + "--compile-commands-dir=${workspaceFolder}", + "--clang-tidy", + "--header-insertion=never", + "--completion-style=detailed", + "--function-arg-placeholders=false", + "--background-index", + "--pch-storage=memory" + ], + "clangd.fallbackFlags": [ + "-std=c++17", + "-I${workspaceFolder}/src", + "-I${workspaceFolder}/tests", + "-Wno-global-constructors" + ], + "C_Cpp.intelliSenseEngine": "disabled", + "C_Cpp.autocomplete": "disabled", + "C_Cpp.errorSquiggles": "disabled", + "C_Cpp.suggestSnippets": false, + "C_Cpp.intelliSenseEngineFallback": "disabled", + "C_Cpp.autocompleteAddParentheses": false, + "C_Cpp.formatting": "disabled", + "C_Cpp.vcpkg.enabled": false, + "C_Cpp.configurationWarnings": "disabled", + "C_Cpp.intelliSenseCachePath": "", + "C_Cpp.intelliSenseCacheSize": 0, + "C_Cpp.intelliSenseUpdateDelay": 0, + "C_Cpp.workspaceParsingPriority": "lowest", + "C_Cpp.disabled": true, + "files.associations": { + "*.ino": "cpp", + "*.h": "cpp", + "*.hpp": "cpp", + "*.cpp": "cpp", + "*.c": "c", + "*.inc": "cpp", + "*.tcc": "cpp", + "*.embeddedhtml": "html", + "compare": "cpp", + "type_traits": "cpp", + "cmath": "cpp", + "limits": "cpp", + "iostream": "cpp", + "random": "cpp", + "functional": "cpp", + "bit": "cpp", + "vector": "cpp", + "array": "cpp", + "string": "cpp", + "memory": "cpp", + "algorithm": "cpp", + "iterator": "cpp", + "utility": "cpp", + "optional": "cpp", + "variant": "cpp", + "numeric": "cpp", + "chrono": "cpp", + "thread": "cpp", + "mutex": "cpp", + "atomic": "cpp", + "future": "cpp", + "condition_variable": "cpp" + }, + "java.enabled": false, + "java.jdt.ls.enabled": false, + "java.compile.nullAnalysis.mode": "disabled", + "java.configuration.checkProjectSettingsExclusions": false, + "java.import.gradle.enabled": false, + "java.import.maven.enabled": false, + "java.autobuild.enabled": false, + "java.maxConcurrentBuilds": 0, + "java.recommendations.enabled": false, + "java.help.showReleaseNotes": false, + "redhat.telemetry.enabled": false, + "java.project.sourcePaths": [], + "java.project.referencedLibraries": [], + "files.exclude": { + "**/.classpath": true, + "**/.project": true, + "**/.factorypath": true + }, + "platformio.disableToolchainAutoInstaller": true, + "platformio-ide.autoRebuildAutocompleteIndex": false, + "platformio-ide.activateProjectOnTextEditorChange": false, + "platformio-ide.autoOpenPlatformIOIniFile": false, + "platformio-ide.autoPreloadEnvTasks": false, + "platformio-ide.autoCloseSerialMonitor": false, + "platformio-ide.disablePIOHomeStartup": true, + "extensions.ignoreRecommendations": true, + "editor.semanticTokenColorCustomizations": { + "rules": { + "class": "#4EC9B0", + "struct": "#4EC9B0", + "type": "#4EC9B0", + "enum": "#4EC9B0", + "enumMember": "#B5CEA8", + "typedef": "#4EC9B0", + "variable": "#FAFAFA", + "variable.local": "#FAFAFA", + "parameter": "#FF8C42", + "variable.parameter": "#FF8C42", + "property": "#D197D9", + "function": "#DCDCAA", + "method": "#DCDCAA", + "function.declaration": "#DCDCAA", + "method.declaration": "#DCDCAA", + "namespace": "#86C5F7", + "variable.readonly": {"foreground": "#B5CEA8", "fontStyle": "italic"}, + "variable.defaultLibrary": "#B5CEA8", + "macro": "#E06C75", + "string": "#CE9178", + "number": "#B5CEA8", + "keyword": "#C586C0", + "keyword.storage": "#FF79C6", + "storageClass": "#FF79C6", + "type.builtin": "#569CD6", + "keyword.type": "#569CD6", + "comment": "#6A9955", + "comment.documentation": "#6A9955" + } + }, + "editor.inlayHints.fontColor": "#808080", + "editor.inlayHints.background": "#3C3C3C20" + }) +} + +fn update_vscode_settings_for_fastled() -> Result<()> { + if !is_fastled_repository() { + return Ok(()); + } + + let cwd = std::env::current_dir().context("current dir")?; + let settings_json_path = cwd.join(".vscode").join("settings.json"); + let mut data = read_json_file(&settings_json_path, json!({})); + if !data.is_object() { + data = json!({}); + } + + let settings = fastled_repository_settings(); + let target = data.as_object_mut().expect("settings root object"); + let source = settings.as_object().expect("settings object"); + for (key, value) in source { + target.insert(key.clone(), value.clone()); + } + + write_json_file(&settings_json_path, &data)?; + println!( + "Updated {} with comprehensive FastLED development settings", + settings_json_path.display() + ); + Ok(()) +} + +fn download_to_path(url: &str, dest: &Path) -> Result<()> { + let client = reqwest::blocking::Client::builder() + .timeout(std::time::Duration::from_secs(120)) + .redirect(reqwest::redirect::Policy::limited(10)) + .build() + .context("build HTTP client")?; + let bytes = client + .get(url) + .send() + .with_context(|| format!("GET {url} failed"))? + .error_for_status() + .with_context(|| format!("download returned error for {url}"))? + .bytes() + .context("read response bytes")?; + fs::write(dest, &bytes).with_context(|| format!("write {}", dest.display()))?; + Ok(()) +} + +fn install_auto_debug_extension(dry_run: bool) -> Result { + if dry_run { + println!("[DRY-RUN]: Would download and install Auto Debug extension"); + return Ok(true); + } + + let Some((ide_command, ide_name)) = detect_supported_ide() else { + println!("Warning: no supported IDE found (VSCode or Cursor)"); + return Ok(false); + }; + + let temp_dir = tempfile::tempdir().context("create temp dir for extension")?; + let vsix_path = temp_dir.path().join("auto-debug.vsix"); + println!("Downloading Auto Debug extension..."); + download_to_path(AUTO_DEBUG_VSIX_URL, &vsix_path)?; + println!("Installing extension in {ide_name}..."); + + let status = Command::new(ide_command) + .args(["--install-extension", &vsix_path.to_string_lossy()]) + .status() + .with_context(|| format!("launch {ide_command} for extension install"))?; + + if !status.success() { + println!("Warning: extension installer exited with {}", status); + return Ok(false); + } + + println!("Auto Debug extension installed in {ide_name}"); + Ok(true) +} + +fn install_default_example() -> Result { + let output_dir = PathBuf::from("fastled"); + let repo_root = ensure_fastled_repo(None)?; + let resolved_ref = crate::project::cached_repo_ref_name(&repo_root); + let out = crate::project::init_example_from_repo( + &repo_root, + DEFAULT_INSTALL_EXAMPLE, + &output_dir, + Some(resolved_ref.as_str()), + )?; + println!("Installed example at {}", out.display()); + Ok(true) +} + +pub fn run_install(options: InstallOptions) -> Result { + println!("Starting FastLED installation..."); + validate_vscode_project(options.no_interactive)?; + + let is_fastled_project = detect_fastled_project(); + let is_repository = is_fastled_repository(); + if is_fastled_project { + if is_repository { + println!("Detected FastLED repository - configuring full development environment"); + } else { + println!("Detected external FastLED project - configuring Arduino environment"); + } + } else { + println!("Detected standard project - configuring basic Arduino environment"); + } + + let should_install_extension = if options.no_interactive { + println!("Skipping Auto Debug extension installation in non-interactive mode"); + false + } else if options.dry_run { + println!("[DRY-RUN]: Simulating Auto Debug extension installation..."); + true + } else { + prompt_yes_no( + "Would you like to install the FastLED auto-debug extension?", + false, + )? + }; + + if should_install_extension && !install_auto_debug_extension(options.dry_run)? { + println!("Warning: Auto Debug extension installation failed, continuing..."); + } + + println!("\nConfiguring VSCode files..."); + update_launch_json_for_arduino()?; + generate_fastled_tasks()?; + + let mut launch_after = false; + if !check_existing_arduino_content() { + if options.no_interactive { + println!( + "No Arduino content found. In non-interactive mode, skipping example installation." + ); + } else if prompt_yes_no( + &format!( + "No Arduino content found. Install the default '{}' example?", + DEFAULT_INSTALL_EXAMPLE + ), + true, + )? { + if options.dry_run { + println!( + "[DRY-RUN]: Would initialize the default '{}' example", + DEFAULT_INSTALL_EXAMPLE + ); + } else { + launch_after = install_default_example()?; + } + } + } else { + println!("Existing Arduino content detected, skipping example installation"); + launch_after = !options.dry_run; + } + + if is_fastled_project { + if is_repository { + println!("\nSetting up FastLED development environment..."); + update_vscode_settings_for_fastled()?; + } else { + println!("\nSkipping clangd settings - not in the FastLED repository"); + } + } + + if options.dry_run { + println!("\n[DRY-RUN]: Skipping auto-launch"); + launch_after = false; + } + + println!("\nFastLED installation completed successfully!"); + Ok(InstallOutcome { launch_after }) +} diff --git a/crates/fastled-cli/src/lib.rs b/crates/fastled-cli/src/lib.rs index ba039bdc..947bb343 100644 --- a/crates/fastled-cli/src/lib.rs +++ b/crates/fastled-cli/src/lib.rs @@ -1,17 +1,113 @@ +#![recursion_limit = "512"] + use clap::Parser; -use std::io::BufRead; +use std::io::Write; use std::path::{Path, PathBuf}; -use std::process::{Command, ExitCode, Stdio}; +use std::process::{Command, ExitCode}; mod archive; mod build; -mod install; +pub mod install; mod keyboard; -mod project; +pub mod project; mod server; mod viewer; mod watcher; +const DEFAULT_EXAMPLE: &str = "wasm"; + +fn ensure_compile_prerequisites() -> Result<(), String> { + match install::ensure_emscripten_installed() { + Ok(install_dir) => { + std::env::set_var("FASTLED_EMSCRIPTEN_DIR", &install_dir); + // FastLED's meson cross-file uses clang-tool-chain wrapper binaries. + // Those wrappers locate emscripten from the toolchain root, not the + // versioned install dir, so export the root when it can be derived. + if let Some(root) = install_dir + .parent() + .and_then(|p| p.parent()) + .and_then(|p| p.parent()) + .and_then(|p| p.parent()) + { + std::env::set_var("CLANG_TOOL_CHAIN_DOWNLOAD_PATH", root); + } + } + Err(e) => { + return Err(format!("emscripten toolchain install failed: {e:#}")); + } + } + match install::ensure_esbuild_installed() { + Ok(esbuild_path) => { + std::env::set_var("FASTLED_ESBUILD_PATH", &esbuild_path); + } + Err(e) => { + return Err(format!("esbuild install failed: {e:#}")); + } + } + Ok(()) +} + +fn selected_build_mode(cli: &Cli) -> build::BuildMode { + if cli.debug { + build::BuildMode::Debug + } else if cli.release { + build::BuildMode::Release + } else { + build::BuildMode::Quick + } +} + +fn purge_fastled_cache(fastled_path: Option<&str>) { + if let Some(home) = dirs::home_dir() { + let cache_dir = home.join(".fastled").join("cache"); + if cache_dir.exists() { + match std::fs::remove_dir_all(&cache_dir) { + Ok(()) => println!("Purged FastLED cache: {}", cache_dir.display()), + Err(err) => eprintln!( + "fastled: failed to purge cache {}: {err}", + cache_dir.display() + ), + } + } else { + println!("No FastLED cache to purge."); + } + } + + if let Some(path) = fastled_path { + let fastled_build = Path::new(path).join(".build"); + if let Ok(entries) = std::fs::read_dir(&fastled_build) { + for entry in entries.flatten() { + let wasm_dir = entry.path(); + let Some(name) = wasm_dir.file_name().and_then(|name| name.to_str()) else { + continue; + }; + if !name.starts_with("meson-wasm-") || !wasm_dir.is_dir() { + continue; + } + for stale in [ + "wasm_ld_args.json", + "wasm_ld_args.key", + "fastled_glue.js", + "js_glue_fingerprint", + "link_environment_fingerprint", + "libemscripten_js_symbols.so", + ] { + let stale_file = wasm_dir.join(stale); + if stale_file.exists() { + match std::fs::remove_file(&stale_file) { + Ok(()) => println!("Purged: {}", stale_file.display()), + Err(err) => eprintln!( + "fastled: failed to purge {}: {err}", + stale_file.display() + ), + } + } + } + } + } + } +} + // --------------------------------------------------------------------------- // Build-status IPC (Rust writes, loading page polls) // --------------------------------------------------------------------------- @@ -44,94 +140,75 @@ fn send_sse(tx: &tokio::sync::broadcast::Sender, json: &str) { let _ = tx.send(json.to_string()); } -/// Run `python -m fastled.app --just-compile` with piped stdout/stderr. -/// -/// Each line is printed to the terminal AND sent through the broadcast -/// channel so the loading page receives it via SSE. -fn run_python_compile_streaming( - cli: &Cli, - extra_args: &[&str], - tx: &tokio::sync::broadcast::Sender, -) -> bool { - let python = find_python(); - let mut args = vec![ - "-m".to_string(), - "fastled.app".to_string(), - "--just-compile".to_string(), - ]; - - if let Some(dir) = &cli.directory { - args.push(dir.clone()); +fn emit_build_log(tx: &tokio::sync::broadcast::Sender, line: &str, stream: &str) { + if stream == "stderr" { + eprintln!("{line}"); + } else { + println!("{line}"); } - if cli.debug { - args.push("--debug".to_string()); - } else if cli.release { - args.push("--release".to_string()); - } - if cli.profile { - args.push("--profile".to_string()); + send_sse( + tx, + &format!( + r#"{{"type":"log","line":"{}","stream":"{}"}}"#, + json_escape(line), + stream + ), + ); +} + +fn emit_build_result_logs( + result: &build::BuildResult, + tx: &tokio::sync::broadcast::Sender, +) { + let stream = if result.success { "stdout" } else { "stderr" }; + for line in result.output.lines() { + emit_build_log(tx, line, stream); } - if let Some(fp) = &cli.fastled_path { - args.push("--fastled-path".to_string()); - args.push(fp.clone()); + + if result.success { + emit_build_log( + tx, + &format!( + "Build finished in {:.2}s (strategy: {}, output: {})", + result.sketch_time_secs, + result.strategy, + result.output_dir.display() + ), + "stdout", + ); } - for arg in extra_args { - args.push(arg.to_string()); +} + +/// Run the native build path and mirror its output to the terminal + SSE. +fn run_native_compile_streaming( + cli: &Cli, + sketch_dir: &Path, + force_clean: bool, + tx: &tokio::sync::broadcast::Sender, +) -> bool { + if force_clean { + purge_fastled_cache(cli.fastled_path.as_deref()); } - let mut child = match Command::new(&python) - .args(&args) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - { - Ok(c) => c, - Err(e) => { - eprintln!("fastled: failed to launch `{python} -m fastled.app`: {e}"); - return false; - } + let request = build::BuildRequest { + sketch_dir: sketch_dir.to_path_buf(), + build_mode: selected_build_mode(cli), + profile: cli.profile, + fastled_path: cli.fastled_path.as_ref().map(PathBuf::from), + force_clean, }; - let stdout = child.stdout.take().unwrap(); - let stderr = child.stderr.take().unwrap(); - - let tx_out = tx.clone(); - let stdout_thread = std::thread::spawn(move || { - let reader = std::io::BufReader::new(stdout); - for line in reader.lines().map_while(Result::ok) { - println!("{line}"); - send_sse( - &tx_out, - &format!( - r#"{{"type":"log","line":"{}","stream":"stdout"}}"#, - json_escape(&line) - ), - ); + match build::run_build(&request) { + Ok(result) => { + emit_build_result_logs(&result, tx); + result.success } - }); - - let tx_err = tx.clone(); - let stderr_thread = std::thread::spawn(move || { - let reader = std::io::BufReader::new(stderr); - for line in reader.lines().map_while(Result::ok) { - eprintln!("{line}"); - send_sse( - &tx_err, - &format!( - r#"{{"type":"log","line":"{}","stream":"stderr"}}"#, - json_escape(&line) - ), + Err(err) => { + emit_build_log( + tx, + &format!("fastled: native compile path failed: {err:#}"), + "stderr", ); - } - }); - - stdout_thread.join().ok(); - stderr_thread.join().ok(); - - match child.wait() { - Ok(s) => s.success(), - Err(e) => { - eprintln!("fastled: error waiting for subprocess: {e}"); false } } @@ -166,39 +243,11 @@ fn compile_and_serve(dir: &str, cli: &Cli, mode: ViewerMode) -> ExitCode { } // Ensure the emscripten + esbuild toolchains are installed before invoking - // Python. The env vars below let the Python compile path skip its own - // download logic and consume the Rust-installed directories. - match install::ensure_emscripten_installed() { - Ok(install_dir) => { - std::env::set_var("FASTLED_EMSCRIPTEN_DIR", &install_dir); - // FastLED's meson cross-file calls `clang-tool-chain-emcc` / - // `-em++` / `-emar`. Those wrappers (from the `clang-tool-chain` - // PyPI package) look up emscripten under - // `$CLANG_TOOL_CHAIN_DOWNLOAD_PATH/emscripten///`. - // install_dir here is `/emscripten///`, - // so walk four parents up to the toolchains root and export it. - if let Some(root) = install_dir - .parent() - .and_then(|p| p.parent()) - .and_then(|p| p.parent()) - .and_then(|p| p.parent()) - { - std::env::set_var("CLANG_TOOL_CHAIN_DOWNLOAD_PATH", root); - } - } - Err(e) => { - eprintln!("fastled: emscripten toolchain install failed: {e:#}"); - return ExitCode::FAILURE; - } - } - match install::ensure_esbuild_installed() { - Ok(esbuild_path) => { - std::env::set_var("FASTLED_ESBUILD_PATH", &esbuild_path); - } - Err(e) => { - eprintln!("fastled: esbuild install failed: {e:#}"); - return ExitCode::FAILURE; - } + // the native build path. The embedded Python build service consumes the + // Rust-installed directories via these environment variables. + if let Err(message) = ensure_compile_prerequisites() { + eprintln!("fastled: {message}"); + return ExitCode::FAILURE; } let output_dir = sketch_dir.join("fastled_js"); @@ -246,11 +295,7 @@ fn compile_and_serve(dir: &str, cli: &Cli, mode: ViewerMode) -> ExitCode { r#"{"type":"status","status":"compiling","message":"Compiling..."}"#, ); - let mut extra: Vec<&str> = Vec::new(); - if cli.purge { - extra.push("--purge"); - } - let success = run_python_compile_streaming(cli, &extra, &tx); + let success = run_native_compile_streaming(cli, &sketch_dir, cli.purge, &tx); if success { write_build_status(&output_dir, "success", "Done"); @@ -300,7 +345,7 @@ fn compile_and_serve(dir: &str, cli: &Cli, mode: ViewerMode) -> ExitCode { r#"{"type":"status","status":"compiling","message":"Recompiling..."}"#, ); - let success = run_python_compile_streaming(cli, &[], &tx); + let success = run_native_compile_streaming(cli, &sketch_dir, false, &tx); if success { println!("Recompilation successful!"); write_build_status(&output_dir, "success", "Done"); @@ -326,9 +371,11 @@ fn compile_and_serve(dir: &str, cli: &Cli, mode: ViewerMode) -> ExitCode { /// FastLED WASM compilation CLI. /// -/// Thin Rust front-end that mirrors every Python flag, then delegates to -/// `python -m fastled.app` so behaviour is identical while the Rust entry -/// point is established. +/// Rust front-end for FastLED WASM workflows. +/// +/// Native Rust owns the full user-facing CLI surface. The only remaining +/// Python runtime dependency on compile paths is the in-process build service +/// invoked from `build.rs`. #[derive(Parser, Debug)] #[command( name = "fastled", @@ -431,38 +478,6 @@ struct Cli { release: bool, } -/// Locate a Python executable to use. -/// -/// Priority: -/// 1. `VIRTUAL_ENV/Scripts/python.exe` (Windows) or `VIRTUAL_ENV/bin/python` (Unix) -/// 2. Plain `python` on PATH -/// 3. Plain `python3` on PATH -fn find_python() -> String { - if let Ok(venv) = std::env::var("VIRTUAL_ENV") { - #[cfg(windows)] - let candidate = format!("{}/Scripts/python.exe", venv); - #[cfg(not(windows))] - let candidate = format!("{}/bin/python", venv); - - if std::path::Path::new(&candidate).exists() { - return candidate; - } - } - - // Try plain `python` - if Command::new("python") - .args(["--version"]) - .output() - .map(|o| o.status.success()) - .unwrap_or(false) - { - return "python".to_string(); - } - - // Fall back to `python3` - "python3".to_string() -} - /// Decide whether to use the native Tauri viewer for this invocation. /// /// Returns `true` when: @@ -473,78 +488,422 @@ fn should_use_tauri_viewer(cli: &Cli) -> bool { cli.app && !cli.legacy_browser && viewer::viewer_available() } -/// Convert the parsed `Cli` struct back into the argv that the Python CLI -/// expects, so we can pass it through verbatim. -/// -/// This is used only for the delegation path (--just-compile, --init, -/// --install) where Python handles the full operation. -fn rebuild_python_args(cli: &Cli) -> Vec { - let mut args: Vec = Vec::new(); +fn validate_init_ref_flags(cli: &Cli) -> Result<(), &'static str> { + if cli.latest && (cli.branch.is_some() || cli.commit.is_some()) { + return Err("--latest cannot be used with --branch or --commit"); + } + Ok(()) +} - if let Some(dir) = &cli.directory { - args.push(dir.clone()); +fn requested_init_ref(cli: &Cli) -> Option<&str> { + if cli.latest { + None + } else { + cli.commit.as_deref().or(cli.branch.as_deref()) } - if let Some(sd) = &cli.serve_dir { - args.push("--serve-dir".to_string()); - args.push(sd.clone()); +} + +fn display_path(path: &Path) -> String { + path.to_string_lossy().into_owned() +} + +fn canonical_display_path(path: &Path) -> String { + path.canonicalize() + .map(|resolved| { + let text = display_path(&resolved); + #[cfg(windows)] + { + text.strip_prefix(r"\\?\").unwrap_or(&text).to_string() + } + #[cfg(not(windows))] + { + text + } + }) + .unwrap_or_else(|_| display_path(path)) +} + +fn detect_local_fastled_path() -> Option { + let cwd = std::env::current_dir().ok()?; + project::find_fastled_repo_upwards(&cwd, 10).map(|path| canonical_display_path(&path)) +} + +enum PromptChoice { + Selected(String), + Narrowed(Vec), + Retry, +} + +fn option_basename(option: &str) -> &str { + Path::new(option) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or(option) +} + +fn fuzzy_match_options(input: &str, options: &[String]) -> Vec { + let basenames: Vec = options + .iter() + .map(|option| option_basename(option).to_string()) + .collect(); + let basename_refs: Vec<&str> = basenames.iter().map(String::as_str).collect(); + let fuzzy_matches = project::best_sketch_match(input, &basename_refs); + if fuzzy_matches.is_empty() { + return Vec::new(); } - if let Some(init_val) = &cli.init { - args.push("--init".to_string()); - // "__init__" is the sentinel used for bare `--init` (no value) - if init_val != "__init__" { - args.push(init_val.clone()); + + let mut results = Vec::new(); + for (index, basename) in basenames.iter().enumerate() { + if fuzzy_matches.iter().any(|candidate| candidate == basename) { + results.push(options[index].clone()); } } - if cli.just_compile { - args.push("--just-compile".to_string()); + results +} + +fn resolve_prompt_choice(input: &str, options: &[String], default_index: usize) -> PromptChoice { + let trimmed = input.trim(); + if trimmed.is_empty() { + return PromptChoice::Selected(options[default_index].clone()); } - if cli.profile { - args.push("--profile".to_string()); + + if let Ok(index) = trimmed.parse::() { + if (1..=options.len()).contains(&index) { + return PromptChoice::Selected(options[index - 1].clone()); + } } - if cli.app { - args.push("--app".to_string()); + + if let Some(exact) = options + .iter() + .find(|option| option.eq_ignore_ascii_case(trimmed)) + { + return PromptChoice::Selected(exact.clone()); } - if cli.install { - args.push("--install".to_string()); + + let input_lower = trimmed.to_lowercase(); + let partial_matches: Vec = options + .iter() + .filter(|option| option.to_lowercase().contains(&input_lower)) + .cloned() + .collect(); + match partial_matches.len() { + 1 => return PromptChoice::Selected(partial_matches[0].clone()), + n if n > 1 => return PromptChoice::Narrowed(partial_matches), + _ => {} } - if cli.dry_run { - args.push("--dry-run".to_string()); + + let fuzzy_matches = fuzzy_match_options(trimmed, options); + match fuzzy_matches.len() { + 1 => PromptChoice::Selected(fuzzy_matches[0].clone()), + n if n > 1 => PromptChoice::Narrowed(fuzzy_matches), + _ => PromptChoice::Retry, } - if cli.no_interactive { - args.push("--no-interactive".to_string()); +} + +fn prompt_for_choice( + options: &[String], + prompt: &str, + default_index: usize, +) -> Result { + if options.is_empty() { + return Err("no options available".to_string()); } - if cli.no_https { - args.push("--no-https".to_string()); + if options.len() == 1 { + return Ok(options[0].clone()); } - if cli.latest { - args.push("--latest".to_string()); + + let mut current_options = options.to_vec(); + let mut current_prompt = prompt.to_string(); + let mut current_default = default_index.min(current_options.len() - 1); + + loop { + println!("\n{current_prompt}"); + for (index, option) in current_options.iter().enumerate() { + if index == current_default { + println!(" [{}]: [{}]", index + 1, option); + } else { + println!(" [{}]: {}", index + 1, option); + } + } + + let default_option = ¤t_options[current_default]; + print!("\nEnter number or name (default: [{default_option}]): "); + std::io::stdout() + .flush() + .map_err(|err| format!("failed to flush prompt: {err}"))?; + + let mut input = String::new(); + std::io::stdin() + .read_line(&mut input) + .map_err(|err| format!("failed to read selection: {err}"))?; + + match resolve_prompt_choice(&input, ¤t_options, current_default) { + PromptChoice::Selected(choice) => return Ok(choice), + PromptChoice::Narrowed(matches) => { + let query = input.trim(); + let is_partial = current_options + .iter() + .filter(|option| option.to_lowercase().contains(&query.to_lowercase())) + .count() + > 1; + current_prompt = if is_partial { + format!("Multiple partial matches for '{query}':") + } else { + format!("Multiple fuzzy matches for '{query}':") + }; + current_options = matches; + current_default = 0; + } + PromptChoice::Retry => { + println!("No match found for '{}'. Please try again.", input.trim()); + } + } } - if let Some(branch) = &cli.branch { - args.push("--branch".to_string()); - args.push(branch.clone()); +} + +fn prompt_for_example(repo_root: &Path) -> Result { + let examples = project::collect_examples(&repo_root.join("examples")); + if examples.is_empty() { + return Err(format!( + "no examples found in FastLED repo {}", + repo_root.display() + )); } - if let Some(commit) = &cli.commit { - args.push("--commit".to_string()); - args.push(commit.clone()); + let default_index = examples + .iter() + .position(|example| example.eq_ignore_ascii_case(DEFAULT_EXAMPLE)) + .unwrap_or(0); + prompt_for_choice(&examples, "Available examples:", default_index) +} + +fn select_sketch_directory( + mut sketch_directories: Vec, + cwd_is_fastled: bool, + no_interactive: bool, +) -> Result, String> { + if cwd_is_fastled { + sketch_directories.retain(|path| { + let text = path.to_string_lossy().replace('\\', "/"); + !matches!(text.as_str(), "src" | "dev" | "tests") + }); } - if let Some(fp) = &cli.fastled_path { - args.push("--fastled-path".to_string()); - args.push(fp.clone()); + + match sketch_directories.len() { + 0 => Ok(None), + 1 => Ok(Some(display_path(&sketch_directories[0]))), + _ if no_interactive => Err( + "multiple sketch directories found; specify one explicitly when using --no-interactive" + .to_string(), + ), + _ => { + let options: Vec = sketch_directories + .iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect(); + prompt_for_choice(&options, "Multiple Directories found, choose one:", 0).map(Some) + } } - if cli.purge { - args.push("--purge".to_string()); +} + +fn resolve_compile_directory(cli: &Cli) -> Result, String> { + let cwd = std::env::current_dir() + .map_err(|err| format!("could not determine current directory: {err}"))?; + + let Some(directory) = &cli.directory else { + if project::looks_like_sketch_directory(&cwd, false) { + return Ok(Some(display_path(&cwd))); + } + let cwd_is_fastled = project::is_fastled_repo(&cwd); + return select_sketch_directory( + project::find_sketches(&cwd), + cwd_is_fastled, + cli.no_interactive, + ); + }; + + let provided_path = PathBuf::from(directory); + if provided_path.is_file() { + let parent = provided_path.parent().map(PathBuf::from); + if let Some(parent) = parent { + if project::looks_like_sketch_directory(&parent, false) { + return Ok(Some(canonical_display_path(&parent))); + } + } + return Ok(Some(directory.clone())); } - if cli.debug { - args.push("--debug".to_string()); + + if provided_path.exists() { + return Ok(Some(canonical_display_path(&provided_path))); } - if cli.quick { - args.push("--quick".to_string()); + + project::find_sketch_by_partial_name(directory, &cwd) + .map(|matched| display_path(&matched)) + .map(Some) + .map_err(|err| err.to_string()) +} + +fn run_native_init(cli: &Cli, example: Option<&str>) -> ExitCode { + if let Err(message) = validate_init_ref_flags(cli) { + eprintln!("fastled: {message}"); + return ExitCode::FAILURE; } - if cli.release { - args.push("--release".to_string()); + + let cwd = match std::env::current_dir() { + Ok(path) => path, + Err(e) => { + eprintln!("fastled: could not determine current directory: {e}"); + return ExitCode::FAILURE; + } + }; + let output_dir = cli + .directory + .as_deref() + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("fastled")); + + if let Some(local_repo) = project::find_fastled_repo_upwards(&cwd, 10) { + println!("Using local FastLED repo at {}", local_repo.display()); + let selected_example = match example { + Some(example) => example.to_string(), + None => { + if cli.no_interactive { + eprintln!("fastled: --init without an example requires interactive input"); + return ExitCode::FAILURE; + } + match prompt_for_example(&local_repo) { + Ok(selected) => selected, + Err(err) => { + eprintln!("fastled: failed to select example: {err}"); + return ExitCode::FAILURE; + } + } + } + }; + return match project::init_example_from_repo( + &local_repo, + &selected_example, + &output_dir, + None, + ) { + Ok(out) => { + println!("Project initialized at {}", out.display()); + println!("\nInitialized FastLED project in {}", out.display()); + println!("Use 'fastled {}' to compile the project.", out.display()); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("fastled: failed to initialize project: {e:#}"); + ExitCode::FAILURE + } + }; + } + + let mut ref_name = requested_init_ref(cli).map(str::to_owned); + if ref_name.is_none() { + ref_name = project::read_fastled_json_ref(&cwd) + .or_else(|| project::read_fastled_json_ref(&output_dir)); + if let Some(saved_ref) = &ref_name { + println!("Using saved ref '{saved_ref}' from fastled.json"); + } + } + + let ref_display = ref_name.as_deref().unwrap_or("latest release"); + + let repo_root = match install::ensure_fastled_repo(ref_name.as_deref()) { + Ok(path) => path, + Err(e) => { + eprintln!("fastled: failed to fetch FastLED repo: {e:#}"); + return ExitCode::FAILURE; + } + }; + let resolved_ref = project::cached_repo_ref_name(&repo_root); + let selected_example = match example { + Some(example) => example.to_string(), + None => { + if cli.no_interactive { + eprintln!("fastled: --init without an example requires interactive input"); + return ExitCode::FAILURE; + } + match prompt_for_example(&repo_root) { + Ok(selected) => selected, + Err(err) => { + eprintln!("fastled: failed to select example: {err}"); + return ExitCode::FAILURE; + } + } + } + }; + + println!( + "Initializing project with example '{}' from FastLED repo ({ref_display})", + selected_example + ); + + match project::init_example_from_repo( + &repo_root, + &selected_example, + &output_dir, + ref_name.as_ref().map(|_| resolved_ref.as_str()), + ) { + Ok(out) => { + if ref_name.is_some() { + println!( + "Saved ref '{resolved_ref}' to {}", + out.join("fastled.json").display() + ); + } + println!("Project initialized at {}", out.display()); + println!("\nInitialized FastLED project in {}", out.display()); + println!("Use 'fastled {}' to compile the project.", out.display()); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("fastled: failed to initialize project: {e:#}"); + ExitCode::FAILURE + } + } +} + +fn run_native_just_compile(cli: &Cli, dir: &str) -> ExitCode { + if let Err(message) = ensure_compile_prerequisites() { + eprintln!("fastled: {message}"); + return ExitCode::FAILURE; + } + + if cli.purge { + purge_fastled_cache(cli.fastled_path.as_deref()); + } + + let request = build::BuildRequest { + sketch_dir: PathBuf::from(dir), + build_mode: selected_build_mode(cli), + profile: cli.profile, + fastled_path: cli.fastled_path.as_ref().map(PathBuf::from), + force_clean: cli.purge, + }; + + let result = match build::run_build(&request) { + Ok(result) => result, + Err(err) => { + eprintln!("fastled: native compile path failed: {err:#}"); + return ExitCode::FAILURE; + } + }; + + if !result.success { + if !result.output.trim().is_empty() { + eprintln!("{}", result.output.trim_end()); + } + eprintln!("\nCompilation failed."); + return ExitCode::FAILURE; } - args + println!("\nCompilation successful!"); + println!(" Time: {:.2} seconds", result.sketch_time_secs); + println!(" Wall time: {:.2} seconds", result.duration_secs); + println!(" Strategy: {}", result.strategy); + println!(" Output: {}", result.output_dir.display()); + ExitCode::SUCCESS } /// Serve a directory using the built-in Rust HTTP server. @@ -608,7 +967,12 @@ fn open_browser(url: &str) { /// Library entry point — invoked from both the `fastled` binary in this crate /// and the wheel-bundled `fastled` binary in `crates/fastled-py`. pub fn run() -> ExitCode { - let cli = Cli::parse(); + let mut cli = Cli::parse(); + + if let Err(message) = validate_init_ref_flags(&cli) { + eprintln!("fastled: {message}"); + return ExitCode::FAILURE; + } // Hidden plumbing for the Python side: download the FastLED repo and // print the local path. No further work. @@ -656,6 +1020,50 @@ pub fn run() -> ExitCode { return serve_directory(serve_dir, &cli); } + if cli.install { + match install::run_install(install::InstallOptions { + dry_run: cli.dry_run, + no_interactive: cli.no_interactive, + }) { + Ok(outcome) => { + cli.install = false; + if !outcome.launch_after { + return ExitCode::SUCCESS; + } + } + Err(err) => { + eprintln!("fastled: installation failed: {err:#}"); + return ExitCode::FAILURE; + } + } + } + + if let Some(ref init_value) = cli.init { + return run_native_init( + &cli, + if init_value == "__init__" { + None + } else { + Some(init_value.as_str()) + }, + ); + } + + if cli.init.is_none() { + if cli.fastled_path.is_none() { + cli.fastled_path = detect_local_fastled_path(); + } + + match resolve_compile_directory(&cli) { + Ok(Some(directory)) => cli.directory = Some(directory), + Ok(None) => {} + Err(message) => { + eprintln!("fastled: {message}"); + return ExitCode::FAILURE; + } + } + } + let use_tauri = should_use_tauri_viewer(&cli); // Normal compilation flow with Rust HTTP server + watch mode. @@ -665,9 +1073,12 @@ pub fn run() -> ExitCode { // Conditions: // - a sketch directory was provided // - the user did NOT pass --just-compile - // - it's not a non-compile command (--init, --install) + // - it's not a non-compile command (--init) if let Some(ref dir) = cli.directory { - if !cli.just_compile && cli.init.is_none() && !cli.install { + if cli.just_compile && cli.init.is_none() { + return run_native_just_compile(&cli, dir); + } + if !cli.just_compile && cli.init.is_none() { let mode = if use_tauri { ViewerMode::TauriViewer } else { @@ -677,74 +1088,185 @@ pub fn run() -> ExitCode { } } - // For --init: pre-download the FastLED repo with Rust so the Python side - // doesn't need httpx. Set FASTLED_LOCAL_REPO_DIR for the subprocess. - if cli.init.is_some() { - // Resolve ref precedence: --latest > --commit > --branch > default. - let ref_opt: Option<&str> = if cli.latest { - None - } else { - cli.commit.as_deref().or(cli.branch.as_deref()) - }; - match install::ensure_fastled_repo(ref_opt) { - Ok(repo_dir) => { - std::env::set_var("FASTLED_LOCAL_REPO_DIR", &repo_dir); - } - Err(e) => { - eprintln!("fastled: failed to fetch FastLED repo: {e:#}"); - return ExitCode::FAILURE; - } + eprintln!("fastled: no sketch directory specified"); + ExitCode::FAILURE +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::sync::{Mutex, OnceLock}; + + fn cwd_lock() -> &'static Mutex<()> { + static LOCK: OnceLock> = OnceLock::new(); + LOCK.get_or_init(|| Mutex::new(())) + } + + struct CurrentDirGuard { + original: PathBuf, + } + + impl CurrentDirGuard { + fn enter(path: &Path) -> Self { + let original = std::env::current_dir().expect("current dir"); + std::env::set_current_dir(path).expect("set current dir"); + Self { original } } } - // If we're about to delegate a compile to Python (`--just-compile `) - // ensure the emscripten + esbuild toolchains are installed first and - // export the paths through env vars — matches what compile_and_serve() - // does for the non-just-compile path. Without this, Python's emscripten - // toolchain lookup falls through to "not found" on a fresh CI runner. - let needs_compile_toolchain = cli.directory.is_some() && cli.init.is_none() && !cli.install; - if needs_compile_toolchain { - match install::ensure_emscripten_installed() { - Ok(install_dir) => { - std::env::set_var("FASTLED_EMSCRIPTEN_DIR", &install_dir); - } - Err(e) => { - eprintln!("fastled: emscripten toolchain install failed: {e:#}"); - return ExitCode::FAILURE; - } + impl Drop for CurrentDirGuard { + fn drop(&mut self) { + let _ = std::env::set_current_dir(&self.original); } - match install::ensure_esbuild_installed() { - Ok(esbuild_path) => { - std::env::set_var("FASTLED_ESBUILD_PATH", &esbuild_path); - } - Err(e) => { - eprintln!("fastled: esbuild install failed: {e:#}"); - return ExitCode::FAILURE; - } + } + + fn base_cli() -> Cli { + Cli { + directory: None, + serve_dir: None, + init: None, + just_compile: false, + profile: false, + app: false, + legacy_browser: false, + install: false, + dry_run: false, + no_interactive: false, + no_https: false, + latest: false, + branch: None, + commit: None, + fastled_path: None, + purge: false, + internal_ensure_fastled_repo: None, + internal_ensure_chrome_extension: Vec::new(), + debug: false, + quick: false, + release: false, } } - // --- Delegate to Python for everything else ------------------------------ - // (--just-compile, --init, --install, etc.) + #[test] + fn resolve_compile_directory_uses_current_sketch_dir() { + let _lock = cwd_lock() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let temp = tempfile::tempdir().expect("tempdir"); + let sketch_dir = temp.path().join("Blink"); + fs::create_dir_all(&sketch_dir).unwrap(); + fs::write(sketch_dir.join("Blink.ino"), b"void setup() {}").unwrap(); + let _guard = CurrentDirGuard::enter(&sketch_dir); + + let resolved = resolve_compile_directory(&base_cli()).unwrap(); + assert_eq!(resolved, Some(display_path(&sketch_dir))); + } + + #[test] + fn resolve_compile_directory_accepts_file_inside_sketch() { + let temp = tempfile::tempdir().expect("tempdir"); + let sketch_dir = temp.path().join("Blink"); + let source_file = sketch_dir.join("Blink.ino"); + fs::create_dir_all(&sketch_dir).unwrap(); + fs::write(&source_file, b"void setup() {}").unwrap(); - let python = find_python(); - let py_args = rebuild_python_args(&cli); + let mut cli = base_cli(); + cli.directory = Some(display_path(&source_file)); - let status = Command::new(&python) - .args(["-m", "fastled.app"]) - .args(&py_args) - .status(); + let resolved = resolve_compile_directory(&cli).unwrap(); + assert_eq!(resolved, Some(display_path(&sketch_dir))); + } - let exit_code = match status { - Ok(s) => { - let code = s.code().unwrap_or(1); - ExitCode::from(code as u8) + #[test] + fn resolve_compile_directory_matches_partial_name() { + let _lock = cwd_lock() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let temp = tempfile::tempdir().expect("tempdir"); + let examples_dir = temp.path().join("examples").join("FxWave2d"); + fs::create_dir_all(&examples_dir).unwrap(); + fs::write(examples_dir.join("FxWave2d.ino"), b"void setup() {}").unwrap(); + let _guard = CurrentDirGuard::enter(temp.path()); + + let mut cli = base_cli(); + cli.directory = Some("FxWave2d".to_string()); + + let resolved = resolve_compile_directory(&cli).unwrap(); + assert_eq!( + resolved, + Some( + PathBuf::from("examples") + .join("FxWave2d") + .to_string_lossy() + .into_owned() + ) + ); + } + + #[test] + fn detect_local_fastled_path_finds_repo_upwards() { + let _lock = cwd_lock() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let temp = tempfile::tempdir().expect("tempdir"); + let repo_root = temp.path().join("FastLED"); + let nested = repo_root.join("examples").join("Blink"); + fs::create_dir_all(&nested).unwrap(); + fs::write(repo_root.join("library.properties"), b"name=FastLED\n").unwrap(); + let _guard = CurrentDirGuard::enter(&nested); + + let detected = detect_local_fastled_path(); + assert_eq!(detected, Some(display_path(&repo_root))); + } + + #[test] + fn resolve_prompt_choice_accepts_default_selection() { + let options = vec!["Blink".to_string(), "Noise".to_string()]; + match resolve_prompt_choice("", &options, 1) { + PromptChoice::Selected(choice) => assert_eq!(choice, "Noise"), + _ => panic!("expected default selection"), } - Err(e) => { - eprintln!("fastled: failed to launch `{python} -m fastled.app`: {e}"); - return ExitCode::FAILURE; + } + + #[test] + fn resolve_prompt_choice_accepts_numeric_selection() { + let options = vec!["Blink".to_string(), "Noise".to_string()]; + match resolve_prompt_choice("2", &options, 0) { + PromptChoice::Selected(choice) => assert_eq!(choice, "Noise"), + _ => panic!("expected numeric selection"), } - }; + } - exit_code + #[test] + fn resolve_prompt_choice_narrows_partial_matches() { + let options = vec![ + "Fire2012".to_string(), + "Fire2012WithPalette".to_string(), + "Blink".to_string(), + ]; + match resolve_prompt_choice("Fire", &options, 0) { + PromptChoice::Narrowed(matches) => { + assert_eq!( + matches, + vec!["Fire2012".to_string(), "Fire2012WithPalette".to_string()] + ); + } + _ => panic!("expected narrowed partial matches"), + } + } + + #[test] + fn resolve_prompt_choice_uses_fuzzy_matching() { + let options = vec![ + "examples/Audio".to_string(), + "examples/BeatDetection".to_string(), + "examples/Blink".to_string(), + ]; + match resolve_prompt_choice("beats", &options, 0) { + PromptChoice::Selected(choice) => { + assert_eq!(choice, "examples/BeatDetection"); + } + _ => panic!("expected fuzzy selection"), + } + } } diff --git a/crates/fastled-cli/src/project.rs b/crates/fastled-cli/src/project.rs index f30e2cfb..b15618e1 100644 --- a/crates/fastled-cli/src/project.rs +++ b/crates/fastled-cli/src/project.rs @@ -13,7 +13,7 @@ use std::fs; use std::path::{Path, PathBuf}; -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; // --------------------------------------------------------------------------- // Sketch detection @@ -51,6 +51,20 @@ pub fn is_sketch_dir(dir: &Path) -> bool { false } +/// Return `true` when `directory` looks like a sketch directory using the +/// Python-side semantics. +pub fn looks_like_sketch_directory(directory: &Path, quick: bool) -> bool { + if !directory.is_dir() || is_fastled_repo(directory) { + return false; + } + + if !quick && sketch_file_count_exceeds_limit(directory, 100) { + return false; + } + + is_sketch_dir(directory) +} + /// Find sketch directories inside `root`. /// /// Behaviour mirrors `sketch.py::find_sketch_directories`: @@ -94,7 +108,7 @@ pub fn find_sketches(root: &Path) -> Vec { if name.eq_ignore_ascii_case("examples") { // Recurse into examples/ up to three levels deep. _search_examples(&path, root, &mut results, &mut count, 0, 3); - } else if is_sketch_dir(&path) { + } else if looks_like_sketch_directory(&path, true) { if let Ok(rel) = path.strip_prefix(root) { results.push(rel.to_path_buf()); } @@ -141,7 +155,7 @@ fn _search_examples( return; } - if is_sketch_dir(&path) { + if looks_like_sketch_directory(&path, true) { if let Ok(rel) = path.strip_prefix(root) { results.push(rel.to_path_buf()); } @@ -152,6 +166,45 @@ fn _search_examples( } } +fn sketch_file_count_exceeds_limit(directory: &Path, limit: usize) -> bool { + let mut count = 0usize; + count_sketch_files(directory, limit, &mut count) +} + +fn count_sketch_files(directory: &Path, limit: usize, count: &mut usize) -> bool { + let entries = match fs::read_dir(directory) { + Ok(e) => e, + Err(_) => return false, + }; + + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name(); + let name = name.to_string_lossy(); + + if path.is_dir() { + if name.starts_with('.') || name.contains("fastled_js") { + continue; + } + if count_sketch_files(&path, limit, count) { + return true; + } + continue; + } + + if name.starts_with('.') || name.contains("platformio.ini") { + continue; + } + + *count += 1; + if *count > limit { + return true; + } + } + + false +} + // --------------------------------------------------------------------------- // FastLED repo detection // --------------------------------------------------------------------------- @@ -200,6 +253,137 @@ pub fn is_fastled_repo(path: &Path) -> bool { false } +/// Walk upwards from `start` and return the first directory that looks like a +/// FastLED repository. +pub fn find_fastled_repo_upwards(start: &Path, max_depth: usize) -> Option { + let mut current = start.canonicalize().unwrap_or_else(|_| start.to_path_buf()); + + for _ in 0..=max_depth { + if is_fastled_repo(¤t) { + return Some(current); + } + + let parent = current.parent()?.to_path_buf(); + if parent == current { + break; + } + current = parent; + } + + None +} + +/// Collect available example names from a FastLED `examples/` directory. +pub fn collect_examples(examples_dir: &Path) -> Vec { + if !examples_dir.is_dir() { + return Vec::new(); + } + + let mut found = Vec::new(); + let entries = match fs::read_dir(examples_dir) { + Ok(e) => e, + Err(_) => return found, + }; + + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_dir() { + continue; + } + + if contains_ino_files(&path) { + if let Some(name) = path.file_name().and_then(|n| n.to_str()) { + found.push(name.to_owned()); + } + continue; + } + + let nested_entries = match fs::read_dir(&path) { + Ok(e) => e, + Err(_) => continue, + }; + for nested in nested_entries.flatten() { + let nested_path = nested.path(); + if !nested_path.is_dir() || !contains_ino_files(&nested_path) { + continue; + } + if let Some(name) = nested_path.file_name().and_then(|n| n.to_str()) { + found.push(name.to_owned()); + } + } + } + + found.sort(); + found +} + +/// Read the `ref` field from `fastled.json` in `directory`. +pub fn read_fastled_json_ref(directory: &Path) -> Option { + let fpath = directory.join("fastled.json"); + let txt = fs::read_to_string(fpath).ok()?; + let value: serde_json::Value = serde_json::from_str(&txt).ok()?; + value.get("ref")?.as_str().map(str::to_owned) +} + +/// Derive the resolved FastLED ref name from a cached repo directory. +/// +/// `install::ensure_fastled_repo()` materializes repos under names like +/// `~/.fastled/cache/fastled-3.9.12/`, so we can recover the effective ref +/// from the leaf directory name for user-facing messages and `fastled.json`. +pub fn cached_repo_ref_name(repo_root: &Path) -> String { + repo_root + .file_name() + .and_then(|name| name.to_str()) + .map(|name| name.strip_prefix("fastled-").unwrap_or(name)) + .filter(|name| !name.is_empty()) + .map(str::to_owned) + .unwrap_or_else(|| "master".to_owned()) +} + +/// Write `fastled.json` with the provided `ref_name`, preserving any existing +/// keys when the file already contains valid JSON. +pub fn write_fastled_json_ref(directory: &Path, ref_name: &str) -> Result<()> { + let fpath = directory.join("fastled.json"); + let mut data = if fpath.is_file() { + fs::read_to_string(&fpath) + .ok() + .and_then(|txt| { + serde_json::from_str::>(&txt).ok() + }) + .unwrap_or_default() + } else { + serde_json::Map::new() + }; + + data.insert( + "ref".to_owned(), + serde_json::Value::String(ref_name.to_owned()), + ); + + let mut json = serde_json::to_string_pretty(&serde_json::Value::Object(data)) + .context("serialize fastled.json")?; + json.push('\n'); + fs::write(&fpath, json).with_context(|| format!("write {}", fpath.display()))?; + Ok(()) +} + +fn contains_ino_files(directory: &Path) -> bool { + let entries = match fs::read_dir(directory) { + Ok(e) => e, + Err(_) => return false, + }; + + entries.flatten().any(|entry| { + entry.path().is_file() + && entry + .path() + .extension() + .and_then(|ext| ext.to_str()) + .map(|ext| ext.eq_ignore_ascii_case("ino")) + .unwrap_or(false) + }) +} + // --------------------------------------------------------------------------- // GitHub archive download and example extraction // --------------------------------------------------------------------------- @@ -325,6 +509,35 @@ pub fn init_example(example_name: &str, dest: &Path, branch: Option<&str>) -> Re Ok(out_path) } +/// Copy `example_name` from an already-materialized FastLED repo into +/// `output_dir/example_name`, optionally persisting `ref_name` in +/// `fastled.json`. +pub fn init_example_from_repo( + repo_root: &Path, + example_name: &str, + output_dir: &Path, + ref_name: Option<&str>, +) -> Result { + let example_src = find_example_in_repo(repo_root, example_name).with_context(|| { + format!( + "example '{example_name}' not found in FastLED repo {}", + repo_root.display() + ) + })?; + + fs::create_dir_all(output_dir) + .with_context(|| format!("cannot create output directory {}", output_dir.display()))?; + let out_path = output_dir.join(example_name); + copy_dir_all(&example_src, &out_path) + .with_context(|| format!("failed to copy example to {}", out_path.display()))?; + + if let Some(ref_name) = ref_name { + write_fastled_json_ref(&out_path, ref_name)?; + } + + Ok(out_path) +} + /// Find the FastLED repo root inside an extracted archive directory. /// /// The zip produces a top-level directory like `FastLED-master` or @@ -354,7 +567,7 @@ fn find_archive_repo_root(extract_dir: &Path) -> Result { /// Handles both layouts: /// * `examples/{name}/` — flat /// * `examples/*/{name}/` — one level of nesting (e.g. `examples/Fx/`) -fn find_example_in_repo(repo_root: &Path, name: &str) -> Option { +pub fn find_example_in_repo(repo_root: &Path, name: &str) -> Option { let examples_dir = repo_root.join("examples"); if !examples_dir.is_dir() { return None; @@ -455,6 +668,100 @@ pub fn best_sketch_match(query: &str, candidates: &[&str]) -> Vec { .collect() } +/// Find a sketch directory by partial name match using the Python-side rules. +/// +/// Returns a path relative to `search_dir`, mirroring `find_sketches`. +pub fn find_sketch_by_partial_name(partial_name: &str, search_dir: &Path) -> Result { + let sketch_directories = find_sketches(search_dir); + let partial_name_normalized = partial_name.replace('\\', "/").to_lowercase(); + let partial_chars: std::collections::HashSet = partial_name_normalized.chars().collect(); + + let similarity = |candidate: &Path| -> f64 { + if partial_chars.is_empty() { + return 0.0; + } + + let candidate_normalized = candidate + .to_string_lossy() + .replace('\\', "/") + .to_lowercase(); + let candidate_chars: std::collections::HashSet = + candidate_normalized.chars().collect(); + let matching_chars = partial_chars.intersection(&candidate_chars).count(); + matching_chars as f64 / partial_chars.len() as f64 + }; + + let matches: Vec = sketch_directories + .iter() + .filter_map(|sketch_dir| { + let sketch_str_normalized = sketch_dir + .to_string_lossy() + .replace('\\', "/") + .to_lowercase(); + (sketch_str_normalized.contains(&partial_name_normalized) + && similarity(sketch_dir) >= 0.5) + .then_some(sketch_dir.clone()) + }) + .collect(); + + if matches.is_empty() { + let all_low_similarity = sketch_directories + .iter() + .all(|sketch_dir| similarity(sketch_dir) <= 0.5); + + if all_low_similarity && !sketch_directories.is_empty() { + let sketches_str = sketch_directories + .iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect::>() + .join("\n "); + bail!( + "'{}' does not look like any of the available sketches.\n\nAvailable sketches:\n {}", + partial_name, + sketches_str + ); + } + + bail!("No sketch directory found matching '{}'", partial_name); + } + + if matches.len() == 1 { + return Ok(matches[0].clone()); + } + + let exact_matches: Vec = matches + .iter() + .filter(|candidate| { + candidate + .file_name() + .and_then(|name| name.to_str()) + .map(|name| name.eq_ignore_ascii_case(&partial_name_normalized)) + .unwrap_or(false) + }) + .cloned() + .collect(); + + if exact_matches.len() == 1 { + return Ok(exact_matches[0].clone()); + } + + let ambiguous_matches = if exact_matches.is_empty() { + matches + } else { + exact_matches + }; + let matches_str = ambiguous_matches + .iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect::>() + .join("\n "); + bail!( + "Multiple sketch directories found matching '{}':\n {}", + partial_name, + matches_str + ); +} + // --------------------------------------------------------------------------- // Unit tests // --------------------------------------------------------------------------- @@ -514,6 +821,28 @@ mod tests { assert!(!is_sketch_dir(&dir.path().join("does_not_exist"))); } + #[test] + fn test_looks_like_sketch_directory_rejects_fastled_repo() { + let dir = temp_dir(); + let root = dir.path(); + fs::write(root.join("library.properties"), b"name=FastLED\n").unwrap(); + fs::write(root.join("demo.ino"), b"void setup() {}").unwrap(); + assert!(!looks_like_sketch_directory(root, false)); + } + + #[test] + fn test_looks_like_sketch_directory_rejects_large_non_quick_tree() { + let dir = temp_dir(); + let sketch = dir.path().join("BigSketch"); + fs::create_dir(&sketch).unwrap(); + fs::write(sketch.join("BigSketch.ino"), b"void setup() {}").unwrap(); + for i in 0..101 { + fs::write(sketch.join(format!("file{i}.txt")), b"x").unwrap(); + } + assert!(!looks_like_sketch_directory(&sketch, false)); + assert!(looks_like_sketch_directory(&sketch, true)); + } + // ------------------------------------------------------------------ // find_sketches // ------------------------------------------------------------------ @@ -636,6 +965,86 @@ mod tests { assert!(!is_fastled_repo(root)); } + #[test] + fn test_find_fastled_repo_upwards() { + let dir = temp_dir(); + let root = dir.path().join("FastLED"); + let nested = root.join("examples").join("Blink"); + fs::create_dir_all(&nested).unwrap(); + fs::write(root.join("library.properties"), b"name=FastLED\n").unwrap(); + + let found = find_fastled_repo_upwards(&nested, 10); + let found = found.unwrap(); + assert_eq!(found.file_name().and_then(|n| n.to_str()), Some("FastLED")); + assert!(found.ends_with("FastLED")); + } + + #[test] + fn test_collect_examples_handles_flat_and_nested_layouts() { + let dir = temp_dir(); + let examples = dir.path().join("examples"); + let flat = examples.join("Blink"); + let nested = examples.join("Fx").join("FxWave"); + fs::create_dir_all(&flat).unwrap(); + fs::create_dir_all(&nested).unwrap(); + fs::write(flat.join("Blink.ino"), b"void setup() {}").unwrap(); + fs::write(nested.join("FxWave.ino"), b"void setup() {}").unwrap(); + + let found = collect_examples(&examples); + assert_eq!(found, vec!["Blink".to_owned(), "FxWave".to_owned()]); + } + + #[test] + fn test_read_and_write_fastled_json_ref() { + let dir = temp_dir(); + write_fastled_json_ref(dir.path(), "master").unwrap(); + assert_eq!(read_fastled_json_ref(dir.path()).as_deref(), Some("master")); + } + + #[test] + fn test_cached_repo_ref_name_strips_fastled_prefix() { + let path = Path::new("/tmp/fastled-3.9.12"); + assert_eq!(cached_repo_ref_name(path), "3.9.12"); + } + + #[test] + fn test_cached_repo_ref_name_falls_back_when_name_missing() { + let path = Path::new(""); + assert_eq!(cached_repo_ref_name(path), "master"); + } + + #[test] + fn test_write_fastled_json_ref_preserves_other_fields() { + let dir = temp_dir(); + fs::write( + dir.path().join("fastled.json"), + "{\n \"name\": \"demo\"\n}\n", + ) + .unwrap(); + + write_fastled_json_ref(dir.path(), "3.9.12").unwrap(); + + let txt = fs::read_to_string(dir.path().join("fastled.json")).unwrap(); + let value: serde_json::Value = serde_json::from_str(&txt).unwrap(); + assert_eq!(value.get("name").and_then(|v| v.as_str()), Some("demo")); + assert_eq!(value.get("ref").and_then(|v| v.as_str()), Some("3.9.12")); + } + + #[test] + fn test_init_example_from_repo_copies_example_and_writes_ref() { + let dir = temp_dir(); + let repo_root = dir.path().join("FastLED"); + let example = repo_root.join("examples").join("Blink"); + let out_root = dir.path().join("out"); + fs::create_dir_all(&example).unwrap(); + fs::write(example.join("Blink.ino"), b"void setup() {}").unwrap(); + + let out = init_example_from_repo(&repo_root, "Blink", &out_root, Some("master")).unwrap(); + + assert!(out.join("Blink.ino").is_file()); + assert_eq!(read_fastled_json_ref(&out).as_deref(), Some("master")); + } + // ------------------------------------------------------------------ // best_sketch_match (fuzzy matching) // ------------------------------------------------------------------ @@ -682,4 +1091,69 @@ mod tests { "case-insensitive match: {matches:?}" ); } + + #[test] + fn test_find_sketch_by_partial_name_returns_unique_match() { + let dir = temp_dir(); + let root = dir.path(); + let sketch = root.join("examples").join("FxWave2d"); + fs::create_dir_all(&sketch).unwrap(); + fs::write(sketch.join("FxWave2d.ino"), b"void setup() {}").unwrap(); + + let matched = find_sketch_by_partial_name("FxWave2d", root).unwrap(); + assert_eq!(matched, PathBuf::from("examples").join("FxWave2d")); + } + + #[test] + fn test_find_sketch_by_partial_name_prefers_exact_leaf_match() { + let dir = temp_dir(); + let root = dir.path(); + for name in ["sketch", "sketch1", "sketch2"] { + let path = root.join("examples").join(name); + fs::create_dir_all(&path).unwrap(); + fs::write(path.join(format!("{name}.ino")), b"void setup() {}").unwrap(); + } + + let matched = find_sketch_by_partial_name("sketch", root).unwrap(); + assert_eq!(matched, PathBuf::from("examples").join("sketch")); + } + + #[test] + fn test_find_sketch_by_partial_name_reports_low_similarity_options() { + let dir = temp_dir(); + let root = dir.path(); + for name in ["path/to/sketch", "examples/MyProject"] { + let path = root.join(name); + fs::create_dir_all(&path).unwrap(); + let file_name = path.file_name().and_then(|value| value.to_str()).unwrap(); + fs::write(path.join(format!("{file_name}.ino")), b"void setup() {}").unwrap(); + } + + let err = find_sketch_by_partial_name("blah", root) + .unwrap_err() + .to_string(); + assert!(err.contains("does not look like any of the available sketches")); + assert!(err.contains("Available sketches:")); + assert!(err.contains("sketch")); + assert!(err.contains("MyProject")); + } + + #[test] + fn test_find_sketch_by_partial_name_reports_ambiguous_matches() { + let dir = temp_dir(); + let root = dir.path(); + for name in ["examples/sketch1", "examples/sketch2"] { + let path = root.join(name); + fs::create_dir_all(&path).unwrap(); + let file_name = path.file_name().and_then(|value| value.to_str()).unwrap(); + fs::write(path.join(format!("{file_name}.ino")), b"void setup() {}").unwrap(); + } + + let err = find_sketch_by_partial_name("sketch", root) + .unwrap_err() + .to_string(); + assert!(err.contains("Multiple sketch directories found matching 'sketch'")); + assert!(err.contains("sketch1")); + assert!(err.contains("sketch2")); + } } diff --git a/crates/fastled-py/Cargo.toml b/crates/fastled-py/Cargo.toml index 8939db8d..b7000a10 100644 --- a/crates/fastled-py/Cargo.toml +++ b/crates/fastled-py/Cargo.toml @@ -14,3 +14,7 @@ crate-type = ["cdylib", "lib"] [dependencies] pyo3 = { workspace = true } +fastled-cli = { path = "../fastled-cli" } +serde_json = { workspace = true } +zip = { workspace = true } +strsim = { workspace = true } diff --git a/crates/fastled-py/src/lib.rs b/crates/fastled-py/src/lib.rs index a176ae54..4c0fc9aa 100644 --- a/crates/fastled-py/src/lib.rs +++ b/crates/fastled-py/src/lib.rs @@ -1,6 +1,16 @@ +use fastled_cli::install; +use fastled_cli::project; +use pyo3::exceptions::{PyRuntimeError, PyValueError}; use pyo3::prelude::*; -use std::path::PathBuf; +use pyo3::types::{PyBytes, PyDict, PyModule}; +use serde_json::json; +use std::collections::HashMap; +use std::fs; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; use std::process::Command; +use std::time::Instant; +use zip::write::SimpleFileOptions; // --------------------------------------------------------------------------- // Internal: Tauri viewer discovery (mirrors viewer.rs in fastled-cli) @@ -61,6 +71,749 @@ fn find_workspace_root_py() -> Option { None } +// --------------------------------------------------------------------------- +// Internal: Native BuildService +// --------------------------------------------------------------------------- + +#[derive(Clone)] +struct BuildState { + build_mode: String, + profile: bool, + fastled_path: Option, +} + +fn normalize_path(path: &Path) -> PathBuf { + fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) +} + +fn normalize_optional_path(path: Option<&str>) -> Option { + path.map(PathBuf::from) + .map(|value| normalize_path(&value).to_string_lossy().into_owned()) +} + +fn resolve_state_key(path: &Path) -> PathBuf { + normalize_path(path) +} + +fn state_file(output_dir: &Path) -> PathBuf { + output_dir.join(".fastled_build_state.json") +} + +fn write_state(output_dir: &Path, state: &BuildState) { + let payload = json!({ + "build_mode": state.build_mode, + "profile": state.profile, + "fastled_path": state.fastled_path, + }); + if let Ok(serialized) = serde_json::to_string(&payload) { + let _ = fs::write(state_file(output_dir), serialized); + } +} + +fn read_state(output_dir: &Path) -> Option { + let payload = fs::read_to_string(state_file(output_dir)).ok()?; + let value: serde_json::Value = serde_json::from_str(&payload).ok()?; + let build_mode = value.get("build_mode")?.as_str()?.to_string(); + let profile = value.get("profile")?.as_bool()?; + let fastled_path = match value.get("fastled_path") { + Some(serde_json::Value::String(path)) => Some(path.clone()), + Some(serde_json::Value::Null) | None => None, + _ => return None, + }; + Some(BuildState { + build_mode, + profile, + fastled_path, + }) +} + +fn collect_files(dir: &Path, out: &mut Vec) -> io::Result<()> { + for entry in fs::read_dir(dir)? { + let entry = entry?; + let path = entry.path(); + if path.is_dir() { + collect_files(&path, out)?; + } else if path.is_file() { + out.push(path); + } + } + Ok(()) +} + +fn zip_output(output_dir: &Path) -> io::Result> { + let mut files = Vec::new(); + collect_files(output_dir, &mut files)?; + files.sort(); + + let cursor = std::io::Cursor::new(Vec::new()); + let mut zip = zip::ZipWriter::new(cursor); + let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + + for file_path in files { + let relative = file_path + .strip_prefix(output_dir) + .unwrap_or(file_path.as_path()) + .to_string_lossy() + .replace('\\', "/"); + zip.start_file(relative, options)?; + zip.write_all(&fs::read(&file_path)?)?; + } + + Ok(zip.finish()?.into_inner()) +} + +fn discover_artifacts(output_dir: &Path) -> HashMap { + let mut artifacts = HashMap::new(); + let candidates = [ + ("js", output_dir.join("fastled.js")), + ("wasm", output_dir.join("fastled.wasm")), + ("dwarf", output_dir.join("fastled.wasm.dwarf")), + ("symbol_map", output_dir.join("fastled.js.symbols")), + ("frontend_assets", output_dir.join("assets")), + ]; + for (name, path) in candidates { + if path.exists() { + artifacts.insert(name.to_string(), path.to_string_lossy().into_owned()); + } + } + if !artifacts.contains_key("frontend_assets") && output_dir.exists() { + artifacts.insert( + "frontend_assets".to_string(), + output_dir.to_string_lossy().into_owned(), + ); + } + artifacts +} + +fn python_path(py: Python<'_>, path: &Path) -> PyResult> { + let pathlib = PyModule::import(py, "pathlib")?; + let cls = pathlib.getattr("Path")?; + Ok(cls + .call1((path.to_string_lossy().as_ref(),))? + .into_any() + .unbind()) +} + +fn py_fspath(py: Python<'_>, value: &Bound<'_, PyAny>) -> PyResult { + let os = PyModule::import(py, "os")?; + let fspath = os.getattr("fspath")?; + let path_value = fspath.call1((value,))?; + let path_str: String = path_value.extract()?; + Ok(PathBuf::from(path_str)) +} + +// --------------------------------------------------------------------------- +// Internal: string_diff port +// --------------------------------------------------------------------------- + +fn token_sort_ratio(a: &str, b: &str) -> f64 { + let mut a_tokens: Vec<&str> = a.split_whitespace().collect(); + let mut b_tokens: Vec<&str> = b.split_whitespace().collect(); + a_tokens.sort_unstable(); + b_tokens.sort_unstable(); + let a_sorted = a_tokens.join(" "); + let b_sorted = b_tokens.join(" "); + ratcliff_obershelp_ratio(&a_sorted, &b_sorted) * 100.0 +} + +fn ratcliff_obershelp_ratio(a: &str, b: &str) -> f64 { + if a.is_empty() && b.is_empty() { + return 1.0; + } + let a_bytes = a.as_bytes(); + let b_bytes = b.as_bytes(); + let matches = matching_chars(a_bytes, b_bytes) as f64; + (2.0 * matches) / ((a_bytes.len() + b_bytes.len()) as f64) +} + +fn matching_chars(a: &[u8], b: &[u8]) -> usize { + let Some((a_pos, b_pos, len)) = longest_common_substring(a, b) else { + return 0; + }; + if len == 0 { + return 0; + } + + len + matching_chars(&a[..a_pos], &b[..b_pos]) + + matching_chars(&a[a_pos + len..], &b[b_pos + len..]) +} + +fn longest_common_substring(a: &[u8], b: &[u8]) -> Option<(usize, usize, usize)> { + if a.is_empty() || b.is_empty() { + return None; + } + + let mut best = (0usize, 0usize, 0usize); + let mut dp = vec![0usize; b.len() + 1]; + + for (i, a_byte) in a.iter().enumerate() { + for j in (0..b.len()).rev() { + if *a_byte == b[j] { + dp[j + 1] = dp[j] + 1; + if dp[j + 1] > best.2 { + best = (i + 1 - dp[j + 1], j + 1 - dp[j + 1], dp[j + 1]); + } + } else { + dp[j + 1] = 0; + } + } + } + + if best.2 == 0 { + None + } else { + Some(best) + } +} + +fn filter_out_obvious_bad_choices(input_str: &str, string_list: &[String]) -> Vec { + if input_str.trim().is_empty() { + return string_list.to_vec(); + } + + let input_chars: std::collections::HashSet = input_str.to_lowercase().chars().collect(); + let mut filtered = Vec::new(); + + for candidate in string_list { + let candidate_chars: std::collections::HashSet = + candidate.to_lowercase().chars().collect(); + let common_chars = input_chars.intersection(&candidate_chars).count(); + if (common_chars as f64) >= (input_chars.len() as f64 / 2.0) { + filtered.push(candidate.clone()); + } + } + + filtered +} + +fn is_in_order_match_impl(input_str: &str, other: &str) -> bool { + let input_chars: Vec = input_str + .chars() + .filter(|c| *c != ' ') + .map(|c| c.to_ascii_lowercase()) + .collect(); + let other_chars: Vec = other.chars().map(|c| c.to_ascii_lowercase()).collect(); + + let mut input_index = 0usize; + let mut other_index = 0usize; + + while input_index < input_chars.len() && other_index < other_chars.len() { + if input_chars[input_index] == other_chars[other_index] { + input_index += 1; + } + other_index += 1; + } + + input_index == input_chars.len() +} + +fn normalize_for_matching(value: &str, ignore_case: bool) -> String { + if ignore_case { + value.to_lowercase() + } else { + value.to_owned() + } +} + +fn string_diff_impl( + input_string: &str, + string_list: &[String], + ignore_case: bool, +) -> Vec<(f64, String)> { + if input_string.trim().is_empty() { + return string_list + .iter() + .enumerate() + .map(|(i, s)| (i as f64, s.clone())) + .collect(); + } + + if string_list.is_empty() { + return Vec::new(); + } + + let original_string_list = string_list.to_vec(); + let normalized_input = normalize_for_matching(input_string, ignore_case); + let normalized_strings: Vec = string_list + .iter() + .map(|s| normalize_for_matching(s, ignore_case)) + .collect(); + let normalized_to_original: HashMap = normalized_strings + .iter() + .cloned() + .zip(string_list.iter().cloned()) + .collect(); + + let exact_matches: Vec = normalized_strings + .iter() + .filter(|s| **s == normalized_input) + .cloned() + .collect(); + let substring_matches: Vec = normalized_strings + .iter() + .filter(|s| s.contains(&normalized_input)) + .cloned() + .collect(); + + if exact_matches.len() == 1 && substring_matches.len() > 1 { + let exact_match = &exact_matches[0]; + let other_substring_matches: Vec<&String> = substring_matches + .iter() + .filter(|s| *s != exact_match) + .collect(); + let mut should_prioritize_exact = true; + let original_exact_match = normalized_to_original + .get(exact_match) + .cloned() + .unwrap_or_else(|| exact_match.clone()); + + for other_match in other_substring_matches { + let original_other_match = normalized_to_original + .get(other_match) + .cloned() + .unwrap_or_else(|| other_match.clone()); + + if !original_other_match + .to_lowercase() + .starts_with(&original_exact_match.to_lowercase()) + { + should_prioritize_exact = false; + break; + } + + let remainder = &original_other_match[original_exact_match.len()..]; + if remainder + .chars() + .next() + .map(|c| c.is_uppercase()) + .unwrap_or(false) + { + if original_exact_match.len() <= 4 && remainder.len() >= 6 { + continue; + } + should_prioritize_exact = false; + break; + } + + should_prioritize_exact = false; + break; + } + + if should_prioritize_exact { + return exact_matches + .iter() + .enumerate() + .map(|(i, s)| { + ( + i as f64, + normalized_to_original + .get(s) + .cloned() + .unwrap_or_else(|| s.clone()), + ) + }) + .collect(); + } + + let should_apply_char_filter = original_exact_match.len() >= 5 + && original_exact_match.chars().any(|c| c.is_ascii_digit()) + && original_exact_match + .chars() + .last() + .map(|c| c.is_ascii_digit() || c.is_ascii_lowercase()) + .unwrap_or(false); + + if should_apply_char_filter { + let max_extra_chars = if original_exact_match.len() <= 6 { + std::cmp::min(10usize, original_exact_match.len() * 2) + } else { + 12usize + }; + + let filtered_matches: Vec = substring_matches + .iter() + .filter_map(|s| { + let original = normalized_to_original + .get(s) + .cloned() + .unwrap_or_else(|| s.clone()); + if s == exact_match { + Some(s.clone()) + } else { + let extra_chars = original.len().saturating_sub(original_exact_match.len()); + (extra_chars <= max_extra_chars).then_some(s.clone()) + } + }) + .collect(); + + return filtered_matches + .iter() + .enumerate() + .map(|(i, s)| { + ( + i as f64, + normalized_to_original + .get(s) + .cloned() + .unwrap_or_else(|| s.clone()), + ) + }) + .collect(); + } + + return substring_matches + .iter() + .enumerate() + .map(|(i, s)| { + ( + i as f64, + normalized_to_original + .get(s) + .cloned() + .unwrap_or_else(|| s.clone()), + ) + }) + .collect(); + } + + if !exact_matches.is_empty() && substring_matches.len() == 1 { + return exact_matches + .iter() + .enumerate() + .map(|(i, s)| { + ( + i as f64, + normalized_to_original + .get(s) + .cloned() + .unwrap_or_else(|| s.clone()), + ) + }) + .collect(); + } + + let mut working_list = normalized_strings.clone(); + if normalized_input.trim().chars().count() >= 3 { + let filtered = filter_out_obvious_bad_choices(&normalized_input, &working_list); + if !filtered.is_empty() { + working_list = filtered; + } + } + + if !substring_matches.is_empty() { + return substring_matches + .iter() + .enumerate() + .map(|(i, s)| { + ( + i as f64, + normalized_to_original + .get(s) + .cloned() + .unwrap_or_else(|| s.clone()), + ) + }) + .collect(); + } + + let in_order_matches: Vec = working_list + .iter() + .filter(|s| is_in_order_match_impl(&normalized_input, s)) + .cloned() + .collect(); + if !in_order_matches.is_empty() { + working_list = in_order_matches; + } + + let mut distances: Vec = working_list + .iter() + .map(|s| 1.0 / (token_sort_ratio(&normalized_input, s) + 1.0)) + .collect(); + + if distances.is_empty() { + working_list = original_string_list + .iter() + .map(|s| normalize_for_matching(s, ignore_case)) + .collect(); + distances = working_list + .iter() + .map(|s| 1.0 / (token_sort_ratio(&normalized_input, s) + 1.0)) + .collect(); + } + + let min_distance = distances + .iter() + .fold(f64::INFINITY, |best, value| best.min(*value)); + + distances + .iter() + .enumerate() + .filter(|(_, distance)| (**distance - min_distance).abs() < 1e-12) + .map(|(i, _)| { + let normalized = &working_list[i]; + ( + i as f64, + normalized_to_original + .get(normalized) + .cloned() + .unwrap_or_else(|| normalized.clone()), + ) + }) + .collect() +} + +#[pyclass(name = "NativeBuildService")] +struct NativeBuildService { + toolchains: HashMap, Py>, + states: HashMap, +} + +#[pymethods] +impl NativeBuildService { + #[new] + fn new() -> Self { + Self { + toolchains: HashMap::new(), + states: HashMap::new(), + } + } + + #[pyo3(signature = (toolchain, fastled_path=None))] + fn register_toolchain(&mut self, toolchain: Py, fastled_path: Option<&str>) { + let key = normalize_optional_path(fastled_path); + self.toolchains.insert(key, toolchain); + } + + #[pyo3(signature = (sketch_dir, build_mode, profile=false, fastled_path=None, force_clean=false))] + fn detect_strategy( + &mut self, + sketch_dir: &str, + build_mode: &str, + profile: bool, + fastled_path: Option<&str>, + force_clean: bool, + ) -> String { + let sketch_dir = PathBuf::from(sketch_dir); + self.detect_strategy_inner( + &sketch_dir, + build_mode, + profile, + normalize_optional_path(fastled_path), + force_clean, + ) + } + + #[pyo3(signature = (sketch_dir, build_mode, build_mode_obj, profile=false, fastled_path=None, force_clean=false))] + fn build( + &mut self, + py: Python<'_>, + sketch_dir: &str, + build_mode: &str, + build_mode_obj: Py, + profile: bool, + fastled_path: Option<&str>, + force_clean: bool, + ) -> PyResult> { + let sketch_dir = PathBuf::from(sketch_dir); + let output_dir = sketch_dir.join("fastled_js"); + let fastled_path = normalize_optional_path(fastled_path); + let strategy = self.detect_strategy_inner( + &sketch_dir, + build_mode, + profile, + fastled_path.clone(), + force_clean, + ); + + if force_clean && output_dir.exists() { + let _ = fs::remove_dir_all(&output_dir); + } + + let toolchain = self + .toolchains + .get(&fastled_path) + .map(|toolchain| toolchain.clone_ref(py)) + .ok_or_else(|| PyRuntimeError::new_err("No toolchain registered for build"))?; + + fs::create_dir_all(&output_dir).map_err(|err| PyRuntimeError::new_err(err.to_string()))?; + + let start = Instant::now(); + let result_payload = match self.run_toolchain( + py, + toolchain, + &sketch_dir, + &output_dir, + build_mode_obj, + profile, + ) { + Ok(js_file) => { + let compile_time = start.elapsed().as_secs_f64(); + let zip_start = Instant::now(); + let zip_bytes = zip_output(&output_dir) + .map_err(|err| PyRuntimeError::new_err(err.to_string()))?; + let zip_time = zip_start.elapsed().as_secs_f64(); + + let state = BuildState { + build_mode: build_mode.to_string(), + profile, + fastled_path: fastled_path.clone(), + }; + self.states + .insert(resolve_state_key(&sketch_dir), state.clone()); + write_state(&output_dir, &state); + + Self::build_payload( + py, + true, + format!( + "Native compilation successful!\nOutput: {}\nWASM: {}", + js_file.display(), + js_file.with_extension("wasm").display() + ), + zip_bytes, + zip_time, + compile_time, + strategy, + &output_dir, + )? + } + Err(err) => { + if err.is_instance_of::(py) { + return Err(err); + } + let compile_time = start.elapsed().as_secs_f64(); + Self::build_payload( + py, + false, + format!("Native compilation failed: {err}"), + Vec::new(), + 0.0, + compile_time, + strategy, + &output_dir, + )? + } + }; + + Ok(result_payload) + } + + fn purge(&mut self, sketch_dir: &str) { + let sketch_dir = PathBuf::from(sketch_dir); + self.states.remove(&resolve_state_key(&sketch_dir)); + let output_dir = sketch_dir.join("fastled_js"); + if output_dir.exists() { + let _ = fs::remove_dir_all(output_dir); + } + } +} + +impl NativeBuildService { + fn detect_strategy_inner( + &mut self, + sketch_dir: &Path, + build_mode: &str, + profile: bool, + fastled_path: Option, + force_clean: bool, + ) -> String { + if force_clean { + return "cold".to_string(); + } + + let output_dir = sketch_dir.join("fastled_js"); + if !output_dir.exists() { + return "cold".to_string(); + } + + let required_artifacts = [ + output_dir.join("fastled.js"), + output_dir.join("fastled.wasm"), + ]; + if required_artifacts.iter().any(|path| !path.exists()) { + return "cold".to_string(); + } + + let sketch_key = resolve_state_key(sketch_dir); + let previous = if let Some(state) = self.states.get(&sketch_key).cloned() { + Some(state) + } else if let Some(state) = read_state(&output_dir) { + self.states.insert(sketch_key.clone(), state.clone()); + Some(state) + } else { + None + }; + + let Some(previous) = previous else { + return "cold".to_string(); + }; + + if previous.fastled_path != fastled_path { + return "cold".to_string(); + } + if previous.build_mode != build_mode { + return "cold".to_string(); + } + if previous.profile != profile { + return "cold".to_string(); + } + + "incremental".to_string() + } + + fn run_toolchain( + &self, + py: Python<'_>, + toolchain: Py, + sketch_dir: &Path, + output_dir: &Path, + build_mode_obj: Py, + profile: bool, + ) -> PyResult { + let kwargs = PyDict::new(py); + kwargs.set_item("sketch_dir", python_path(py, sketch_dir)?)?; + kwargs.set_item("output_dir", python_path(py, output_dir)?)?; + kwargs.set_item("build_mode", build_mode_obj)?; + kwargs.set_item("profile", profile)?; + + let js_file = toolchain + .bind(py) + .call_method("compile", (), Some(&kwargs))?; + py_fspath(py, &js_file) + } + + fn build_payload( + py: Python<'_>, + success: bool, + stdout: String, + zip_bytes: Vec, + zip_time: f64, + sketch_time: f64, + strategy: String, + output_dir: &Path, + ) -> PyResult> { + let payload = PyDict::new(py); + let artifacts = PyDict::new(py); + for (name, path) in discover_artifacts(output_dir) { + artifacts.set_item(name, path)?; + } + + payload.set_item("success", success)?; + payload.set_item("stdout", stdout)?; + payload.set_item("hash_value", py.None())?; + payload.set_item("zip_bytes", PyBytes::new(py, &zip_bytes))?; + payload.set_item("zip_time", zip_time)?; + payload.set_item("libfastled_time", 0.0)?; + payload.set_item("sketch_time", sketch_time)?; + payload.set_item("response_processing_time", 0.0)?; + payload.set_item("strategy", strategy)?; + payload.set_item("output_dir", output_dir.to_string_lossy().into_owned())?; + payload.set_item("artifacts", artifacts)?; + + Ok(payload.unbind()) + } +} + // --------------------------------------------------------------------------- // PyO3 functions // --------------------------------------------------------------------------- @@ -72,15 +825,6 @@ fn version() -> &'static str { } /// Return whether the native Rust file watcher is available in this build. -/// -/// Python callers can use this to decide whether to prefer the Rust watcher -/// over the Python watchdog implementation. -/// -/// ```python -/// from fastled._native import watch_available -/// if watch_available(): -/// print("native watcher ready") -/// ``` #[pyfunction] fn watch_available() -> bool { true @@ -88,12 +832,6 @@ fn watch_available() -> bool { /// Return whether the native Rust archive download and extraction utilities /// are available in this build. -/// -/// ```python -/// from fastled._native import archive_available -/// if archive_available(): -/// print("native archive support ready") -/// ``` #[pyfunction] fn archive_available() -> bool { true @@ -101,25 +839,105 @@ fn archive_available() -> bool { /// Return whether the native Rust project initialisation and sketch detection /// utilities are available in this build. -/// -/// ```python -/// from fastled._native import project_available -/// if project_available(): -/// print("native project init ready") -/// ``` #[pyfunction] fn project_available() -> bool { true } +#[pyfunction(signature = (directory=None))] +fn find_sketch_directories(directory: Option<&str>) -> PyResult> { + let root = directory + .map(PathBuf::from) + .unwrap_or(std::env::current_dir()?); + Ok(project::find_sketches(&root) + .into_iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect()) +} + +#[pyfunction(signature = (partial_name, search_dir=None))] +fn find_sketch_by_partial_name(partial_name: &str, search_dir: Option<&str>) -> PyResult { + let root = search_dir + .map(PathBuf::from) + .unwrap_or(std::env::current_dir()?); + project::find_sketch_by_partial_name(partial_name, &root) + .map(|path| path.to_string_lossy().into_owned()) + .map_err(|err| PyValueError::new_err(err.to_string())) +} + +#[pyfunction(signature = (path=None))] +fn looks_like_fastled_repo(path: Option<&str>) -> PyResult { + let directory = path.map(PathBuf::from).unwrap_or(std::env::current_dir()?); + Ok(project::is_fastled_repo(&directory)) +} + +#[pyfunction(signature = (path=None, quick=false))] +fn looks_like_sketch_directory(path: Option<&str>, quick: bool) -> PyResult { + let Some(directory) = path + .map(PathBuf::from) + .or_else(|| std::env::current_dir().ok()) + else { + return Ok(false); + }; + Ok(project::looks_like_sketch_directory(&directory, quick)) +} + +#[pyfunction(signature = (start=None, max_depth=10))] +fn find_fastled_repo_upwards(start: Option<&str>, max_depth: usize) -> PyResult> { + let directory = start.map(PathBuf::from).unwrap_or(std::env::current_dir()?); + Ok(project::find_fastled_repo_upwards(&directory, max_depth) + .map(|path| path.to_string_lossy().into_owned())) +} + +#[pyfunction] +fn collect_examples(examples_dir: &str) -> Vec { + project::collect_examples(&PathBuf::from(examples_dir)) +} + +#[pyfunction] +fn find_example_in_repo(repo_root: &str, example: &str) -> Option { + project::find_example_in_repo(&PathBuf::from(repo_root), example) + .map(|path| path.to_string_lossy().into_owned()) +} + +#[pyfunction(signature = (example_name, dest, branch=None))] +fn init_example(example_name: &str, dest: &str, branch: Option<&str>) -> PyResult { + project::init_example(example_name, &PathBuf::from(dest), branch) + .map(|path| path.to_string_lossy().into_owned()) + .map_err(|err| PyValueError::new_err(err.to_string())) +} + +#[pyfunction(signature = (ref_name=None))] +fn ensure_fastled_repo(ref_name: Option<&str>) -> PyResult { + install::ensure_fastled_repo(ref_name) + .map(|path| path.to_string_lossy().into_owned()) + .map_err(|err| PyValueError::new_err(err.to_string())) +} + +#[pyfunction] +fn read_fastled_json_ref(directory: &str) -> Option { + project::read_fastled_json_ref(&PathBuf::from(directory)) +} + +#[pyfunction(signature = (repo_root, example_name, output_dir, ref_name=None))] +fn init_example_from_repo( + repo_root: &str, + example_name: &str, + output_dir: &str, + ref_name: Option<&str>, +) -> PyResult { + project::init_example_from_repo( + &PathBuf::from(repo_root), + example_name, + &PathBuf::from(output_dir), + ref_name, + ) + .map(|path| path.to_string_lossy().into_owned()) + .map_err(|err| PyValueError::new_err(err.to_string())) +} + /// Return whether the native Rust build orchestration module is available in /// this build. -/// -/// ```python -/// from fastled._native import build_available -/// if build_available(): -/// print("native build orchestration ready") -/// ``` #[pyfunction] fn build_available() -> bool { true @@ -127,28 +945,91 @@ fn build_available() -> bool { /// Return whether the native Tauri viewer binary (`fastled-viewer`) can be /// found alongside the CLI, in the Cargo target directory, or on PATH. -/// -/// Python callers can use this to decide whether to prefer the native viewer -/// over the legacy Flask + Playwright browser experience. -/// -/// ```python -/// from fastled._native import viewer_available -/// if viewer_available(): -/// print("native viewer ready") -/// ``` #[pyfunction] fn viewer_available() -> bool { find_tauri_viewer_path().is_some() } +#[pyfunction] +fn is_in_order_match(input_str: &str, other: &str) -> bool { + is_in_order_match_impl(input_str, other) +} + +#[pyfunction(signature = (input_string, string_list, ignore_case=true))] +fn string_diff( + input_string: &str, + string_list: Vec, + ignore_case: bool, +) -> Vec<(f64, String)> { + string_diff_impl(input_string, &string_list, ignore_case) +} + /// FastLED native extension module. #[pymodule] fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add_class::()?; m.add_function(wrap_pyfunction!(version, m)?)?; m.add_function(wrap_pyfunction!(watch_available, m)?)?; m.add_function(wrap_pyfunction!(archive_available, m)?)?; m.add_function(wrap_pyfunction!(project_available, m)?)?; + m.add_function(wrap_pyfunction!(find_sketch_directories, m)?)?; + m.add_function(wrap_pyfunction!(find_sketch_by_partial_name, m)?)?; + m.add_function(wrap_pyfunction!(looks_like_fastled_repo, m)?)?; + m.add_function(wrap_pyfunction!(looks_like_sketch_directory, m)?)?; + m.add_function(wrap_pyfunction!(find_fastled_repo_upwards, m)?)?; + m.add_function(wrap_pyfunction!(collect_examples, m)?)?; + m.add_function(wrap_pyfunction!(find_example_in_repo, m)?)?; + m.add_function(wrap_pyfunction!(init_example, m)?)?; + m.add_function(wrap_pyfunction!(ensure_fastled_repo, m)?)?; + m.add_function(wrap_pyfunction!(read_fastled_json_ref, m)?)?; + m.add_function(wrap_pyfunction!(init_example_from_repo, m)?)?; m.add_function(wrap_pyfunction!(build_available, m)?)?; m.add_function(wrap_pyfunction!(viewer_available, m)?)?; + m.add_function(wrap_pyfunction!(is_in_order_match, m)?)?; + m.add_function(wrap_pyfunction!(string_diff, m)?)?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::{is_in_order_match_impl, string_diff_impl}; + + #[test] + fn test_native_is_in_order_match() { + assert!(is_in_order_match_impl("wave 2d", "Wave2d")); + assert!(!is_in_order_match_impl("wz", "Wave2d")); + } + + #[test] + fn test_native_string_diff_prefers_fxwave2d_for_fxwave() { + let haystack = vec![ + "examples\\Wave2d".to_owned(), + "examples\\FxWave2d".to_owned(), + "examples\\Blink".to_owned(), + ]; + let result = string_diff_impl("FxWave", &haystack, true); + assert_eq!(result[0].1, "examples\\FxWave2d"); + } + + #[test] + fn test_native_string_diff_prioritizes_exact_wasm_match() { + let haystack = vec!["wasm".to_owned(), "WasmScreenCoords".to_owned()]; + let result = string_diff_impl("Wasm", &haystack, true); + assert_eq!(result, vec![(0.0, "wasm".to_owned())]); + } + + #[test] + fn test_native_string_diff_returns_variants_for_fire2012() { + let haystack = vec![ + "Fire2012".to_owned(), + "Fire2012WithPalette".to_owned(), + "FxFire2012".to_owned(), + "VeryLongPrefixFire2012".to_owned(), + ]; + let result = string_diff_impl("Fire2012", &haystack, true); + let names: Vec = result.into_iter().map(|(_, name)| name).collect(); + assert!(names.contains(&"Fire2012".to_owned())); + assert!(names.contains(&"FxFire2012".to_owned())); + assert!(!names.contains(&"VeryLongPrefixFire2012".to_owned())); + } +} diff --git a/src/fastled/_rust_cli.py b/src/fastled/_rust_cli.py index 808c7a01..cc1b50a2 100644 --- a/src/fastled/_rust_cli.py +++ b/src/fastled/_rust_cli.py @@ -16,6 +16,7 @@ import os import shutil +import subprocess import sys from pathlib import Path @@ -24,31 +25,37 @@ def _exe_name() -> str: return "fastled.exe" if sys.platform == "win32" else "fastled" -def find_rust_fastled_cli() -> Path | None: - """Return the path to the Rust ``fastled`` binary, or ``None``.""" - exe = _exe_name() - - # 1. Workspace target/ tree (dev / editable). +def _find_workspace_root() -> Path | None: current = Path(__file__).resolve().parent for _ in range(10): if (current / "Cargo.toml").is_file(): - for profile in ("release", "debug"): - candidate = current / "target" / profile / exe - if candidate.is_file(): - return candidate - target_dir = current / "target" - if target_dir.is_dir(): - for arch_dir in target_dir.iterdir(): - if arch_dir.is_dir() and not arch_dir.name.startswith("."): - for profile in ("release", "debug"): - candidate = arch_dir / profile / exe - if candidate.is_file(): - return candidate - break + return current parent = current.parent if parent == current: break current = parent + return None + + +def find_rust_fastled_cli() -> Path | None: + """Return the path to the Rust ``fastled`` binary, or ``None``.""" + exe = _exe_name() + + # 1. Workspace target/ tree (dev / editable). + workspace_root = _find_workspace_root() + if workspace_root is not None: + for profile in ("release", "debug"): + candidate = workspace_root / "target" / profile / exe + if candidate.is_file(): + return candidate + target_dir = workspace_root / "target" + if target_dir.is_dir(): + for arch_dir in target_dir.iterdir(): + if arch_dir.is_dir() and not arch_dir.name.startswith("."): + for profile in ("release", "debug"): + candidate = arch_dir / profile / exe + if candidate.is_file(): + return candidate # 2. cargo-binstall install location. cargo_home = os.environ.get("CARGO_HOME") @@ -68,3 +75,21 @@ def find_rust_fastled_cli() -> Path | None: if found: return Path(found) return None + + +def invoke_rust_fastled_cli(argv: list[str] | None = None) -> int: + """Run the Rust FastLED CLI and return its exit code.""" + args = list(argv or []) + cli = find_rust_fastled_cli() + if cli is not None: + return subprocess.run([str(cli), *args], check=False).returncode + + workspace_root = _find_workspace_root() + if workspace_root is not None: + return subprocess.run( + ["cargo", "run", "--quiet", "--bin", "fastled", "--", *args], + check=False, + cwd=workspace_root, + ).returncode + + raise RuntimeError("Could not locate the Rust fastled CLI binary.") diff --git a/src/fastled/app.py b/src/fastled/app.py index 29da625c..aa88f5ab 100644 --- a/src/fastled/app.py +++ b/src/fastled/app.py @@ -1,120 +1,14 @@ -""" -Uses native EMSDK to compile FastLED sketches to WASM. -""" +"""Compatibility entry point that forwards to the native Rust CLI.""" -import os import sys -from pathlib import Path -from fastled.emoji_util import EMO -from fastled.interrupts import handle_keyboard_interrupt -from fastled.parse_args import parse_args - - -def purge_cache(cache_dir: Path, fastled_path: Path | str | None = None) -> None: - """Purge cached FastLED repo and WASM build artifacts.""" - import shutil - - if cache_dir.exists(): - shutil.rmtree(cache_dir, ignore_errors=True) - print(f"Purged FastLED cache: {cache_dir}") - else: - print("No FastLED cache to purge.") - # Also purge WASM build caches in the fastled_path if provided - if fastled_path: - fastled_build = Path(fastled_path) / ".build" - for wasm_dir in fastled_build.glob("meson-wasm-*"): - for stale in [ - "wasm_ld_args.json", - "wasm_ld_args.key", - "fastled_glue.js", - "js_glue_fingerprint", - "link_environment_fingerprint", - "libemscripten_js_symbols.so", - ]: - f = wasm_dir / stale - if f.exists(): - f.unlink() - print(f"Purged: {f}") +from fastled._rust_cli import invoke_rust_fastled_cli def main() -> int: - from fastled import __version__ - - args = parse_args() - - # Handle --install command early - if args.install: - from fastled.install.main import fastled_install - - result = fastled_install( - dry_run=args.dry_run, no_interactive=args.no_interactive - ) - return 0 if result else 1 - - if args.serve_dir is not None: - # --serve-dir is handled natively by the Rust CLI (main.rs). - # If we reach here, the user called `python -m fastled.app --serve-dir` - # directly, which is no longer supported. - print( - "Error: --serve-dir is now handled by the Rust CLI.\n" - "Use `fastled --serve-dir ` instead." - ) - return 1 - - # Handle --purge: clear cached FastLED repo and WASM build artifacts - if args.purge: - cache_dir = Path.home() / ".fastled" / "cache" - purge_cache(cache_dir, args.fastled_path) - if args.directory is None: - return 0 - - just_compile: bool = args.just_compile - directory: Path | None = Path(args.directory) if args.directory else None - - # now it is safe to print out the version - print(f"FastLED version: {__version__}") - - # Print current working directory - print(f"Current working directory: {os.getcwd()}") - - # Check if Playwright browsers are installed - playwright_dir = Path.home() / ".fastled" / "playwright" - if playwright_dir.exists() and any(playwright_dir.iterdir()): - print( - f"{EMO('theatre', '*')} Playwright browsers available at: {playwright_dir}" - ) - - # Native compilation mode (the only mode now) - from fastled.compile_native import run_native_compile - from fastled.types import BuildMode - - if directory is None: - print("Error: No sketch directory specified for compilation.") - return 1 - - print("Running in native EMSDK compilation mode.") - build_mode = BuildMode.from_args(args) - return run_native_compile( - directory=directory, - build_mode=build_mode, - profile=args.profile, - open_browser=not just_compile, - keep_running=not just_compile, - enable_https=args.enable_https, - fastled_path=args.fastled_path, - app=args.app, - ) + """Run the native Rust CLI with the current argv.""" + return invoke_rust_fastled_cli(sys.argv[1:]) if __name__ == "__main__": - # Note that the entry point for the exe is in cli.py - try: - sys.exit(main()) - except KeyboardInterrupt as ki: - print("\nExiting from main...") - handle_keyboard_interrupt(ki) - sys.exit(1) - except Exception as e: - print(f"Error: {e}") - sys.exit(1) + sys.exit(main()) diff --git a/src/fastled/build_service.py b/src/fastled/build_service.py index 216cc65b..7652e0d8 100644 --- a/src/fastled/build_service.py +++ b/src/fastled/build_service.py @@ -7,12 +7,21 @@ import zipfile from dataclasses import dataclass from pathlib import Path -from typing import Protocol +from typing import Any, Protocol, cast from fastled.build_types import BuildRequest, BuildResult, BuildStrategy from fastled.interrupts import handle_keyboard_interrupt from fastled.types import BuildMode, CompileResult +try: + from fastled._native import NativeBuildService as _NativeBuildService +except ImportError: + _NativeBuildService = None + + +def _toolchain_key(fastled_path: Path | None) -> str | None: + return str(fastled_path.resolve()) if fastled_path else None + class _CompilerToolchain(Protocol): def compile( @@ -31,7 +40,7 @@ class _BuildState: fastled_path: str | None -class BuildService: +class _PythonBuildService: def __init__(self) -> None: self._toolchains: dict[str | None, _CompilerToolchain] = {} self._states: dict[Path, _BuildState] = {} @@ -39,8 +48,7 @@ def __init__(self) -> None: def register_toolchain( self, fastled_path: Path | None, toolchain: _CompilerToolchain ) -> None: - key = str(fastled_path.resolve()) if fastled_path else None - self._toolchains[key] = toolchain + self._toolchains[_toolchain_key(fastled_path)] = toolchain def build(self, request: BuildRequest) -> BuildResult: from fastled.toolchain.emscripten import EmscriptenToolchain @@ -51,9 +59,7 @@ def build(self, request: BuildRequest) -> BuildResult: if request.force_clean and output_dir.exists(): shutil.rmtree(output_dir, ignore_errors=True) - toolchain_key = ( - str(request.fastled_path.resolve()) if request.fastled_path else None - ) + toolchain_key = _toolchain_key(request.fastled_path) toolchain = self._toolchains.get(toolchain_key) if toolchain is None: toolchain = EmscriptenToolchain(fastled_path=request.fastled_path) @@ -142,9 +148,7 @@ def detect_strategy(self, request: BuildRequest) -> BuildStrategy: if previous is None: return "cold" - current_fastled_path = ( - str(request.fastled_path.resolve()) if request.fastled_path else None - ) + current_fastled_path = _toolchain_key(request.fastled_path) if previous.fastled_path != current_fastled_path: return "cold" if previous.build_mode != request.build_mode.value: @@ -207,12 +211,10 @@ def _read_state(cls, output_dir: Path) -> _BuildState | None: @staticmethod def _zip_output(output_dir: Path) -> bytes: zip_buffer = io.BytesIO() - zip_start = time.time() with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf: for file_path in output_dir.rglob("*"): if file_path.is_file(): zf.write(file_path, file_path.relative_to(output_dir)) - _ = time.time() - zip_start return zip_buffer.getvalue() @staticmethod @@ -231,3 +233,99 @@ def _discover_artifacts(output_dir: Path) -> dict[str, Path]: if "frontend_assets" not in artifacts and output_dir.exists(): artifacts["frontend_assets"] = output_dir return artifacts + + +class BuildService: + def __init__(self) -> None: + self._native = _NativeBuildService() if _NativeBuildService is not None else None + self._toolchains: dict[str | None, _CompilerToolchain] = {} + self._fallback = None if self._native is not None else _PythonBuildService() + + def register_toolchain( + self, fastled_path: Path | None, toolchain: _CompilerToolchain + ) -> None: + if self._native is None: + assert self._fallback is not None + self._fallback.register_toolchain(fastled_path, toolchain) + return + + key = _toolchain_key(fastled_path) + self._toolchains[key] = toolchain + self._native.register_toolchain(toolchain, key) + + def build(self, request: BuildRequest) -> BuildResult: + if self._native is None: + assert self._fallback is not None + return self._fallback.build(request) + + self._ensure_toolchain(request.fastled_path) + + try: + payload = self._native.build( + str(request.sketch_dir), + request.build_mode.value, + request.build_mode, + request.profile, + _toolchain_key(request.fastled_path), + request.force_clean, + ) + except KeyboardInterrupt as ki: + handle_keyboard_interrupt(ki) + raise + + compile_result = CompileResult( + success=bool(payload["success"]), + stdout=str(payload["stdout"]), + hash_value=cast(str | None, payload["hash_value"]), + zip_bytes=bytes(payload["zip_bytes"]), + zip_time=float(payload["zip_time"]), + libfastled_time=float(payload["libfastled_time"]), + sketch_time=float(payload["sketch_time"]), + response_processing_time=float(payload["response_processing_time"]), + ) + + artifacts = { + name: Path(path_str) + for name, path_str in cast(dict[str, str], payload["artifacts"]).items() + } + + return BuildResult( + compile_result=compile_result, + strategy=cast(BuildStrategy, payload["strategy"]), + output_dir=Path(str(payload["output_dir"])), + artifacts=artifacts, + ) + + def detect_strategy(self, request: BuildRequest) -> BuildStrategy: + if self._native is None: + assert self._fallback is not None + return self._fallback.detect_strategy(request) + + return cast( + BuildStrategy, + self._native.detect_strategy( + str(request.sketch_dir), + request.build_mode.value, + request.profile, + _toolchain_key(request.fastled_path), + request.force_clean, + ), + ) + + def purge(self, sketch_dir: Path) -> None: + if self._native is None: + assert self._fallback is not None + self._fallback.purge(sketch_dir) + return + self._native.purge(str(sketch_dir)) + + def _ensure_toolchain(self, fastled_path: Path | None) -> None: + key = _toolchain_key(fastled_path) + if key in self._toolchains: + return + + from fastled.toolchain.emscripten import EmscriptenToolchain + + self.register_toolchain( + fastled_path, EmscriptenToolchain(fastled_path=fastled_path) + ) diff --git a/src/fastled/cli.py b/src/fastled/cli.py index 73954c88..92ee8a79 100644 --- a/src/fastled/cli.py +++ b/src/fastled/cli.py @@ -1,27 +1,16 @@ -""" -Main entry point. -""" +"""Python compatibility shim that launches the native Rust CLI.""" import multiprocessing import sys - -def run_app() -> int: - """Run the application.""" - from fastled.app import main as app_main - - return app_main() +from fastled._rust_cli import invoke_rust_fastled_cli def main() -> int: - """Main entry point for the template_python_cmd package.""" - # if "--debug" in sys.argv: - # # Debug mode - # os.environ["FLASK_SERVER_LOGGING"] = "1" - return run_app() + """Run the native Rust CLI with the current argv.""" + return invoke_rust_fastled_cli(sys.argv[1:]) -# Cli entry point for the pyinstaller generated exe if __name__ == "__main__": - multiprocessing.freeze_support() # needed by pyinstaller. + multiprocessing.freeze_support() sys.exit(main()) diff --git a/src/fastled/project_init.py b/src/fastled/project_init.py index 8625981b..85a29cd1 100644 --- a/src/fastled/project_init.py +++ b/src/fastled/project_init.py @@ -11,6 +11,27 @@ DEFAULT_EXAMPLE = "wasm" +try: + from fastled._native import collect_examples as _native_collect_examples + from fastled._native import find_example_in_repo as _native_find_example_in_repo + from fastled._native import ( + ensure_fastled_repo as _native_ensure_fastled_repo, + ) + from fastled._native import ( + find_fastled_repo_upwards as _native_find_fastled_repo_upwards, + ) + from fastled._native import ( + init_example_from_repo as _native_init_example_from_repo, + ) + from fastled._native import read_fastled_json_ref as _native_read_fastled_json_ref +except ImportError: + _native_collect_examples = None + _native_find_example_in_repo = None + _native_ensure_fastled_repo = None + _native_find_fastled_repo_upwards = None + _native_init_example_from_repo = None + _native_read_fastled_json_ref = None + @dataclass class _CachedRepo: @@ -25,6 +46,14 @@ def _ensure_repo_via_rust(ref: str | None) -> Path: The Rust side owns the actual GitHub download. Python never performs the HTTP request itself. """ + if _native_ensure_fastled_repo is not None: + repo_path = Path(_native_ensure_fastled_repo(ref)) + if not repo_path.is_dir(): + raise RuntimeError( + f"Rust extension returned non-existent repo path: {str(repo_path)!r}" + ) + return repo_path + cli = _find_rust_fastled_cli() if cli is None: raise RuntimeError( @@ -82,6 +111,9 @@ def _get_local_fastled_repo(ref: str | None) -> _CachedRepo: def _read_fastled_json(directory: Path) -> str | None: """Read the 'ref' field from fastled.json in the given directory.""" + if _native_read_fastled_json_ref is not None: + return _native_read_fastled_json_ref(str(directory)) + fpath = directory / "fastled.json" if not fpath.exists(): return None @@ -113,6 +145,11 @@ def _find_fastled_repo_via_library_json(start: Path) -> Path | None: Returns the repo root directory, or None. """ + if _native_find_fastled_repo_upwards is not None: + found = _native_find_fastled_repo_upwards(str(start), 10) + if found: + return Path(found) + current = start.resolve() for _ in range(10): # limit depth lib_json = current / "library.json" @@ -139,6 +176,10 @@ def _find_example_in_repo(repo_root: Path, example: str) -> Path | None: Handles both flat layout (examples/FxSdCard/) and nested layout (examples/Fx/FxSdCard/). """ + if _native_find_example_in_repo is not None: + found = _native_find_example_in_repo(str(repo_root), example) + return Path(found) if found else None + examples_dir = repo_root / "examples" if not examples_dir.exists(): return None @@ -155,6 +196,9 @@ def _find_example_in_repo(repo_root: Path, example: str) -> Path | None: def _collect_examples_from_dir(examples_dir: Path) -> list[str]: """Collect example names from an examples directory.""" + if _native_collect_examples is not None: + return list(_native_collect_examples(str(examples_dir))) + if not examples_dir.exists(): return [] found: list[str] = [] @@ -247,18 +291,14 @@ def project_init( repo_root = cached.root resolved_ref = cached.ref_name - example_src = _find_example_in_repo(repo_root, example) - if example_src is None: - raise FileNotFoundError(f"Example '{example}' not found in FastLED repo") - - dest = outputdir / example - dest.mkdir(parents=True, exist_ok=True) - shutil.copytree(example_src, dest, dirs_exist_ok=True) - - out = outputdir / example + out = _init_example_from_repo( + repo_root=repo_root, + example=example, + outputdir=outputdir, + resolved_ref=resolved_ref if ref is not None else None, + ) if ref is not None: - _write_fastled_json(out, resolved_ref) print(f"Saved ref '{resolved_ref}' to {out / 'fastled.json'}") print(f"Project initialized at {out}") @@ -292,20 +332,42 @@ def _init_from_local_repo( example = result if result else DEFAULT_EXAMPLE assert example is not None + out = _init_example_from_repo( + repo_root=repo_root, + example=example, + outputdir=outputdir, + resolved_ref=None, + ) + print(f"Project initialized at {out}") + assert out.exists() + return out + + +def _init_example_from_repo( + repo_root: Path, + example: str, + outputdir: Path, + resolved_ref: str | None, +) -> Path: + if _native_init_example_from_repo is not None: + return Path( + _native_init_example_from_repo( + str(repo_root), example, str(outputdir), resolved_ref + ) + ) + example_src = _find_example_in_repo(repo_root, example) if example_src is None: - raise FileNotFoundError( - f"Example '{example}' not found in local FastLED repo at {repo_root}" - ) + raise FileNotFoundError(f"Example '{example}' not found in FastLED repo") dest = outputdir / example dest.mkdir(parents=True, exist_ok=True) shutil.copytree(example_src, dest, dirs_exist_ok=True) - out = outputdir / example - print(f"Project initialized at {out}") - assert out.exists() - return out + if resolved_ref is not None: + _write_fastled_json(dest, resolved_ref) + + return dest def unit_test() -> None: diff --git a/src/fastled/sketch.py b/src/fastled/sketch.py index 86898782..d9313b9f 100644 --- a/src/fastled/sketch.py +++ b/src/fastled/sketch.py @@ -3,10 +3,29 @@ _MAX_FILES_SEARCH_LIMIT = 10000 +try: + from fastled._native import ( + find_sketch_by_partial_name as _native_find_sketch_by_partial_name, + ) + from fastled._native import ( + find_sketch_directories as _native_find_sketch_directories, + ) + from fastled._native import looks_like_fastled_repo as _native_looks_like_fastled_repo + from fastled._native import ( + looks_like_sketch_directory as _native_looks_like_sketch_directory, + ) +except ImportError: + _native_find_sketch_by_partial_name = None + _native_find_sketch_directories = None + _native_looks_like_fastled_repo = None + _native_looks_like_sketch_directory = None + def find_sketch_directories(directory: Path | None = None) -> list[Path]: if directory is None: directory = Path(".") + if _native_find_sketch_directories is not None: + return [Path(p) for p in _native_find_sketch_directories(str(directory))] file_count = 0 sketch_directories: list[Path] = [] # search all the paths one level deep @@ -51,6 +70,9 @@ def search_examples_recursive( return sketch_directories +_ORIGINAL_FIND_SKETCH_DIRECTORIES = find_sketch_directories + + def get_sketch_files(directory: Path) -> list[Path]: file_count = 0 files: list[Path] = [] @@ -80,6 +102,8 @@ def get_sketch_files(directory: Path) -> list[Path]: def looks_like_fastled_repo(directory: Path = Path(".")) -> bool: + if _native_looks_like_fastled_repo is not None: + return bool(_native_looks_like_fastled_repo(str(directory))) libprops = directory / "library.properties" if not libprops.exists(): return False @@ -94,6 +118,8 @@ def _lots_and_lots_of_files(directory: Path) -> bool: def looks_like_sketch_directory(directory: Path | str | None, quick=False) -> bool: if directory is None: return False + if _native_looks_like_sketch_directory is not None: + return bool(_native_looks_like_sketch_directory(str(directory), quick)) directory = Path(directory) if looks_like_fastled_repo(directory): print("Directory looks like the FastLED repo") @@ -138,6 +164,12 @@ def find_sketch_by_partial_name( if search_dir is None: search_dir = Path(".") + if ( + _native_find_sketch_by_partial_name is not None + and find_sketch_directories is _ORIGINAL_FIND_SKETCH_DIRECTORIES + ): + return Path(_native_find_sketch_by_partial_name(partial_name, str(search_dir))) + # First, find all sketch directories sketch_directories = find_sketch_directories(search_dir) diff --git a/src/fastled/string_diff.py b/src/fastled/string_diff.py index 46ad850e..c92a92b7 100644 --- a/src/fastled/string_diff.py +++ b/src/fastled/string_diff.py @@ -1,6 +1,13 @@ from difflib import SequenceMatcher from pathlib import Path +try: + from fastled._native import is_in_order_match as _native_is_in_order_match + from fastled._native import string_diff as _native_string_diff +except ImportError: + _native_is_in_order_match = None + _native_string_diff = None + def _token_sort_ratio(a: str, b: str) -> float: """Return a 0..100 similarity score after sorting whitespace-split tokens.""" @@ -31,6 +38,8 @@ def _filter_out_obvious_bad_choices( def is_in_order_match(input_str: str, other: str) -> bool: + if _native_is_in_order_match is not None: + return bool(_native_is_in_order_match(input_str, other)) """ Check if the input string is an in-order match for any string in the list. An in-order match means that the characters of the input string appear @@ -58,6 +67,8 @@ def is_in_order_match(input_str: str, other: str) -> bool: def string_diff( input_string: str, string_list: list[str], ignore_case=True ) -> list[tuple[float, str]]: + if _native_string_diff is not None: + return list(_native_string_diff(input_string, string_list, ignore_case)) def normalize(s: str) -> str: return s.lower() if ignore_case else s diff --git a/tests/unit/test_post_migration.py b/tests/unit/test_post_migration.py index 23b1148c..e7571f46 100644 --- a/tests/unit/test_post_migration.py +++ b/tests/unit/test_post_migration.py @@ -1,34 +1,22 @@ """Tests for post-migration cleanup: dead code removal, stale exports, and bug fixes.""" import ast -import inspect import unittest from pathlib import Path SRC_DIR = Path(__file__).parent.parent.parent / "src" / "fastled" -class TestAppFlagPassedToNativeCompile(unittest.TestCase): - """Bug 1: --app flag must be accepted and forwarded by run_native_compile.""" +class TestPythonEntrypointsDelegateToRust(unittest.TestCase): + """User-facing Python entry points should forward to the native Rust CLI.""" - def test_run_native_compile_accepts_app_param(self) -> None: - from fastled.compile_native import run_native_compile + def test_cli_main_uses_rust_launcher(self) -> None: + source = (SRC_DIR / "cli.py").read_text() + self.assertIn("invoke_rust_fastled_cli", source) - sig = inspect.signature(run_native_compile) - self.assertIn( - "app", - sig.parameters, - "run_native_compile must accept an 'app' parameter", - ) - - def test_app_main_passes_app_to_run_native_compile(self) -> None: - """Verify app.py passes args.app in the run_native_compile() call.""" + def test_app_main_uses_rust_launcher(self) -> None: source = (SRC_DIR / "app.py").read_text() - self.assertIn( - "app=", - source, - "app.py should pass app= keyword to run_native_compile", - ) + self.assertIn("invoke_rust_fastled_cli", source) class TestNoDeadCodeModules(unittest.TestCase): diff --git a/tests/unit/test_project_init.py b/tests/unit/test_project_init.py index b7b87aca..dfe299ea 100644 --- a/tests/unit/test_project_init.py +++ b/tests/unit/test_project_init.py @@ -1,7 +1,13 @@ import unittest from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch -from fastled.project_init import get_examples +from fastled.project_init import ( + _ensure_repo_via_rust, + _init_example_from_repo, + get_examples, +) HERE = Path(__file__).parent TEST_DIR = HERE / "test_ino" / "wasm" @@ -16,6 +22,33 @@ def test_get_examples(self) -> None: self.assertTrue(len(examples) > 0) self.assertTrue("wasm" in examples) + @patch("fastled.project_init._native_ensure_fastled_repo") + def test_ensure_repo_via_rust_prefers_native_extension(self, mock_native) -> None: + """Native Rust extension should be used before CLI subprocess fallback.""" + with TemporaryDirectory() as tmpdir: + mock_native.return_value = tmpdir + repo = _ensure_repo_via_rust("master") + self.assertEqual(Path(tmpdir), repo) + mock_native.assert_called_once_with("master") + + @patch("fastled.project_init._native_init_example_from_repo") + def test_init_example_from_repo_prefers_native_extension(self, mock_native) -> None: + """Example copy should stay in Rust when the extension is available.""" + with TemporaryDirectory() as tmpdir: + out = Path(tmpdir) / "Blink" + out.mkdir() + mock_native.return_value = str(out) + result = _init_example_from_repo( + repo_root=Path("repo"), + example="Blink", + outputdir=Path(tmpdir), + resolved_ref="master", + ) + self.assertEqual(out, result) + mock_native.assert_called_once_with( + "repo", "Blink", tmpdir, "master" + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/test_sketch_partial_match.py b/tests/unit/test_sketch_partial_match.py index e90f5847..20914666 100644 --- a/tests/unit/test_sketch_partial_match.py +++ b/tests/unit/test_sketch_partial_match.py @@ -140,6 +140,14 @@ def test_sufficient_similarity_allows_match(self, mock_find): result = find_sketch_by_partial_name("sketch") self.assertEqual(Path("examples/sketch123"), result) + @patch("fastled.sketch._native_find_sketch_by_partial_name") + def test_prefers_native_extension_when_available(self, mock_native): + """Normal runtime should delegate partial matching to the Rust extension.""" + mock_native.return_value = "examples/FxWave2d" + result = find_sketch_by_partial_name("FxWave2d", Path("demo")) + self.assertEqual(Path("examples/FxWave2d"), result) + mock_native.assert_called_once_with("FxWave2d", "demo") + if __name__ == "__main__": unittest.main()