diff --git a/.github/workflows/_build.yml b/.github/workflows/_build.yml index 40bec070..19f3cafe 100644 --- a/.github/workflows/_build.yml +++ b/.github/workflows/_build.yml @@ -55,6 +55,41 @@ jobs: if: inputs.maturin-target != '' run: rustup target add "${{ inputs.maturin-target }}" + - name: Build fastled CLI binary (for wheel bundling) + run: | + # Compile the Rust `fastled` CLI and stage it under wheel-data/scripts/ + # so maturin packages it into -.data/scripts/ in the wheel. + # See `build-wheel` and `[tool.maturin] data` in pyproject.toml. + if [ -n "${{ inputs.maturin-target }}" ]; then + ./_cargo build --release --bin fastled --target "${{ inputs.maturin-target }}" + case "${{ inputs.maturin-target }}" in + *windows*) EXE_NAME="fastled.exe" ;; + *) EXE_NAME="fastled" ;; + esac + BIN_SRC="target/${{ inputs.maturin-target }}/release/${EXE_NAME}" + else + ./_cargo build --release --bin fastled + case "$(uname -s)" in + MINGW*|MSYS*|CYGWIN*) EXE_NAME="fastled.exe" ;; + *) EXE_NAME="fastled" ;; + esac + # _cargo forces an MSVC target on Windows even without --target. + if [ -n "${CARGO_BUILD_TARGET:-}" ] || [ "$EXE_NAME" = "fastled.exe" ]; then + ARCH="$(uname -m)" + if [ "$ARCH" = "x86_64" ]; then TRIPLE="x86_64-pc-windows-msvc"; else TRIPLE="aarch64-pc-windows-msvc"; fi + if [ -f "target/${TRIPLE}/release/${EXE_NAME}" ]; then + BIN_SRC="target/${TRIPLE}/release/${EXE_NAME}" + else + BIN_SRC="target/release/${EXE_NAME}" + fi + else + BIN_SRC="target/release/${EXE_NAME}" + fi + fi + mkdir -p wheel-data/scripts + cp -f "$BIN_SRC" "wheel-data/scripts/${EXE_NAME}" + ls -lh wheel-data/scripts/ + - name: Build wheel run: | if [ -n "${{ inputs.maturin-target }}" ]; then diff --git a/.gitignore b/.gitignore index cc4a79f9..e462d2ae 100644 --- a/.gitignore +++ b/.gitignore @@ -159,3 +159,8 @@ vscode-plugin /target/ /.cargo/ /.rustup/ + +# Maturin wheel data dir — populated by `./build-wheel` with the Rust +# fastled binary before `maturin build`. Bundled into the wheel as +# -.data/scripts/. +/wheel-data/ diff --git a/build-wheel b/build-wheel new file mode 100644 index 00000000..765a5abf --- /dev/null +++ b/build-wheel @@ -0,0 +1,56 @@ +#!/bin/bash +# Build a fastled wheel that bundles the Rust CLI binary as a wheel script. +# +# Maturin's pyo3-binding mode produces the `_native` extension module but +# doesn't ship Rust [[bin]] targets in the wheel. We work around that by +# compiling the binary first, dropping it into `wheel-data/scripts/`, and +# letting maturin package that directory as the wheel's `.data/` tree (see +# `[tool.maturin] data` in pyproject.toml). Pip extracts `data/scripts/*` +# to the venv's Scripts/ (Windows) or bin/ (Unix) on install. + +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" + +# Platform-specific binary name and target directory. +case "$(uname -s)" in + MINGW*|MSYS*|CYGWIN*) EXE_NAME="fastled.exe" ;; + *) EXE_NAME="fastled" ;; +esac + +echo "Compiling fastled CLI (release)..." +"$SCRIPT_DIR/_cargo" build --release --bin fastled + +# Resolve where cargo wrote the binary. The _cargo wrapper sets +# CARGO_BUILD_TARGET on Windows so the binary lands under a triple subdir. +if [[ -n "${CARGO_BUILD_TARGET:-}" ]]; then + BIN_SRC="$SCRIPT_DIR/target/${CARGO_BUILD_TARGET}/release/${EXE_NAME}" +else + BIN_SRC="$SCRIPT_DIR/target/release/${EXE_NAME}" +fi + +# Discover from _cargo's exported target on Windows even if not set in env. +case "$(uname -s)" in + MINGW*|MSYS*|CYGWIN*) + ARCH="$(uname -m)" + if [[ "$ARCH" = "x86_64" ]]; then + TARGET_TRIPLE="x86_64-pc-windows-msvc" + else + TARGET_TRIPLE="aarch64-pc-windows-msvc" + fi + BIN_SRC="$SCRIPT_DIR/target/${TARGET_TRIPLE}/release/${EXE_NAME}" + ;; +esac + +if [[ ! -f "$BIN_SRC" ]]; then + echo "Error: built binary not found at $BIN_SRC" >&2 + exit 1 +fi + +WHEEL_DATA_DIR="$SCRIPT_DIR/wheel-data/scripts" +mkdir -p "$WHEEL_DATA_DIR" +cp -f "$BIN_SRC" "$WHEEL_DATA_DIR/$EXE_NAME" +echo "Staged $BIN_SRC -> $WHEEL_DATA_DIR/$EXE_NAME" + +echo "Building wheel..." +uv run maturin build --release "$@" diff --git a/crates/fastled-cli/Cargo.toml b/crates/fastled-cli/Cargo.toml index 5ab3a9c0..f3211d5d 100644 --- a/crates/fastled-cli/Cargo.toml +++ b/crates/fastled-cli/Cargo.toml @@ -8,6 +8,10 @@ repository.workspace = true homepage.workspace = true description = "FastLED WASM compilation CLI" +[lib] +name = "fastled_cli" +path = "src/lib.rs" + [[bin]] name = "fastled" path = "src/main.rs" diff --git a/crates/fastled-cli/src/lib.rs b/crates/fastled-cli/src/lib.rs new file mode 100644 index 00000000..5995a334 --- /dev/null +++ b/crates/fastled-cli/src/lib.rs @@ -0,0 +1,709 @@ +use clap::Parser; +use std::io::BufRead; +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitCode, Stdio}; + +mod archive; +mod build; +mod install; +mod keyboard; +mod project; +mod server; +mod viewer; +mod watcher; + +// --------------------------------------------------------------------------- +// Build-status IPC (Rust writes, loading page polls) +// --------------------------------------------------------------------------- + +fn write_build_status(output_dir: &Path, status: &str, message: &str) { + let status_file = output_dir.join("build-status.json"); + let json = format!( + r#"{{"status":"{}","message":"{}"}}"#, + status, + message.replace('\\', "\\\\").replace('"', "\\\"") + ); + let _ = std::fs::write(status_file, json); +} + +// --------------------------------------------------------------------------- +// Streaming compile (captures output line-by-line, sends via broadcast) +// --------------------------------------------------------------------------- + +/// Escape a string for JSON embedding. +fn json_escape(s: &str) -> String { + s.replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\n', "\\n") + .replace('\r', "\\r") + .replace('\t', "\\t") +} + +/// Send an SSE event through the broadcast channel. +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()); + } + 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()); + } + if let Some(fp) = &cli.fastled_path { + args.push("--fastled-path".to_string()); + args.push(fp.clone()); + } + for arg in extra_args { + args.push(arg.to_string()); + } + + 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 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) + ), + ); + } + }); + + 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) + ), + ); + } + }); + + 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 + } + } +} + +// --------------------------------------------------------------------------- +// Viewer mode selector +// --------------------------------------------------------------------------- + +/// Controls how the compiled output is displayed to the user. +enum ViewerMode { + /// Open the default system browser. + Browser, + /// Launch the native Tauri viewer pointing at the output directory. + TauriViewer, +} + +// --------------------------------------------------------------------------- +// Compile + serve + watch (replaces Flask-based flow) +// --------------------------------------------------------------------------- + +/// Compile a sketch, serve the output via the built-in HTTP server, and +/// watch for file changes to trigger recompilation. +/// +/// Build output is streamed to the browser (or Tauri viewer) in real time +/// via SSE. +fn compile_and_serve(dir: &str, cli: &Cli, mode: ViewerMode) -> ExitCode { + let sketch_dir = PathBuf::from(dir); + if !sketch_dir.is_dir() { + eprintln!("fastled: sketch directory does not exist: {dir}"); + return ExitCode::FAILURE; + } + + // 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); + } + 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; + } + } + + let output_dir = sketch_dir.join("fastled_js"); + if let Err(e) = std::fs::create_dir_all(&output_dir) { + eprintln!( + "fastled: could not create output directory {}: {e}", + output_dir.display() + ); + return ExitCode::FAILURE; + } + + // Broadcast channel for SSE streaming to browser. + let (tx, _rx) = tokio::sync::broadcast::channel::(256); + + // Write initial compiling status for polling fallback. + write_build_status(&output_dir, "compiling", "Compiling..."); + + let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime"); + rt.block_on(async { + // Start the Rust HTTP server (background tokio task). + let addr = match server::start_server(output_dir.clone(), 0, Some(tx.clone())).await { + Ok(a) => a, + Err(e) => { + eprintln!("fastled: failed to start server: {e}"); + return ExitCode::FAILURE; + } + }; + + let url = format!("http://{addr}"); + println!("Serving at {url}"); + + match mode { + ViewerMode::Browser => open_browser(&url), + ViewerMode::TauriViewer => { + if let Err(e) = viewer::launch_tauri_viewer(&output_dir) { + eprintln!("fastled: Tauri viewer failed: {e}, falling back to browser"); + open_browser(&url); + } + } + } + + // --- Initial compilation ------------------------------------------------ + send_sse( + &tx, + 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); + + if success { + write_build_status(&output_dir, "success", "Done"); + send_sse( + &tx, + r#"{"type":"status","status":"success","message":"Done"}"#, + ); + } else { + write_build_status(&output_dir, "error", "Compilation failed"); + send_sse( + &tx, + r#"{"type":"status","status":"error","message":"Compilation failed"}"#, + ); + } + + // --- Watch mode --------------------------------------------------------- + println!("\nWill recompile on sketch changes or space bar press."); + println!("Press Ctrl+C to stop..."); + + let watcher_result = + watcher::FileWatcher::new(sketch_dir.clone(), watcher::DEFAULT_DEBOUNCE_MS); + let mut file_watcher = match watcher_result { + Ok(w) => w, + Err(e) => { + eprintln!("fastled: file watcher failed: {e}"); + tokio::signal::ctrl_c().await.ok(); + return ExitCode::SUCCESS; + } + }; + let rx = file_watcher.start(); + + loop { + let should_rebuild = match rx.recv_timeout(std::time::Duration::from_secs(1)) { + Ok(changed) => { + println!("\nChanges detected in {changed:?}"); + true + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => keyboard::check_for_space(), + Err(_) => break, + }; + + if should_rebuild { + println!("Compiling..."); + write_build_status(&output_dir, "compiling", "Recompiling..."); + send_sse( + &tx, + r#"{"type":"status","status":"compiling","message":"Recompiling..."}"#, + ); + + let success = run_python_compile_streaming(cli, &[], &tx); + if success { + println!("Recompilation successful!"); + write_build_status(&output_dir, "success", "Done"); + send_sse( + &tx, + r#"{"type":"status","status":"success","message":"Done"}"#, + ); + } else { + eprintln!("Recompilation failed."); + write_build_status(&output_dir, "error", "Compilation failed"); + send_sse( + &tx, + r#"{"type":"status","status":"error","message":"Compilation failed"}"#, + ); + } + } + } + + file_watcher.stop(); + ExitCode::SUCCESS + }) +} + +/// 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. +#[derive(Parser, Debug)] +#[command( + name = "fastled", + version, + about = "FastLED WASM compilation CLI", + long_about = None, + // Stop Rust clap from eating flags it doesn't recognise; we want to be + // a strict mirror, so every flag is declared explicitly. +)] +struct Cli { + /// Directory containing the FastLED sketch to compile. + directory: Option, + + /// Serve an existing directory without compiling a sketch. + #[arg(long, value_name = "DIR")] + serve_dir: Option, + + /// Initialize a FastLED sketch in the current directory. + /// An optional example name may be provided (e.g. --init Blink). + #[arg(long, value_name = "EXAMPLE", num_args = 0..=1, default_missing_value = "__init__")] + init: Option, + + /// Just compile; skip opening the browser and watching for changes. + #[arg(long)] + just_compile: bool, + + /// Enable profiling of the C++ build system used for WASM compilation. + #[arg(long)] + profile: bool, + + /// Use Playwright app-like browser experience (downloads browsers if needed). + #[arg(long)] + app: bool, + + /// Force the legacy Flask + browser viewer even when the native Tauri + /// viewer is available. Has no effect unless `--app` is also passed. + #[arg(long)] + legacy_browser: bool, + + /// Install the FastLED development environment with VSCode configuration. + #[arg(long)] + install: bool, + + /// Run in dry-run mode (simulate actions without making changes). + #[arg(long)] + dry_run: bool, + + /// Run in non-interactive mode (fail instead of prompting for input). + #[arg(long)] + no_interactive: bool, + + /// Disable HTTPS and use HTTP for the local server. + #[arg(long)] + no_https: bool, + + /// Use the latest release when initialising examples with --init (default behaviour). + #[arg(long)] + latest: bool, + + /// Use a specific branch when initialising examples with --init. + #[arg(long, value_name = "BRANCH")] + branch: Option, + + /// Use a specific commit SHA when initialising examples with --init. + #[arg(long, value_name = "SHA")] + commit: Option, + + /// Path to the FastLED library for native compilation. + #[arg(long, value_name = "PATH")] + fastled_path: Option, + + /// Purge the cached FastLED repo, forcing a fresh re-download on next build. + #[arg(long)] + purge: bool, + + /// Internal plumbing flag: ensure the FastLED repo for the given ref + /// (defaults to latest release) is downloaded and extracted, print the + /// local path to stdout, and exit. Used by the Python `Api.project_init` + /// path so the Python side never has to do an HTTP download. + #[arg(long, value_name = "REF", num_args = 0..=1, default_missing_value = "__latest__", hide = true)] + internal_ensure_fastled_repo: Option, + + /// Internal plumbing flag: download a Chrome Web Store extension (by ID) + /// into ``~/.fastled/chrome-extensions//``, print the path to + /// stdout, and exit. Used by the Python playwright helpers. + #[arg(long, value_names = ["EXTENSION_ID", "NAME"], num_args = 2, hide = true)] + internal_ensure_chrome_extension: Vec, + + // Build mode (mutually exclusive). + /// Build in debug mode. + #[arg(long, conflicts_with_all = ["quick", "release"])] + debug: bool, + + /// Build in quick mode (default). + #[arg(long, conflicts_with_all = ["debug", "release"])] + quick: bool, + + /// Build in optimised release mode. + #[arg(long, conflicts_with_all = ["debug", "quick"])] + 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: +/// * `--app` was requested, AND +/// * `--legacy-browser` was NOT passed, AND +/// * the `fastled-viewer` binary can be found. +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(); + + if let Some(dir) = &cli.directory { + args.push(dir.clone()); + } + if let Some(sd) = &cli.serve_dir { + args.push("--serve-dir".to_string()); + args.push(sd.clone()); + } + 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()); + } + } + if cli.just_compile { + args.push("--just-compile".to_string()); + } + if cli.profile { + args.push("--profile".to_string()); + } + if cli.app { + args.push("--app".to_string()); + } + if cli.install { + args.push("--install".to_string()); + } + if cli.dry_run { + args.push("--dry-run".to_string()); + } + if cli.no_interactive { + args.push("--no-interactive".to_string()); + } + if cli.no_https { + args.push("--no-https".to_string()); + } + if cli.latest { + args.push("--latest".to_string()); + } + if let Some(branch) = &cli.branch { + args.push("--branch".to_string()); + args.push(branch.clone()); + } + if let Some(commit) = &cli.commit { + args.push("--commit".to_string()); + args.push(commit.clone()); + } + if let Some(fp) = &cli.fastled_path { + args.push("--fastled-path".to_string()); + args.push(fp.clone()); + } + if cli.purge { + args.push("--purge".to_string()); + } + if cli.debug { + args.push("--debug".to_string()); + } + if cli.quick { + args.push("--quick".to_string()); + } + if cli.release { + args.push("--release".to_string()); + } + + args +} + +/// Serve a directory using the built-in Rust HTTP server. +/// +/// This replaces the Flask-based `--serve-dir` implementation with a native +/// Rust server, eliminating the Python/Flask dependency for this code path. +fn serve_directory(dir: &str, cli: &Cli) -> ExitCode { + let path = PathBuf::from(dir); + if !path.is_dir() { + eprintln!("fastled: --serve-dir path does not exist: {dir}"); + return ExitCode::FAILURE; + } + + let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime"); + rt.block_on(async { + let addr = match server::start_server(path.clone(), 0, None).await { + Ok(a) => a, + Err(e) => { + eprintln!("fastled: failed to start server: {e}"); + return ExitCode::FAILURE; + } + }; + + let url = format!("http://{addr}"); + println!("Serving {dir} at {url}"); + println!("Press Ctrl+C to stop..."); + + // Open the Tauri viewer or fall back to system browser. + if viewer::viewer_available() && !cli.no_https { + if let Err(e) = viewer::launch_tauri_viewer(&path) { + eprintln!("fastled: Tauri viewer failed: {e}, opening system browser"); + open_browser(&url); + } + } else { + open_browser(&url); + } + + // Wait for Ctrl+C. + tokio::signal::ctrl_c().await.ok(); + println!("\nShutting down..."); + ExitCode::SUCCESS + }) +} + +/// Open a URL in the default system browser. +fn open_browser(url: &str) { + #[cfg(target_os = "windows")] + { + let _ = Command::new("cmd").args(["/c", "start", url]).spawn(); + } + #[cfg(target_os = "macos")] + { + let _ = Command::new("open").arg(url).spawn(); + } + #[cfg(target_os = "linux")] + { + let _ = Command::new("xdg-open").arg(url).spawn(); + } +} + +/// 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(); + + // Hidden plumbing for the Python side: download the FastLED repo and + // print the local path. No further work. + if let Some(ref ref_str) = cli.internal_ensure_fastled_repo { + let ref_opt = if ref_str == "__latest__" { + None + } else { + Some(ref_str.as_str()) + }; + return match install::ensure_fastled_repo(ref_opt) { + Ok(path) => { + println!("{}", path.display()); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("fastled: failed to fetch FastLED repo: {e:#}"); + ExitCode::FAILURE + } + }; + } + + // Hidden plumbing: download a Chrome Web Store extension and print its + // local install path. Used by the Python playwright helpers. + if !cli.internal_ensure_chrome_extension.is_empty() { + if cli.internal_ensure_chrome_extension.len() != 2 { + eprintln!("fastled: --internal-ensure-chrome-extension requires EXTENSION_ID NAME"); + return ExitCode::FAILURE; + } + let extension_id = &cli.internal_ensure_chrome_extension[0]; + let name = &cli.internal_ensure_chrome_extension[1]; + return match install::ensure_chrome_extension(extension_id, name) { + Ok(path) => { + println!("{}", path.display()); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("fastled: failed to fetch Chrome extension: {e:#}"); + ExitCode::FAILURE + } + }; + } + + // Handle --serve-dir natively with the Rust HTTP server (no Python needed). + if let Some(ref serve_dir) = cli.serve_dir { + return serve_directory(serve_dir, &cli); + } + + let use_tauri = should_use_tauri_viewer(&cli); + + // Normal compilation flow with Rust HTTP server + watch mode. + // Both browser and Tauri viewer paths use the same compile_and_serve() + // infrastructure so compilation output is streamed via SSE in real time. + // + // Conditions: + // - a sketch directory was provided + // - the user did NOT pass --just-compile + // - it's not a non-compile command (--init, --install) + if let Some(ref dir) = cli.directory { + if !cli.just_compile && cli.init.is_none() && !cli.install { + let mode = if use_tauri { + ViewerMode::TauriViewer + } else { + ViewerMode::Browser + }; + return compile_and_serve(dir, &cli, mode); + } + } + + // 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; + } + } + } + + // --- Delegate to Python for everything else ------------------------------ + // (--just-compile, --init, --install, etc.) + + let python = find_python(); + let py_args = rebuild_python_args(&cli); + + let status = Command::new(&python) + .args(["-m", "fastled.app"]) + .args(&py_args) + .status(); + + let exit_code = match status { + Ok(s) => { + let code = s.code().unwrap_or(1); + ExitCode::from(code as u8) + } + Err(e) => { + eprintln!("fastled: failed to launch `{python} -m fastled.app`: {e}"); + return ExitCode::FAILURE; + } + }; + + exit_code +} diff --git a/crates/fastled-cli/src/main.rs b/crates/fastled-cli/src/main.rs index bc5523fb..c50cc00a 100644 --- a/crates/fastled-cli/src/main.rs +++ b/crates/fastled-cli/src/main.rs @@ -1,707 +1,3 @@ -use clap::Parser; -use std::io::BufRead; -use std::path::{Path, PathBuf}; -use std::process::{Command, ExitCode, Stdio}; - -mod archive; -mod build; -mod install; -mod keyboard; -mod project; -mod server; -mod viewer; -mod watcher; - -// --------------------------------------------------------------------------- -// Build-status IPC (Rust writes, loading page polls) -// --------------------------------------------------------------------------- - -fn write_build_status(output_dir: &Path, status: &str, message: &str) { - let status_file = output_dir.join("build-status.json"); - let json = format!( - r#"{{"status":"{}","message":"{}"}}"#, - status, - message.replace('\\', "\\\\").replace('"', "\\\"") - ); - let _ = std::fs::write(status_file, json); -} - -// --------------------------------------------------------------------------- -// Streaming compile (captures output line-by-line, sends via broadcast) -// --------------------------------------------------------------------------- - -/// Escape a string for JSON embedding. -fn json_escape(s: &str) -> String { - s.replace('\\', "\\\\") - .replace('"', "\\\"") - .replace('\n', "\\n") - .replace('\r', "\\r") - .replace('\t', "\\t") -} - -/// Send an SSE event through the broadcast channel. -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()); - } - 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()); - } - if let Some(fp) = &cli.fastled_path { - args.push("--fastled-path".to_string()); - args.push(fp.clone()); - } - for arg in extra_args { - args.push(arg.to_string()); - } - - 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 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) - ), - ); - } - }); - - 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) - ), - ); - } - }); - - 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 - } - } -} - -// --------------------------------------------------------------------------- -// Viewer mode selector -// --------------------------------------------------------------------------- - -/// Controls how the compiled output is displayed to the user. -enum ViewerMode { - /// Open the default system browser. - Browser, - /// Launch the native Tauri viewer pointing at the output directory. - TauriViewer, -} - -// --------------------------------------------------------------------------- -// Compile + serve + watch (replaces Flask-based flow) -// --------------------------------------------------------------------------- - -/// Compile a sketch, serve the output via the built-in HTTP server, and -/// watch for file changes to trigger recompilation. -/// -/// Build output is streamed to the browser (or Tauri viewer) in real time -/// via SSE. -fn compile_and_serve(dir: &str, cli: &Cli, mode: ViewerMode) -> ExitCode { - let sketch_dir = PathBuf::from(dir); - if !sketch_dir.is_dir() { - eprintln!("fastled: sketch directory does not exist: {dir}"); - return ExitCode::FAILURE; - } - - // 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); - } - 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; - } - } - - let output_dir = sketch_dir.join("fastled_js"); - if let Err(e) = std::fs::create_dir_all(&output_dir) { - eprintln!( - "fastled: could not create output directory {}: {e}", - output_dir.display() - ); - return ExitCode::FAILURE; - } - - // Broadcast channel for SSE streaming to browser. - let (tx, _rx) = tokio::sync::broadcast::channel::(256); - - // Write initial compiling status for polling fallback. - write_build_status(&output_dir, "compiling", "Compiling..."); - - let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime"); - rt.block_on(async { - // Start the Rust HTTP server (background tokio task). - let addr = match server::start_server(output_dir.clone(), 0, Some(tx.clone())).await { - Ok(a) => a, - Err(e) => { - eprintln!("fastled: failed to start server: {e}"); - return ExitCode::FAILURE; - } - }; - - let url = format!("http://{addr}"); - println!("Serving at {url}"); - - match mode { - ViewerMode::Browser => open_browser(&url), - ViewerMode::TauriViewer => { - if let Err(e) = viewer::launch_tauri_viewer(&output_dir) { - eprintln!("fastled: Tauri viewer failed: {e}, falling back to browser"); - open_browser(&url); - } - } - } - - // --- Initial compilation ------------------------------------------------ - send_sse( - &tx, - 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); - - if success { - write_build_status(&output_dir, "success", "Done"); - send_sse( - &tx, - r#"{"type":"status","status":"success","message":"Done"}"#, - ); - } else { - write_build_status(&output_dir, "error", "Compilation failed"); - send_sse( - &tx, - r#"{"type":"status","status":"error","message":"Compilation failed"}"#, - ); - } - - // --- Watch mode --------------------------------------------------------- - println!("\nWill recompile on sketch changes or space bar press."); - println!("Press Ctrl+C to stop..."); - - let watcher_result = - watcher::FileWatcher::new(sketch_dir.clone(), watcher::DEFAULT_DEBOUNCE_MS); - let mut file_watcher = match watcher_result { - Ok(w) => w, - Err(e) => { - eprintln!("fastled: file watcher failed: {e}"); - tokio::signal::ctrl_c().await.ok(); - return ExitCode::SUCCESS; - } - }; - let rx = file_watcher.start(); - - loop { - let should_rebuild = match rx.recv_timeout(std::time::Duration::from_secs(1)) { - Ok(changed) => { - println!("\nChanges detected in {changed:?}"); - true - } - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => keyboard::check_for_space(), - Err(_) => break, - }; - - if should_rebuild { - println!("Compiling..."); - write_build_status(&output_dir, "compiling", "Recompiling..."); - send_sse( - &tx, - r#"{"type":"status","status":"compiling","message":"Recompiling..."}"#, - ); - - let success = run_python_compile_streaming(cli, &[], &tx); - if success { - println!("Recompilation successful!"); - write_build_status(&output_dir, "success", "Done"); - send_sse( - &tx, - r#"{"type":"status","status":"success","message":"Done"}"#, - ); - } else { - eprintln!("Recompilation failed."); - write_build_status(&output_dir, "error", "Compilation failed"); - send_sse( - &tx, - r#"{"type":"status","status":"error","message":"Compilation failed"}"#, - ); - } - } - } - - file_watcher.stop(); - ExitCode::SUCCESS - }) -} - -/// 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. -#[derive(Parser, Debug)] -#[command( - name = "fastled", - version, - about = "FastLED WASM compilation CLI", - long_about = None, - // Stop Rust clap from eating flags it doesn't recognise; we want to be - // a strict mirror, so every flag is declared explicitly. -)] -struct Cli { - /// Directory containing the FastLED sketch to compile. - directory: Option, - - /// Serve an existing directory without compiling a sketch. - #[arg(long, value_name = "DIR")] - serve_dir: Option, - - /// Initialize a FastLED sketch in the current directory. - /// An optional example name may be provided (e.g. --init Blink). - #[arg(long, value_name = "EXAMPLE", num_args = 0..=1, default_missing_value = "__init__")] - init: Option, - - /// Just compile; skip opening the browser and watching for changes. - #[arg(long)] - just_compile: bool, - - /// Enable profiling of the C++ build system used for WASM compilation. - #[arg(long)] - profile: bool, - - /// Use Playwright app-like browser experience (downloads browsers if needed). - #[arg(long)] - app: bool, - - /// Force the legacy Flask + browser viewer even when the native Tauri - /// viewer is available. Has no effect unless `--app` is also passed. - #[arg(long)] - legacy_browser: bool, - - /// Install the FastLED development environment with VSCode configuration. - #[arg(long)] - install: bool, - - /// Run in dry-run mode (simulate actions without making changes). - #[arg(long)] - dry_run: bool, - - /// Run in non-interactive mode (fail instead of prompting for input). - #[arg(long)] - no_interactive: bool, - - /// Disable HTTPS and use HTTP for the local server. - #[arg(long)] - no_https: bool, - - /// Use the latest release when initialising examples with --init (default behaviour). - #[arg(long)] - latest: bool, - - /// Use a specific branch when initialising examples with --init. - #[arg(long, value_name = "BRANCH")] - branch: Option, - - /// Use a specific commit SHA when initialising examples with --init. - #[arg(long, value_name = "SHA")] - commit: Option, - - /// Path to the FastLED library for native compilation. - #[arg(long, value_name = "PATH")] - fastled_path: Option, - - /// Purge the cached FastLED repo, forcing a fresh re-download on next build. - #[arg(long)] - purge: bool, - - /// Internal plumbing flag: ensure the FastLED repo for the given ref - /// (defaults to latest release) is downloaded and extracted, print the - /// local path to stdout, and exit. Used by the Python `Api.project_init` - /// path so the Python side never has to do an HTTP download. - #[arg(long, value_name = "REF", num_args = 0..=1, default_missing_value = "__latest__", hide = true)] - internal_ensure_fastled_repo: Option, - - /// Internal plumbing flag: download a Chrome Web Store extension (by ID) - /// into ``~/.fastled/chrome-extensions//``, print the path to - /// stdout, and exit. Used by the Python playwright helpers. - #[arg(long, value_names = ["EXTENSION_ID", "NAME"], num_args = 2, hide = true)] - internal_ensure_chrome_extension: Vec, - - // Build mode (mutually exclusive). - /// Build in debug mode. - #[arg(long, conflicts_with_all = ["quick", "release"])] - debug: bool, - - /// Build in quick mode (default). - #[arg(long, conflicts_with_all = ["debug", "release"])] - quick: bool, - - /// Build in optimised release mode. - #[arg(long, conflicts_with_all = ["debug", "quick"])] - 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: -/// * `--app` was requested, AND -/// * `--legacy-browser` was NOT passed, AND -/// * the `fastled-viewer` binary can be found. -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(); - - if let Some(dir) = &cli.directory { - args.push(dir.clone()); - } - if let Some(sd) = &cli.serve_dir { - args.push("--serve-dir".to_string()); - args.push(sd.clone()); - } - 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()); - } - } - if cli.just_compile { - args.push("--just-compile".to_string()); - } - if cli.profile { - args.push("--profile".to_string()); - } - if cli.app { - args.push("--app".to_string()); - } - if cli.install { - args.push("--install".to_string()); - } - if cli.dry_run { - args.push("--dry-run".to_string()); - } - if cli.no_interactive { - args.push("--no-interactive".to_string()); - } - if cli.no_https { - args.push("--no-https".to_string()); - } - if cli.latest { - args.push("--latest".to_string()); - } - if let Some(branch) = &cli.branch { - args.push("--branch".to_string()); - args.push(branch.clone()); - } - if let Some(commit) = &cli.commit { - args.push("--commit".to_string()); - args.push(commit.clone()); - } - if let Some(fp) = &cli.fastled_path { - args.push("--fastled-path".to_string()); - args.push(fp.clone()); - } - if cli.purge { - args.push("--purge".to_string()); - } - if cli.debug { - args.push("--debug".to_string()); - } - if cli.quick { - args.push("--quick".to_string()); - } - if cli.release { - args.push("--release".to_string()); - } - - args -} - -/// Serve a directory using the built-in Rust HTTP server. -/// -/// This replaces the Flask-based `--serve-dir` implementation with a native -/// Rust server, eliminating the Python/Flask dependency for this code path. -fn serve_directory(dir: &str, cli: &Cli) -> ExitCode { - let path = PathBuf::from(dir); - if !path.is_dir() { - eprintln!("fastled: --serve-dir path does not exist: {dir}"); - return ExitCode::FAILURE; - } - - let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime"); - rt.block_on(async { - let addr = match server::start_server(path.clone(), 0, None).await { - Ok(a) => a, - Err(e) => { - eprintln!("fastled: failed to start server: {e}"); - return ExitCode::FAILURE; - } - }; - - let url = format!("http://{addr}"); - println!("Serving {dir} at {url}"); - println!("Press Ctrl+C to stop..."); - - // Open the Tauri viewer or fall back to system browser. - if viewer::viewer_available() && !cli.no_https { - if let Err(e) = viewer::launch_tauri_viewer(&path) { - eprintln!("fastled: Tauri viewer failed: {e}, opening system browser"); - open_browser(&url); - } - } else { - open_browser(&url); - } - - // Wait for Ctrl+C. - tokio::signal::ctrl_c().await.ok(); - println!("\nShutting down..."); - ExitCode::SUCCESS - }) -} - -/// Open a URL in the default system browser. -fn open_browser(url: &str) { - #[cfg(target_os = "windows")] - { - let _ = Command::new("cmd").args(["/c", "start", url]).spawn(); - } - #[cfg(target_os = "macos")] - { - let _ = Command::new("open").arg(url).spawn(); - } - #[cfg(target_os = "linux")] - { - let _ = Command::new("xdg-open").arg(url).spawn(); - } -} - -fn main() -> ExitCode { - let cli = Cli::parse(); - - // Hidden plumbing for the Python side: download the FastLED repo and - // print the local path. No further work. - if let Some(ref ref_str) = cli.internal_ensure_fastled_repo { - let ref_opt = if ref_str == "__latest__" { - None - } else { - Some(ref_str.as_str()) - }; - return match install::ensure_fastled_repo(ref_opt) { - Ok(path) => { - println!("{}", path.display()); - ExitCode::SUCCESS - } - Err(e) => { - eprintln!("fastled: failed to fetch FastLED repo: {e:#}"); - ExitCode::FAILURE - } - }; - } - - // Hidden plumbing: download a Chrome Web Store extension and print its - // local install path. Used by the Python playwright helpers. - if !cli.internal_ensure_chrome_extension.is_empty() { - if cli.internal_ensure_chrome_extension.len() != 2 { - eprintln!("fastled: --internal-ensure-chrome-extension requires EXTENSION_ID NAME"); - return ExitCode::FAILURE; - } - let extension_id = &cli.internal_ensure_chrome_extension[0]; - let name = &cli.internal_ensure_chrome_extension[1]; - return match install::ensure_chrome_extension(extension_id, name) { - Ok(path) => { - println!("{}", path.display()); - ExitCode::SUCCESS - } - Err(e) => { - eprintln!("fastled: failed to fetch Chrome extension: {e:#}"); - ExitCode::FAILURE - } - }; - } - - // Handle --serve-dir natively with the Rust HTTP server (no Python needed). - if let Some(ref serve_dir) = cli.serve_dir { - return serve_directory(serve_dir, &cli); - } - - let use_tauri = should_use_tauri_viewer(&cli); - - // Normal compilation flow with Rust HTTP server + watch mode. - // Both browser and Tauri viewer paths use the same compile_and_serve() - // infrastructure so compilation output is streamed via SSE in real time. - // - // Conditions: - // - a sketch directory was provided - // - the user did NOT pass --just-compile - // - it's not a non-compile command (--init, --install) - if let Some(ref dir) = cli.directory { - if !cli.just_compile && cli.init.is_none() && !cli.install { - let mode = if use_tauri { - ViewerMode::TauriViewer - } else { - ViewerMode::Browser - }; - return compile_and_serve(dir, &cli, mode); - } - } - - // 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; - } - } - } - - // --- Delegate to Python for everything else ------------------------------ - // (--just-compile, --init, --install, etc.) - - let python = find_python(); - let py_args = rebuild_python_args(&cli); - - let status = Command::new(&python) - .args(["-m", "fastled.app"]) - .args(&py_args) - .status(); - - let exit_code = match status { - Ok(s) => { - let code = s.code().unwrap_or(1); - ExitCode::from(code as u8) - } - Err(e) => { - eprintln!("fastled: failed to launch `{python} -m fastled.app`: {e}"); - return ExitCode::FAILURE; - } - }; - - exit_code +fn main() -> std::process::ExitCode { + fastled_cli::run() } diff --git a/install b/install index 388c9614..52b77133 100755 --- a/install +++ b/install @@ -18,6 +18,15 @@ fi uv venv --python 3.11 --seed uv pip install "maturin>=1.7,<2" + +# Ensure the maturin data dir exists before invoking maturin. The +# `[tool.maturin] data = "wheel-data"` config points here; maturin treats a +# missing path as an error during `pep517 build-wheel`. The cargo-build step +# later in this script will populate `wheel-data/scripts/` with the Rust +# fastled binary so subsequent `./build-wheel` invocations bundle it; an +# empty dir is fine for the editable-install path that pip is about to run. +mkdir -p wheel-data/scripts + uv pip install -e . uv pip install -r requirements.testing.txt @@ -107,3 +116,44 @@ if [[ "$FASTLED_CLI_BINSTALLED" -eq 0 ]]; then "$(dirname "$0")/_cargo" build --release --bin fastled \ || { echo "Error: cargo build --bin fastled failed"; exit 1; } fi + +# Locate the just-built (or binstalled) Rust binary and stage it where +# downstream tooling will find it. Editable installs (`uv pip install -e .`) +# don't extract the maturin `data` dir to the venv's Scripts/, so we mimic +# the wheel-install layout manually: +# * `.venv/Scripts/fastled[.exe]` (or `.venv/bin/fastled`) — so PATH lookup +# resolves the Rust binary for callers like `build_site.py` that shell +# out to plain `fastled`. +# * `wheel-data/scripts/fastled[.exe]` — so a subsequent `./build-wheel` +# produces a wheel that bundles the binary. +if [[ "$OSTYPE" == "msys" ]]; then + EXE_NAME="fastled.exe" + VENV_BIN_DIR=".venv/Scripts" +else + EXE_NAME="fastled" + VENV_BIN_DIR=".venv/bin" +fi + +BIN_SRC="" +# Discover where the binary landed. `_cargo` sets CARGO_BUILD_TARGET on +# Windows, so the bin is under target//release/; on other platforms +# (and when binstall provided it) check the usual locations. +for CANDIDATE in \ + "target/x86_64-pc-windows-msvc/release/${EXE_NAME}" \ + "target/aarch64-pc-windows-msvc/release/${EXE_NAME}" \ + "target/release/${EXE_NAME}" \ + "${CARGO_BIN}/${EXE_NAME}"; do + if [[ -f "$CANDIDATE" ]]; then + BIN_SRC="$CANDIDATE" + break + fi +done + +if [[ -n "$BIN_SRC" ]]; then + mkdir -p "$VENV_BIN_DIR" wheel-data/scripts + cp -f "$BIN_SRC" "$VENV_BIN_DIR/$EXE_NAME" + cp -f "$BIN_SRC" "wheel-data/scripts/$EXE_NAME" + echo "Staged $BIN_SRC -> $VENV_BIN_DIR/$EXE_NAME (and wheel-data/scripts/)" +else + echo "Warning: Rust fastled binary not found; PATH lookups for 'fastled' will miss" >&2 +fi diff --git a/pyproject.toml b/pyproject.toml index 7840b05f..9f90a6d1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,13 @@ manifest-path = "crates/fastled-py/Cargo.toml" module-name = "fastled._native" python-source = "src" features = ["pyo3/extension-module", "pyo3/abi3-py310"] +# Pre-built Rust binaries get dropped into wheel-data/scripts/ by the +# build-wheel helper before maturin runs. maturin packages this directory as +# the wheel's -.data/ tree; pip then extracts scripts/ to the +# venv's Scripts/ (Windows) or bin/ (Unix) at install time, so end users get +# the Rust `fastled` binary directly — no Python entry-point shim, no +# cargo build at install time. +data = "wheel-data" [tool.ruff] line-length = 200 @@ -50,6 +57,10 @@ ignore_missing_imports = true disable_error_code = ["import-untyped"] [project.scripts] +# `fastled` is intentionally NOT a Python entry-point; the Rust binary is +# bundled into the wheel via [tool.maturin] data (see above) and pip +# installs it directly to the venv's Scripts/bin directory. The Python +# aliases below are kept as thin shims for the rarely-used `python -m` +# invocation paths. fastled-wasm = "fastled.cli:main" fled = "fastled.cli:main" -fastled = "fastled.cli:main" diff --git a/src/fastled/_rust_cli.py b/src/fastled/_rust_cli.py index 557e3ff9..808c7a01 100644 --- a/src/fastled/_rust_cli.py +++ b/src/fastled/_rust_cli.py @@ -1,20 +1,21 @@ -"""Locate the Rust ``fastled`` binary, NOT the Python entry-point shim. +"""Locate the Rust ``fastled`` binary. -The Python package registers ``fastled`` as a console-script in -``[project.scripts]``, which lands at ``.venv/Scripts/fastled.exe`` (or -``.venv/bin/fastled``) and shadows the Rust binary on ``PATH``. The Rust -binary needs to be invoked for the internal plumbing flags -(``--internal-ensure-fastled-repo`` etc.); the shim's argparse rejects them. +In wheel-installed deployments the Rust binary is bundled directly into the +venv's ``Scripts/`` / ``bin/`` directory via ``[tool.maturin] data`` (see +``pyproject.toml``), so ``shutil.which(\"fastled\")`` returns it. In editable +dev installs the Rust binary lives under ``target/`` from a local +``cargo build --bin fastled``. Search order: - 1. Workspace ``target/{release,debug}/fastled[.exe]`` (dev builds). + 1. Workspace ``target/{release,debug}/fastled[.exe]`` (dev / editable). 2. ``$CARGO_HOME/bin/fastled[.exe]`` (where ``cargo binstall`` installs). - 3. PATH walk that skips Python venv / system-Python directories. + 3. ``shutil.which(\"fastled\")`` (wheel install puts it on ``PATH``). """ from __future__ import annotations import os +import shutil import sys from pathlib import Path @@ -23,23 +24,11 @@ def _exe_name() -> str: return "fastled.exe" if sys.platform == "win32" else "fastled" -def _looks_like_python_dir(dir_path: Path) -> bool: - """Return True if ``dir_path`` hosts a Python interpreter. - - Used to filter out Python venv/install dirs from the PATH walk so that a - ``fastled`` console-script entry-point in the same directory does not - shadow the actual Rust binary. - """ - if sys.platform == "win32": - return (dir_path / "python.exe").is_file() - return (dir_path / "python").is_file() or (dir_path / "python3").is_file() - - 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 builds). + # 1. Workspace target/ tree (dev / editable). current = Path(__file__).resolve().parent for _ in range(10): if (current / "Cargo.toml").is_file(): @@ -71,17 +60,11 @@ def find_rust_fastled_cli() -> Path | None: if candidate.is_file(): return candidate - # 3. PATH walk, skipping Python interpreter dirs (which contain the - # Python entry-point shim that shadows the Rust binary). - for path_entry in os.environ.get("PATH", "").split(os.pathsep): - if not path_entry: - continue - path_dir = Path(path_entry) - candidate = path_dir / exe - if not candidate.is_file(): - continue - if _looks_like_python_dir(path_dir): - continue - return candidate - + # 3. Wheel install drops the Rust binary directly into the venv's + # Scripts/bin dir; there is no Python `fastled` entry-point shim + # competing for the name anymore (see pyproject.toml). Plain PATH lookup + # finds it. + found = shutil.which(exe) + if found: + return Path(found) return None