Skip to main content

litz_cli/
toolchain.rs

1//! `litz toolchain`: which firmware toolchains this machine has, and
2//! `litz editor --vscode`: the editor configuration that points a debugger at
3//! the runner's GDB stub.
4//!
5//! Detection is read-only. It looks for executables on `PATH` (and under
6//! `$IDF_PATH`) and runs only version-style commands, each with a short
7//! timeout. It makes no network calls and installs nothing.
8//!
9//! The editor configuration is ordinary VS Code JSON: a `cppdbg` launch
10//! configuration that connects to `127.0.0.1:<port>`, and a background task
11//! that runs `litz run . --gdb <port>` so the firmware boots, the GDB stub
12//! starts, and the run's serial output stays in the task's terminal.
13
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value, json};
16use std::path::{Path, PathBuf};
17use std::process::{Command, Stdio};
18use std::time::{Duration, Instant};
19
20/// Port the generated VS Code task serves the GDB stub on.
21pub const DEFAULT_GDB_PORT: u16 = 3333;
22
23/// How long one version probe may take. Long enough for a cold interpreter,
24/// short enough that a broken wrapper cannot stall `litz toolchain`.
25const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
26
27/// One row of the detection table.
28#[derive(Clone, Debug, Serialize)]
29pub struct Tool {
30    pub name: &'static str,
31    pub found: bool,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub path: Option<String>,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub version: Option<String>,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub note: Option<String>,
38}
39
40/// What detection may consult: `PATH` entries and `$IDF_PATH`.
41///
42/// Kept explicit so a test can hand over a fake `PATH` without touching the
43/// process environment.
44#[derive(Clone, Debug)]
45pub struct Environment {
46    path: Vec<PathBuf>,
47    idf_path: Option<PathBuf>,
48}
49
50impl Environment {
51    /// Read `PATH` and `IDF_PATH` from this process.
52    pub fn from_process() -> Self {
53        let path = std::env::var_os("PATH")
54            .map(|value| {
55                std::env::split_paths(&value)
56                    .filter(|entry| !entry.as_os_str().is_empty())
57                    .collect()
58            })
59            .unwrap_or_default();
60        let idf_path = std::env::var_os("IDF_PATH")
61            .filter(|value| !value.is_empty())
62            .map(PathBuf::from);
63        Self { path, idf_path }
64    }
65
66    /// The debugger the generated launch configuration should name, when one
67    /// of the common ESP32 GDB builds is installed.
68    pub fn gdb(&self) -> Option<PathBuf> {
69        [
70            "riscv32-esp-elf-gdb",
71            "xtensa-esp32s3-elf-gdb",
72            "xtensa-esp32-elf-gdb",
73            "gdb",
74        ]
75        .iter()
76        .find_map(|name| self.find_on_path(name))
77    }
78
79    fn find_on_path(&self, name: &str) -> Option<PathBuf> {
80        self.path.iter().find_map(|directory| {
81            executable_candidates(directory, name)
82                .into_iter()
83                .find(|candidate| is_executable(candidate))
84        })
85    }
86
87    fn probe_version(&self, program: &Path, args: &[&str]) -> Option<String> {
88        let capture = self.capture(program, args)?;
89        // A failed probe usually printed usage or a traceback, not a version.
90        if !capture.success {
91            return None;
92        }
93        let text = if capture.stdout.trim().is_empty() {
94            &capture.stderr
95        } else {
96            &capture.stdout
97        };
98        let line = text.lines().map(str::trim).find(|line| !line.is_empty())?;
99        Some(shorten(line))
100    }
101
102    /// Run a short command and collect its output, killing it at
103    /// [`PROBE_TIMEOUT`] so a wrapper that waits on input cannot hang the CLI.
104    fn capture(&self, program: &Path, args: &[&str]) -> Option<Capture> {
105        let mut command = Command::new(program);
106        command
107            .args(args)
108            .stdin(Stdio::null())
109            .stdout(Stdio::piped())
110            .stderr(Stdio::piped());
111        if !self.path.is_empty() {
112            let joined = std::env::join_paths(self.path.iter()).ok()?;
113            command.env("PATH", joined);
114        }
115        let mut child = command.spawn().ok()?;
116        let deadline = Instant::now() + PROBE_TIMEOUT;
117        loop {
118            match child.try_wait() {
119                Ok(Some(_)) => break,
120                Ok(None) => {}
121                Err(_) => {
122                    let _ = child.kill();
123                    let _ = child.wait();
124                    return None;
125                }
126            }
127            if Instant::now() >= deadline {
128                let _ = child.kill();
129                let _ = child.wait();
130                return None;
131            }
132            std::thread::sleep(Duration::from_millis(10));
133        }
134        let output = child.wait_with_output().ok()?;
135        Some(Capture {
136            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
137            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
138            success: output.status.success(),
139        })
140    }
141
142    /// The installed version of Arduino's ESP32 core, read through
143    /// `arduino-cli core list`.
144    fn esp32_core(&self, arduino_cli: &Path) -> Option<String> {
145        let capture = self.capture(arduino_cli, &["core", "list"])?;
146        if !capture.success {
147            return None;
148        }
149        for line in capture.stdout.lines() {
150            let mut fields = line.split_whitespace();
151            if fields.next() == Some("esp32:esp32") {
152                return fields.next().map(str::to_string);
153            }
154        }
155        None
156    }
157
158    /// Whether the wasm target is installed. `rustup` knows the installed
159    /// targets directly; without it, the sysroot is the evidence.
160    fn wasm_target(&self, rustc: Option<&Path>) -> Option<&'static str> {
161        if let Some(rustup) = self.find_on_path("rustup")
162            && let Some(capture) = self.capture(&rustup, &["target", "list", "--installed"])
163            && capture.success
164            && capture
165                .stdout
166                .lines()
167                .any(|line| line.trim() == "wasm32-unknown-unknown")
168        {
169            return Some("installed via rustup");
170        }
171        let capture = self.capture(rustc?, &["--print", "sysroot"])?;
172        let sysroot = PathBuf::from(capture.stdout.trim());
173        let target = sysroot
174            .join("lib")
175            .join("rustlib")
176            .join("wasm32-unknown-unknown");
177        target.is_dir().then_some("found in the rustc sysroot")
178    }
179}
180
181struct Capture {
182    stdout: String,
183    stderr: String,
184    success: bool,
185}
186
187/// The fixed detection table, in the order the report prints it.
188pub fn detect(environment: &Environment) -> Vec<Tool> {
189    let mut tools = Vec::new();
190
191    // Arduino first: the ESP32 core is only visible through the CLI.
192    let arduino_cli = environment.find_on_path("arduino-cli");
193    let arduino_version = arduino_cli
194        .as_deref()
195        .and_then(|program| environment.probe_version(program, &["version"]));
196    tools.push(match &arduino_cli {
197        Some(path) => found("arduino-cli", Some(path.clone()), arduino_version, None),
198        None => missing("arduino-cli"),
199    });
200    let core = arduino_cli.as_deref().and_then(|program| {
201        environment
202            .esp32_core(program)
203            .map(|version| (program.to_path_buf(), version))
204    });
205    tools.push(match core {
206        Some((cli, version)) => found(
207            "arduino core esp32",
208            Some(cli),
209            Some(version),
210            Some("via arduino-cli core list"),
211        ),
212        None => missing("arduino core esp32"),
213    });
214
215    // ESP-IDF: the script may come from PATH or from $IDF_PATH/tools.
216    let idf_script = environment.find_on_path("idf.py").or_else(|| {
217        environment
218            .idf_path
219            .as_ref()
220            .map(|root| root.join("tools").join("idf.py"))
221            .filter(|path| is_executable(path))
222    });
223    tools.push(match &idf_script {
224        Some(script) => found(
225            "idf.py",
226            Some(script.clone()),
227            environment.probe_version(script, &["--version"]),
228            None,
229        ),
230        None => match &environment.idf_path {
231            Some(root) if root.is_dir() => found(
232                "idf.py",
233                Some(root.clone()),
234                None,
235                Some("$IDF_PATH is set but tools/idf.py was not found"),
236            ),
237            _ => missing("idf.py"),
238        },
239    });
240
241    for name in [
242        "riscv32-esp-elf-gcc",
243        "xtensa-esp32-elf-gcc",
244        "xtensa-esp32s3-elf-gcc",
245        "xtensa-esp32c3-elf-gcc",
246        "arm-none-eabi-gcc",
247        "avr-gcc",
248    ] {
249        tools.push(compiler(environment, name));
250    }
251
252    tools.push(match environment.find_on_path("avrdude") {
253        Some(path) => found(
254            "avrdude",
255            Some(path.clone()),
256            environment.probe_version(&path, &["--version"]),
257            None,
258        ),
259        None => missing("avrdude"),
260    });
261
262    // The host interpreter and the tool that reaches a board are separate
263    // capabilities: one can be installed without the other.
264    for (name, note) in [
265        ("micropython", None),
266        // CircuitPython's host CLI is separate from MicroPython's; firmware
267        // images for the simulator come from tools/fetch-circuitpython.sh.
268        (
269            "circuitpython",
270            Some("images come from tools/fetch-circuitpython.sh"),
271        ),
272        ("mpremote", Some("for boards over USB serial")),
273    ] {
274        tools.push(match environment.find_on_path(name) {
275            Some(path) => found(
276                name,
277                Some(path.clone()),
278                environment.probe_version(&path, &["--version"]),
279                note,
280            ),
281            None => missing(name),
282        });
283    }
284
285    let rustc = environment.find_on_path("rustc");
286    let rustc_version = rustc
287        .as_deref()
288        .and_then(|program| environment.probe_version(program, &["--version"]));
289    tools.push(match &rustc {
290        Some(path) => found("rustc", Some(path.clone()), rustc_version, None),
291        None => missing("rustc"),
292    });
293    tools.push(match environment.wasm_target(rustc.as_deref()) {
294        Some(note) => found("rust target wasm32-unknown-unknown", None, None, Some(note)),
295        None => missing("rust target wasm32-unknown-unknown"),
296    });
297
298    tools
299}
300
301/// The report as one line per tool, with columns aligned.
302pub fn table(tools: &[Tool]) -> String {
303    let width = tools
304        .iter()
305        .map(|tool| tool.name.len())
306        .max()
307        .unwrap_or(0)
308        .max(20);
309    let mut output = String::new();
310    for tool in tools {
311        if tool.found {
312            output.push_str(&format!("{:<width$}  ", tool.name));
313            match &tool.path {
314                Some(path) => output.push_str(path),
315                None => output.push_str("found"),
316            }
317            if let Some(version) = &tool.version {
318                output.push_str(&format!("  ({version})"));
319            }
320            if let Some(note) = &tool.note {
321                output.push_str(&format!("  [{note}]"));
322            }
323        } else {
324            output.push_str(&format!("{:<width$}  not found", tool.name));
325        }
326        output.push('\n');
327    }
328    output
329}
330
331/// The report as a machine-readable object: `{"tools": [...]}`.
332pub fn to_json(tools: &[Tool]) -> String {
333    let document = json!({ "tools": tools });
334    let mut text =
335        serde_json::to_string_pretty(&document).expect("the detection table always serialises");
336    text.push('\n');
337    text
338}
339
340fn compiler(environment: &Environment, name: &'static str) -> Tool {
341    match environment.find_on_path(name) {
342        Some(path) => {
343            let version = environment.probe_version(&path, &["--version"]);
344            found(name, Some(path), version, None)
345        }
346        None => missing(name),
347    }
348}
349
350fn found(
351    name: &'static str,
352    path: Option<PathBuf>,
353    version: Option<String>,
354    note: Option<&str>,
355) -> Tool {
356    Tool {
357        name,
358        found: true,
359        path: path.map(|path| path.display().to_string()),
360        version,
361        note: note.map(str::to_string),
362    }
363}
364
365fn missing(name: &'static str) -> Tool {
366    Tool {
367        name,
368        found: false,
369        path: None,
370        version: None,
371        note: None,
372    }
373}
374
375#[cfg(windows)]
376fn executable_candidates(directory: &Path, name: &str) -> Vec<PathBuf> {
377    vec![directory.join(format!("{name}.exe")), directory.join(name)]
378}
379
380#[cfg(not(windows))]
381fn executable_candidates(directory: &Path, name: &str) -> Vec<PathBuf> {
382    vec![directory.join(name)]
383}
384
385#[cfg(unix)]
386fn is_executable(path: &Path) -> bool {
387    use std::os::unix::fs::PermissionsExt;
388    std::fs::metadata(path)
389        .map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
390        .unwrap_or(false)
391}
392
393#[cfg(not(unix))]
394fn is_executable(path: &Path) -> bool {
395    path.is_file()
396}
397
398fn shorten(line: &str) -> String {
399    let collapsed = line.split_whitespace().collect::<Vec<_>>().join(" ");
400    if collapsed.chars().count() <= 120 {
401        return collapsed;
402    }
403    let mut short: String = collapsed.chars().take(117).collect();
404    short.push_str("...");
405    short
406}
407
408/// `litz editor --vscode`: write or merge the editor files for `directory`.
409///
410/// Without `force`, any existing `launch.json` or `tasks.json` is refused
411/// rather than replaced. With `force`, the Litz entries are merged into the
412/// existing documents, so unrelated configurations and tasks survive.
413pub fn write_vscode(directory: &Path, force: bool, port: u16) -> Result<Vec<PathBuf>, String> {
414    let environment = Environment::from_process();
415    write_vscode_with(directory, force, port, environment.gdb().as_deref())
416}
417
418fn write_vscode_with(
419    directory: &Path,
420    force: bool,
421    port: u16,
422    gdb: Option<&Path>,
423) -> Result<Vec<PathBuf>, String> {
424    if !directory.is_dir() {
425        return Err(format!("{}: not a directory", directory.display()));
426    }
427    let vscode = directory.join(".vscode");
428    let launch_path = vscode.join("launch.json");
429    let tasks_path = vscode.join("tasks.json");
430
431    if !force {
432        for path in [&launch_path, &tasks_path] {
433            if path.exists() {
434                return Err(format!(
435                    "{} already exists; pass --force to merge the Litz configuration into it",
436                    path.display()
437                ));
438            }
439        }
440    }
441
442    let launch = merge_document(
443        read_existing(&launch_path, force)?,
444        "0.2.0",
445        "configurations",
446        "name",
447        LAUNCH_NAME,
448        launch_configuration(&program_for(directory), gdb, port),
449    );
450    let tasks = merge_document(
451        read_existing(&tasks_path, force)?,
452        "2.0.0",
453        "tasks",
454        "label",
455        TASK_LABEL,
456        debug_task(port),
457    );
458
459    std::fs::create_dir_all(&vscode).map_err(|error| format!("{}: {error}", vscode.display()))?;
460    write_json(&launch_path, &launch)?;
461    write_json(&tasks_path, &tasks)?;
462    Ok(vec![launch_path, tasks_path])
463}
464
465const LAUNCH_NAME: &str = "Litz: debug firmware";
466const TASK_LABEL: &str = "litz: run firmware with GDB";
467
468#[derive(Deserialize, Default)]
469struct Manifest {
470    sim: Option<Sim>,
471}
472
473#[derive(Deserialize, Default)]
474struct Sim {
475    elf: Option<String>,
476    firmware: Option<String>,
477}
478
479/// The file GDB should load symbols from. `[sim] elf` is what Litz's own
480/// debugger path uses; a bare firmware image still gives GDB an address space.
481fn program_for(directory: &Path) -> String {
482    let file = std::fs::read_to_string(directory.join("litz.toml"))
483        .ok()
484        .and_then(|text| toml::from_str::<Manifest>(&text).ok())
485        .and_then(|manifest| manifest.sim)
486        .and_then(|sim| sim.elf.or(sim.firmware));
487    match file {
488        Some(file) if Path::new(&file).is_absolute() => file,
489        Some(file) => format!("${{workspaceFolder}}/{}", file.replace('\\', "/")),
490        None => "${workspaceFolder}".to_string(),
491    }
492}
493
494fn launch_configuration(program: &str, gdb: Option<&Path>, port: u16) -> Value {
495    let mut configuration = json!({
496        "name": LAUNCH_NAME,
497        "type": "cppdbg",
498        "request": "launch",
499        "program": program,
500        "cwd": "${workspaceFolder}",
501        "stopAtEntry": false,
502        "externalConsole": false,
503        "MIMode": "gdb",
504        "miDebuggerServerAddress": format!("127.0.0.1:{port}"),
505        "preLaunchTask": TASK_LABEL,
506        "setupCommands": [{
507            "description": "Enable gdb pretty-printing",
508            "text": "-enable-pretty-printing",
509            "ignoreFailures": true
510        }]
511    });
512    if let Some(gdb) = gdb {
513        configuration["miDebuggerPath"] = json!(gdb.display().to_string());
514    }
515    configuration
516}
517
518fn debug_task(port: u16) -> Value {
519    json!({
520        "label": TASK_LABEL,
521        "type": "shell",
522        "command": "litz",
523        "args": ["run", ".", "--gdb", port.to_string()],
524        "options": { "cwd": "${workspaceFolder}" },
525        "isBackground": true,
526        "problemMatcher": {
527            "owner": "litz",
528            "pattern": {
529                "regexp": "^litz-diagnostic: ([^:]+): (.*)$",
530                "file": 1,
531                "message": 2
532            },
533            "background": {
534                "activeOnStart": true,
535                "beginsPattern": "litz: gdb serves board",
536                "endsPattern": "litz: gdb waiting on"
537            }
538        },
539        "presentation": { "reveal": "always", "panel": "dedicated", "clear": true }
540    })
541}
542
543/// Merge one named entry into an existing document, keeping everything else.
544fn merge_document(
545    existing: Option<Value>,
546    version: &str,
547    array_key: &str,
548    name_key: &str,
549    name: &str,
550    item: Value,
551) -> Value {
552    let mut root = match existing {
553        Some(value) if value.is_object() => value,
554        _ => {
555            let mut object = Map::new();
556            object.insert("version".to_string(), Value::String(version.to_string()));
557            object.insert(array_key.to_string(), Value::Array(Vec::new()));
558            Value::Object(object)
559        }
560    };
561    let object = root
562        .as_object_mut()
563        .expect("the document was just checked to be an object");
564    object
565        .entry("version".to_string())
566        .or_insert_with(|| json!(version));
567    let array = object
568        .entry(array_key.to_string())
569        .or_insert_with(|| Value::Array(Vec::new()));
570    if !array.is_array() {
571        *array = Value::Array(Vec::new());
572    }
573    let array = array
574        .as_array_mut()
575        .expect("the entry was just made an array");
576    match array
577        .iter_mut()
578        .find(|entry| entry.get(name_key).and_then(Value::as_str) == Some(name))
579    {
580        Some(slot) => *slot = item,
581        None => array.push(item),
582    }
583    root
584}
585
586fn read_existing(path: &Path, force: bool) -> Result<Option<Value>, String> {
587    if !path.exists() {
588        return Ok(None);
589    }
590    let text =
591        std::fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))?;
592    match serde_json::from_str(&text) {
593        Ok(value) => Ok(Some(value)),
594        // With --force an unparseable file is replaced rather than merged.
595        Err(_) if force => Ok(None),
596        Err(error) => Err(format!("{}: {error}", path.display())),
597    }
598}
599
600fn write_json(path: &Path, value: &Value) -> Result<(), String> {
601    let mut text = serde_json::to_string_pretty(value)
602        .map_err(|error| format!("{}: {error}", path.display()))?;
603    text.push('\n');
604    std::fs::write(path, text).map_err(|error| format!("{}: {error}", path.display()))
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610    use std::sync::atomic::{AtomicU32, Ordering};
611
612    fn scratch(tag: &str) -> PathBuf {
613        static NEXT: AtomicU32 = AtomicU32::new(0);
614        let n = NEXT.fetch_add(1, Ordering::Relaxed);
615        let dir =
616            std::env::temp_dir().join(format!("litz-toolchain-{}-{n}-{tag}", std::process::id()));
617        let _ = std::fs::remove_dir_all(&dir);
618        std::fs::create_dir_all(&dir).unwrap();
619        dir
620    }
621
622    #[cfg(unix)]
623    fn fake_tool(directory: &Path, name: &str, body: &str) -> PathBuf {
624        use std::os::unix::fs::PermissionsExt;
625        let path = directory.join(name);
626        std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
627        let mut permissions = std::fs::metadata(&path).unwrap().permissions();
628        permissions.set_mode(0o755);
629        std::fs::set_permissions(&path, permissions).unwrap();
630        path
631    }
632
633    fn tool<'a>(tools: &'a [Tool], name: &str) -> &'a Tool {
634        tools
635            .iter()
636            .find(|tool| tool.name == name)
637            .unwrap_or_else(|| panic!("{name:?} is in the detection table"))
638    }
639
640    #[cfg(unix)]
641    #[test]
642    fn the_detection_table_reads_versions_from_a_fake_path() {
643        let bin = scratch("detect-bin");
644        fake_tool(
645            &bin,
646            "arduino-cli",
647            r#"if [ "$1" = "version" ]; then
648  echo "arduino-cli  Version: 1.0.4 Commit: deadbeef"
649elif [ "$1" = "core" ]; then
650  printf 'ID          Installed Latest Name\nesp32:esp32 3.0.7     3.0.7  Arduino ESP32 Boards\n'
651fi"#,
652        );
653        fake_tool(
654            &bin,
655            "riscv32-esp-elf-gcc",
656            r#"echo "riscv32-esp-elf-gcc (crosstool-NG) 13.2.0""#,
657        );
658        fake_tool(
659            &bin,
660            "xtensa-esp32s3-elf-gcc",
661            r#"echo "xtensa-esp32s3-elf-gcc (crosstool-NG) 12.2.0""#,
662        );
663        fake_tool(&bin, "rustc", r#"echo "rustc 1.98.0-nightly""#);
664        fake_tool(&bin, "circuitpython", r#"echo "CircuitPython 10.3.2""#);
665        fake_tool(
666            &bin,
667            "rustup",
668            r#"if [ "$1" = "target" ]; then
669  printf 'wasm32-unknown-unknown\nx86_64-apple-darwin\n'
670fi"#,
671        );
672
673        let idf = scratch("detect-idf");
674        let idf_tools = idf.join("tools");
675        std::fs::create_dir_all(&idf_tools).unwrap();
676        fake_tool(&idf_tools, "idf.py", r#"echo "ESP-IDF v5.2.1""#);
677
678        let environment = Environment {
679            path: vec![bin.clone()],
680            idf_path: Some(idf.clone()),
681        };
682        let tools = detect(&environment);
683
684        let arduino = tool(&tools, "arduino-cli");
685        assert!(arduino.found);
686        assert!(arduino.version.as_deref().unwrap().contains("1.0.4"));
687
688        let core = tool(&tools, "arduino core esp32");
689        assert!(core.found);
690        assert_eq!(core.version.as_deref(), Some("3.0.7"));
691
692        let idf_tool = tool(&tools, "idf.py");
693        assert!(idf_tool.found);
694        assert!(idf_tool.path.as_deref().unwrap().ends_with("tools/idf.py"));
695        assert!(
696            idf_tool
697                .version
698                .as_deref()
699                .unwrap()
700                .contains("ESP-IDF v5.2.1")
701        );
702
703        let riscv = tool(&tools, "riscv32-esp-elf-gcc");
704        assert!(riscv.found);
705        assert!(riscv.version.as_deref().unwrap().contains("13.2.0"));
706
707        assert!(tool(&tools, "xtensa-esp32s3-elf-gcc").found);
708        assert!(!tool(&tools, "xtensa-esp32-elf-gcc").found);
709        assert!(!tool(&tools, "xtensa-esp32c3-elf-gcc").found);
710        assert!(!tool(&tools, "arm-none-eabi-gcc").found);
711        assert!(!tool(&tools, "avr-gcc").found);
712        assert!(!tool(&tools, "avrdude").found);
713        assert!(!tool(&tools, "micropython").found);
714        assert!(!tool(&tools, "mpremote").found);
715
716        let circuitpython = tool(&tools, "circuitpython");
717        assert!(circuitpython.found);
718        assert!(circuitpython.version.as_deref().unwrap().contains("10.3.2"));
719
720        let rustc = tool(&tools, "rustc");
721        assert!(rustc.found);
722        assert!(rustc.version.as_deref().unwrap().contains("1.98.0"));
723
724        let target = tool(&tools, "rust target wasm32-unknown-unknown");
725        assert!(target.found);
726        assert_eq!(target.note.as_deref(), Some("installed via rustup"));
727
728        let _ = std::fs::remove_dir_all(&bin);
729        let _ = std::fs::remove_dir_all(&idf);
730    }
731
732    #[test]
733    fn an_empty_path_reports_every_tool_as_missing() {
734        let bin = scratch("empty-bin");
735        let environment = Environment {
736            path: vec![bin.clone()],
737            idf_path: None,
738        };
739        let tools = detect(&environment);
740        assert!(!tools.is_empty());
741        for tool in &tools {
742            assert!(!tool.found, "{} should be missing", tool.name);
743            assert!(tool.path.is_none(), "{} should have no path", tool.name);
744        }
745        let _ = std::fs::remove_dir_all(&bin);
746    }
747
748    #[test]
749    fn json_is_one_object_with_a_tools_array() {
750        let bin = scratch("json-bin");
751        let environment = Environment {
752            path: vec![bin.clone()],
753            idf_path: None,
754        };
755        let text = to_json(&detect(&environment));
756        let document: Value = serde_json::from_str(&text).unwrap();
757        let tools = document["tools"].as_array().unwrap();
758        assert!(tools.iter().any(|tool| tool["name"] == "rustc"));
759        assert!(tools.iter().all(|tool| tool["found"].is_boolean()));
760        let _ = std::fs::remove_dir_all(&bin);
761    }
762
763    #[test]
764    fn editor_writes_valid_json_and_then_refuses_without_force() {
765        let dir = scratch("editor-fresh");
766        std::fs::write(
767            dir.join("litz.toml"),
768            "[sim]\nfirmware = \"firmware/app.bin\"\n",
769        )
770        .unwrap();
771
772        let written =
773            write_vscode_with(&dir, false, DEFAULT_GDB_PORT, Some(Path::new("/bin/gdb"))).unwrap();
774        assert_eq!(written.len(), 2);
775
776        let launch: Value = serde_json::from_str(
777            &std::fs::read_to_string(dir.join(".vscode/launch.json")).unwrap(),
778        )
779        .unwrap();
780        let configurations = launch["configurations"].as_array().unwrap();
781        assert_eq!(configurations.len(), 1);
782        let configuration = &configurations[0];
783        assert_eq!(configuration["name"].as_str(), Some(LAUNCH_NAME));
784        assert_eq!(configuration["type"].as_str(), Some("cppdbg"));
785        assert_eq!(
786            configuration["miDebuggerServerAddress"].as_str(),
787            Some("127.0.0.1:3333")
788        );
789        assert_eq!(configuration["miDebuggerPath"].as_str(), Some("/bin/gdb"));
790        assert!(
791            configuration["program"]
792                .as_str()
793                .unwrap()
794                .ends_with("firmware/app.bin")
795        );
796
797        let tasks: Value =
798            serde_json::from_str(&std::fs::read_to_string(dir.join(".vscode/tasks.json")).unwrap())
799                .unwrap();
800        let task = &tasks["tasks"][0];
801        assert_eq!(task["command"].as_str(), Some("litz"));
802        let args: Vec<&str> = task["args"]
803            .as_array()
804            .unwrap()
805            .iter()
806            .filter_map(Value::as_str)
807            .collect();
808        let gdb = args
809            .iter()
810            .position(|arg| *arg == "--gdb")
811            .expect("the task serves the GDB stub");
812        assert_eq!(args.get(gdb + 1), Some(&"3333"));
813
814        let error = write_vscode_with(&dir, false, DEFAULT_GDB_PORT, None).unwrap_err();
815        assert!(error.contains("--force"), "{error}");
816
817        let _ = std::fs::remove_dir_all(&dir);
818    }
819
820    #[test]
821    fn merging_keeps_unrelated_configurations_and_tasks() {
822        let dir = scratch("editor-merge");
823        let vscode = dir.join(".vscode");
824        std::fs::create_dir_all(&vscode).unwrap();
825        std::fs::write(
826            vscode.join("launch.json"),
827            r#"{"version":"0.2.0","configurations":[{"name":"Unrelated","type":"node"}]}"#,
828        )
829        .unwrap();
830        std::fs::write(
831            vscode.join("tasks.json"),
832            r#"{"version":"2.0.0","tasks":[{"label":"Unrelated","command":"true"}]}"#,
833        )
834        .unwrap();
835
836        write_vscode_with(&dir, true, 4444, None).unwrap();
837
838        let launch: Value =
839            serde_json::from_str(&std::fs::read_to_string(vscode.join("launch.json")).unwrap())
840                .unwrap();
841        let names: Vec<&str> = launch["configurations"]
842            .as_array()
843            .unwrap()
844            .iter()
845            .filter_map(|entry| entry["name"].as_str())
846            .collect();
847        assert!(names.contains(&"Unrelated"), "{names:?}");
848        assert!(names.contains(&LAUNCH_NAME), "{names:?}");
849
850        let tasks: Value =
851            serde_json::from_str(&std::fs::read_to_string(vscode.join("tasks.json")).unwrap())
852                .unwrap();
853        let labels: Vec<&str> = tasks["tasks"]
854            .as_array()
855            .unwrap()
856            .iter()
857            .filter_map(|entry| entry["label"].as_str())
858            .collect();
859        assert!(labels.contains(&"Unrelated"), "{labels:?}");
860        assert!(labels.contains(&TASK_LABEL), "{labels:?}");
861
862        let _ = std::fs::remove_dir_all(&dir);
863    }
864
865    #[test]
866    fn an_existing_file_is_refused_before_anything_is_written() {
867        let dir = scratch("editor-existing");
868        let vscode = dir.join(".vscode");
869        std::fs::create_dir_all(&vscode).unwrap();
870        std::fs::write(vscode.join("launch.json"), "{}").unwrap();
871
872        let error = write_vscode_with(&dir, false, DEFAULT_GDB_PORT, None).unwrap_err();
873        assert!(error.contains("--force"), "{error}");
874        assert!(
875            !vscode.join("tasks.json").exists(),
876            "nothing is written when the run is refused"
877        );
878
879        let _ = std::fs::remove_dir_all(&dir);
880    }
881}