Skip to main content

litz_cli/
catalog.rs

1//! `litz catalog`: the builtin catalog as JSON.
2//!
3//! The command exists so a front end can render a component picker without
4//! linking the runner. It reads the same [`Registry::builtin`] every other
5//! command starts from and prints one record per entry. Nothing here
6//! simulates, loads a diagram or touches the filesystem.
7
8use litz_catalog::{PartManifest, Registry, Simulation};
9use litz_diagram::AttrDef;
10use serde_json::{Value, json};
11use std::collections::BTreeSet;
12use std::fmt::Write as _;
13use std::path::{Component, Path, PathBuf};
14
15/// The builtin catalog as a JSON array, one object per part or board.
16pub fn builtin_json() -> String {
17    json_text(&Registry::builtin())
18}
19
20/// Serialise a registry. Every entry appears exactly once, ordered by id
21/// because the registry is a `BTreeMap`.
22pub fn json_text(registry: &Registry) -> String {
23    serde_json::to_string_pretty(&value(registry))
24        .expect("a catalog entry holds only JSON-serialisable values")
25}
26
27/// The catalog as a JSON value: `{id, kind, name, description, pins, attrs}`.
28pub fn value(registry: &Registry) -> Value {
29    let mut entries = Vec::new();
30    for id in registry.ids() {
31        let Some(manifest) = registry.get(id) else {
32            continue;
33        };
34        let kind = if manifest.board.is_some() {
35            "board"
36        } else {
37            "part"
38        };
39        entries.push(json!({
40            "id": manifest.id,
41            "kind": kind,
42            "name": manifest.name,
43            "description": manifest.description,
44            "pins": manifest.pins.iter()
45                .map(|pin| json!({"name": pin.name, "kind": pin.kind}))
46                .collect::<Vec<_>>(),
47            "attrs": manifest.attrs.iter().map(attr_value).collect::<Vec<_>>(),
48        }));
49    }
50    Value::Array(entries)
51}
52
53fn attr_value(attr: &AttrDef) -> Value {
54    json!({
55        "name": attr.name,
56        "type": attr.kind,
57        "values": attr.values,
58        "default": attr.default,
59    })
60}
61
62// ------------------------------------------------------------ human listings
63
64/// One row of a human catalog table.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct Row {
67    pub id: String,
68    pub kind: &'static str,
69    pub name: String,
70    pub pins: usize,
71    /// `builtin`, `parts/` or `boards/`.
72    pub source: &'static str,
73}
74
75/// The registry's entries as rows, ordered by id.
76pub fn rows(registry: &Registry) -> Vec<Row> {
77    let mut rows: Vec<Row> = registry
78        .ids()
79        .filter_map(|id| registry.get(id))
80        .map(|manifest| Row {
81            id: manifest.id.clone(),
82            kind: if manifest.board.is_some() {
83                "board"
84            } else {
85                "part"
86            },
87            name: manifest.name.clone(),
88            pins: manifest.pins.len(),
89            source: source_label(manifest.source.as_deref()),
90        })
91        .collect();
92    rows.sort_by(|a, b| a.id.cmp(&b.id));
93    rows
94}
95
96/// The directory a manifest was loaded from, as the table spells it.
97fn source_label(source: Option<&Path>) -> &'static str {
98    match source
99        .and_then(Path::parent)
100        .and_then(Path::file_name)
101        .and_then(|name| name.to_str())
102    {
103        Some("parts") => "parts/",
104        Some("boards") => "boards/",
105        Some(_) => "project",
106        None => "builtin",
107    }
108}
109
110/// Render rows as a compact human table. `source` adds the source column used
111/// by `catalog list`; `catalog` itself leaves it off.
112pub fn table(rows: &[Row], source: bool) -> String {
113    let id_width = rows
114        .iter()
115        .map(|row| row.id.len())
116        .max()
117        .unwrap_or(0)
118        .max("id".len());
119    let kind_width = rows
120        .iter()
121        .map(|row| row.kind.len())
122        .max()
123        .unwrap_or(0)
124        .max("kind".len());
125    let name_width = rows
126        .iter()
127        .map(|row| row.name.len())
128        .max()
129        .unwrap_or(0)
130        .max("name".len());
131    let pins_width = rows
132        .iter()
133        .map(|row| row.pins.to_string().len())
134        .max()
135        .unwrap_or(0)
136        .max("pins".len());
137
138    let mut out = String::new();
139    if source {
140        let source_width = rows
141            .iter()
142            .map(|row| row.source.len())
143            .max()
144            .unwrap_or(0)
145            .max("source".len());
146        let _ = writeln!(
147            out,
148            "{:<id_width$}  {:<kind_width$}  {:<name_width$}  {:>pins_width$}  {:<source_width$}",
149            "id", "kind", "name", "pins", "source"
150        );
151        for row in rows {
152            let _ = writeln!(
153                out,
154                "{:<id_width$}  {:<kind_width$}  {:<name_width$}  {:>pins_width$}  {:<source_width$}",
155                row.id, row.kind, row.name, row.pins, row.source
156            );
157        }
158    } else {
159        let _ = writeln!(
160            out,
161            "{:<id_width$}  {:<kind_width$}  {:<name_width$}  {:>pins_width$}",
162            "id", "kind", "name", "pins"
163        );
164        for row in rows {
165            let _ = writeln!(
166                out,
167                "{:<id_width$}  {:<kind_width$}  {:<name_width$}  {:>pins_width$}",
168                row.id, row.kind, row.name, row.pins
169            );
170        }
171    }
172    out
173}
174
175/// The builtin catalog as a human table.
176pub fn builtin_table() -> String {
177    table(&rows(&Registry::builtin()), false)
178}
179
180/// The builtin catalog plus `dir/parts` and `dir/boards`, as rows.
181pub fn listing(dir: &Path) -> Result<Vec<Row>, String> {
182    Ok(rows(&load_project(dir)?))
183}
184
185/// Builtin entries first, then the project's manifests, which override an
186/// entry with the same id exactly as a run does.
187fn load_project(dir: &Path) -> Result<Registry, String> {
188    let mut registry = Registry::builtin();
189    for sub in ["parts", "boards"] {
190        let path = dir.join(sub);
191        if path.is_dir() {
192            registry.load_dir(&path).map_err(|e| e.to_string())?;
193        }
194    }
195    Ok(registry)
196}
197
198// ------------------------------------------------------------------ checking
199
200/// What `catalog check` found: how many manifests it read and one message per
201/// manifest that did not parse.
202#[derive(Debug, Default)]
203pub struct CheckReport {
204    pub checked: usize,
205    pub errors: Vec<String>,
206}
207
208/// Parse every manifest in `dir/parts` and `dir/boards`. A missing directory
209/// is not an error; it simply holds no manifests.
210pub fn check_dir(dir: &Path) -> CheckReport {
211    let mut report = CheckReport::default();
212    for sub in ["parts", "boards"] {
213        let files = match toml_files(&dir.join(sub)) {
214            Ok(files) => files,
215            Err(error) => {
216                report.errors.push(error);
217                continue;
218            }
219        };
220        for file in files {
221            report.checked += 1;
222            if let Err(error) = parse_file(&file) {
223                report.errors.push(error);
224            }
225        }
226    }
227    report
228}
229
230// ---------------------------------------------------------------- installing
231
232/// A bundle copied into a project's catalog directory.
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct Installed {
235    pub id: String,
236    /// The installed manifest, not the directory.
237    pub path: PathBuf,
238}
239
240/// Install `source` into `project/dir`.
241///
242/// The whole bundle is read and checked before the first byte is written, so a
243/// bad bundle leaves the destination untouched. A failed write rolls back the
244/// files this call created.
245pub fn add(source: &Path, project: &Path, dir: &str) -> Result<Installed, String> {
246    if !source.is_dir() {
247        return Err(format!("{}: not a directory", source.display()));
248    }
249    let manifest_path = bundle_manifest(source)?;
250    let manifest = parse_file(&manifest_path)?;
251    let id = manifest.id.clone();
252
253    if Registry::builtin().get(&id).is_some() {
254        return Err(format!(
255            "{id}: the id is already a builtin entry; rename it before installing"
256        ));
257    }
258
259    // A part is one file in `parts/`; a board is a directory of its own,
260    // because its module, schematic and source all belong together and two
261    // boards must not both land on `board.toml`.
262    let base = project.join(dir);
263    let destination = if manifest.board.is_some() {
264        base.join(&id)
265    } else {
266        base.clone()
267    };
268    for file in toml_files(&base)? {
269        let other = parse_file(&file)?;
270        if other.id == id {
271            return Err(format!(
272                "{id}: already installed in {}",
273                destination.display()
274            ));
275        }
276    }
277
278    let manifest_name = manifest_path
279        .file_name()
280        .ok_or_else(|| format!("{}: has no file name", manifest_path.display()))?;
281    let target_manifest = destination.join(manifest_name);
282    if target_manifest.exists() {
283        return Err(format!("{}: already exists", target_manifest.display()));
284    }
285
286    let mut files: Vec<(String, Vec<u8>)> = Vec::new();
287    for relative in referenced_files(&manifest) {
288        check_relative(&id, &relative)?;
289        let from = source.join(&relative);
290        let bytes = std::fs::read(&from).map_err(|e| {
291            format!(
292                "{}: references {relative:?}, which cannot be read: {e}",
293                manifest_path.display()
294            )
295        })?;
296        if !files.iter().any(|(name, _)| name == &relative) {
297            files.push((relative, bytes));
298        }
299    }
300    let manifest_bytes =
301        std::fs::read(&manifest_path).map_err(|e| format!("{}: {e}", manifest_path.display()))?;
302
303    std::fs::create_dir_all(&destination).map_err(|e| format!("{}: {e}", destination.display()))?;
304
305    let mut written: Vec<PathBuf> = Vec::new();
306    let result = (|| {
307        std::fs::write(&target_manifest, &manifest_bytes)
308            .map_err(|e| format!("{}: {e}", target_manifest.display()))?;
309        written.push(target_manifest.clone());
310        for (relative, bytes) in &files {
311            let to = destination.join(relative);
312            if let Some(parent) = to.parent() {
313                std::fs::create_dir_all(parent)
314                    .map_err(|e| format!("{}: {e}", parent.display()))?;
315            }
316            std::fs::write(&to, bytes).map_err(|e| format!("{}: {e}", to.display()))?;
317            written.push(to);
318        }
319        Ok(())
320    })();
321    if let Err(error) = result {
322        for path in written.iter().rev() {
323            let _ = std::fs::remove_file(path);
324        }
325        return Err(error);
326    }
327
328    Ok(Installed {
329        id,
330        path: target_manifest,
331    })
332}
333
334/// The bundle's one manifest: `part.toml` when present, otherwise the only
335/// `*.toml` in the directory.
336fn bundle_manifest(source: &Path) -> Result<PathBuf, String> {
337    let named = source.join("part.toml");
338    if named.is_file() {
339        return Ok(named);
340    }
341    let files = toml_files(source)?;
342    match files.as_slice() {
343        [] => Err(format!(
344            "{}: no part.toml and no *.toml manifest",
345            source.display()
346        )),
347        [only] => Ok(only.clone()),
348        many => Err(format!(
349            "{}: expected one manifest, found {}: {}",
350            source.display(),
351            many.len(),
352            many.iter()
353                .filter_map(|path| path.file_name())
354                .map(|name| name.to_string_lossy().into_owned())
355                .collect::<Vec<_>>()
356                .join(", ")
357        )),
358    }
359}
360
361/// Every file a manifest names relative to itself. A schematic a board ships
362/// is checked too; it is needed for the same reason a wasm module is.
363fn referenced_files(manifest: &PartManifest) -> Vec<String> {
364    let mut files = Vec::new();
365    if let Simulation::Wasm { module, .. } = &manifest.simulation {
366        files.push(module.clone());
367    }
368    if let Some(board) = &manifest.board {
369        if let Some(simulator) = &board.simulator {
370            files.push(simulator.module.clone());
371        }
372        if let Some(schematic) = &board.schematic {
373            files.push(schematic.clone());
374        }
375    }
376    files
377}
378
379/// The wasm modules a manifest names. These, and only these, may be removed
380/// with the manifest.
381fn referenced_modules(manifest: &PartManifest) -> Vec<String> {
382    let mut modules = Vec::new();
383    if let Simulation::Wasm { module, .. } = &manifest.simulation {
384        modules.push(module.clone());
385    }
386    if let Some(simulator) = manifest
387        .board
388        .as_ref()
389        .and_then(|board| board.simulator.as_ref())
390    {
391        modules.push(simulator.module.clone());
392    }
393    modules
394}
395
396/// A referenced file must be a plain relative path: no root and no `..`.
397fn check_relative(id: &str, path: &str) -> Result<(), String> {
398    if path.trim().is_empty()
399        || Path::new(path).is_absolute()
400        || !Path::new(path)
401            .components()
402            .all(|part| matches!(part, Component::Normal(_)))
403    {
404        return Err(format!(
405            "{id}: {path:?} must be relative to the manifest and stay inside its directory"
406        ));
407    }
408    Ok(())
409}
410
411// ---------------------------------------------------------------- scaffolding
412
413/// Write a starter manifest to `project/dir/<id>.toml`.
414///
415/// The scaffold declares two passive pins and leaves the backend commented:
416/// the generated file is valid TOML, but the author chooses the engine before
417/// the catalog can load it.
418pub fn new_part(
419    project: &Path,
420    dir: &str,
421    id: &str,
422    name: Option<&str>,
423) -> Result<PathBuf, String> {
424    validate_id(id)?;
425
426    let text = scaffold(id, name.unwrap_or(id));
427    toml::from_str::<toml::Value>(&text)
428        .map_err(|e| format!("generated manifest is invalid: {e}"))?;
429
430    let destination = project.join(dir);
431    std::fs::create_dir_all(&destination).map_err(|e| format!("{}: {e}", destination.display()))?;
432    let path = destination.join(format!("{id}.toml"));
433    if path.exists() {
434        return Err(format!("{}: already exists", path.display()));
435    }
436    std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
437    Ok(path)
438}
439
440fn scaffold(id: &str, name: &str) -> String {
441    format!(
442        r#"# Litz part manifest.
443#
444# Choose one simulation backend and uncomment it:
445#
446#   [simulation]
447#   backend = "builtin"
448#   engine = "led"
449#
450# or:
451#
452#   [simulation]
453#   backend = "wasm"
454#   module = "part.wasm"
455
456[part]
457id = "{id}"
458name = "{name}"
459version = "0.1.0"
460description = ""
461license = "MIT"
462
463[pins."1"]
464kind = "passive"
465number = 1
466
467[pins."2"]
468kind = "passive"
469number = 2
470"#,
471        name = escape(name)
472    )
473}
474
475/// Quote-safe text for the scaffold's one free-form field.
476fn escape(text: &str) -> String {
477    text.replace('\\', "\\\\")
478        .replace('"', "\\\"")
479        .replace('\n', "\\n")
480        .replace('\r', "\\r")
481}
482
483/// A catalog id is also a file and directory name, so it stays a plain name.
484fn validate_id(id: &str) -> Result<(), String> {
485    if id.is_empty()
486        || id.starts_with('.')
487        || !id
488            .chars()
489            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
490    {
491        return Err(format!(
492            "{id:?}: an id may contain only letters, digits, '-', '_' and '.'"
493        ));
494    }
495    Ok(())
496}
497
498// ------------------------------------------------------------ board scaffolding
499
500/// The files `new_board` writes live in `templates/board`, one template per
501/// file, so the repository documents the generated layout. `onboard.json` is
502/// renamed to `<id>.onboard.json` when written, because the manifest resolves
503/// the schematic by that name.
504const BOARD_MANIFEST: &str = include_str!("../templates/board/board.toml");
505const BOARD_SCHEMATIC: &str = include_str!("../templates/board/onboard.json");
506const SIMULATOR_MANIFEST: &str = include_str!("../templates/board/simulator/Cargo.toml.in");
507const SIMULATOR_SOURCE: &str = include_str!("../templates/board/simulator/src/lib.rs");
508const SIMULATOR_BUILD: &str = include_str!("../templates/board/simulator/build.sh");
509const BOARD_README: &str = include_str!("../templates/board/README.md");
510/// The contract copy placed next to `simulator/`. The test module keeps it
511/// byte-identical to `crates/litz-mcu-wit/wit-v2`.
512const BOARD_WIT: &str = include_str!("../templates/board/wit-v2/litz-mcu.wit");
513
514/// Every file of a board bundle, relative to the board directory.
515fn board_files(id: &str, name: &str) -> Vec<(String, String)> {
516    let krate = format!("{id}-sim");
517    let name = escape(name);
518    let render = |template: &str| {
519        template
520            .replace("{{id}}", id)
521            // Longer placeholder first; `{{crate}}` is not a prefix of it.
522            .replace("{{crate_snake}}", &krate.replace('-', "_"))
523            .replace("{{crate}}", &krate)
524            .replace("{{name}}", &name)
525    };
526    vec![
527        ("board.toml".into(), render(BOARD_MANIFEST)),
528        (format!("{id}.onboard.json"), render(BOARD_SCHEMATIC)),
529        ("simulator/Cargo.toml".into(), render(SIMULATOR_MANIFEST)),
530        ("simulator/src/lib.rs".into(), render(SIMULATOR_SOURCE)),
531        ("simulator/build.sh".into(), render(SIMULATOR_BUILD)),
532        ("wit-v2/litz-mcu.wit".into(), render(BOARD_WIT)),
533        ("README.md".into(), render(BOARD_README)),
534    ]
535}
536
537/// Write a starter board bundle to `project/dir/<id>/`.
538///
539/// Unlike [`new_part`], the result is a directory: a board is a manifest, an
540/// onboard schematic, a guest source tree and the WIT contract it builds
541/// against. `catalog add` reads the directory as one bundle and installs the
542/// manifest, schematic and built module.
543///
544/// The id is used as a catalog id, so `board-` is added when the caller did
545/// not write it. An existing non-empty directory is refused rather than
546/// merged.
547pub fn new_board(
548    project: &Path,
549    dir: &str,
550    id: &str,
551    name: Option<&str>,
552) -> Result<PathBuf, String> {
553    validate_id(id)?;
554    // The default name follows what the author typed, not the catalog prefix.
555    let name = name.unwrap_or(id);
556    let id = if id.starts_with("board-") {
557        id.to_string()
558    } else {
559        format!("board-{id}")
560    };
561
562    let destination = project.join(dir).join(&id);
563    if destination.exists() {
564        let empty = std::fs::read_dir(&destination)
565            .map(|mut entries| entries.next().is_none())
566            .unwrap_or(false);
567        if !empty {
568            return Err(format!("{}: already exists", destination.display()));
569        }
570    }
571
572    // Render and parse before touching the disk, so a bad template cannot
573    // leave a half-written board behind.
574    let files = board_files(&id, name);
575    let manifest = files
576        .iter()
577        .find(|(relative, _)| relative.as_str() == "board.toml")
578        .map(|(_, text)| text)
579        .expect("board_files always writes the manifest");
580    toml::from_str::<toml::Value>(manifest)
581        .map_err(|e| format!("generated board manifest is invalid: {e}"))?;
582
583    std::fs::create_dir_all(&destination).map_err(|e| format!("{}: {e}", destination.display()))?;
584    let result = (|| {
585        for (relative, text) in &files {
586            let path = destination.join(relative);
587            if let Some(parent) = path.parent() {
588                std::fs::create_dir_all(parent)
589                    .map_err(|e| format!("{}: {e}", parent.display()))?;
590            }
591            std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
592        }
593        Ok(())
594    })();
595    if let Err(error) = result {
596        let _ = std::fs::remove_dir_all(&destination);
597        return Err(error);
598    }
599    // The README runs the script directly; a plain write is not executable.
600    #[cfg(unix)]
601    {
602        use std::os::unix::fs::PermissionsExt;
603        let script = destination.join("simulator/build.sh");
604        if let Ok(metadata) = std::fs::metadata(&script) {
605            let mut permissions = metadata.permissions();
606            permissions.set_mode(permissions.mode() | 0o111);
607            let _ = std::fs::set_permissions(&script, permissions);
608        }
609    }
610    Ok(destination)
611}
612
613// ------------------------------------------------------------------ removing
614
615/// Remove an installed manifest and the wasm module it alone names.
616///
617/// A module another manifest in the same directory still names is kept. A
618/// builtin id is refused: the catalog ships it, and no project file owns it.
619pub fn remove(project: &Path, dir: &str, id: &str) -> Result<PathBuf, String> {
620    if Registry::builtin().get(id).is_some() {
621        return Err(format!("{id}: builtin entries cannot be removed"));
622    }
623
624    let destination = project.join(dir);
625    let mut found: Vec<(PathBuf, PartManifest)> = Vec::new();
626    for file in toml_files(&destination)? {
627        let manifest = parse_file(&file)?;
628        if manifest.id == id {
629            found.push((file, manifest));
630        }
631    }
632    let (manifest_path, manifest) = match found.len() {
633        0 => {
634            return Err(format!("{id}: not installed in {}", destination.display()));
635        }
636        1 => found.pop().expect("one entry"),
637        _ => {
638            return Err(format!(
639                "{id}: declared by more than one manifest in {}",
640                destination.display()
641            ));
642        }
643    };
644
645    // Module paths are relative to the manifest, which for a board is the
646    // board's own directory rather than `boards/` itself.
647    let base = manifest_path
648        .parent()
649        .map(Path::to_path_buf)
650        .unwrap_or_else(|| destination.clone());
651    let modules: Vec<PathBuf> = referenced_modules(&manifest)
652        .into_iter()
653        .map(|module| base.join(module))
654        .collect();
655    let mut shared = BTreeSet::new();
656    for file in toml_files(&destination)? {
657        if file == manifest_path {
658            continue;
659        }
660        let owner = file.parent().map(Path::to_path_buf).unwrap_or_default();
661        for module in referenced_modules(&parse_file(&file)?) {
662            shared.insert(owner.join(module));
663        }
664    }
665
666    std::fs::remove_file(&manifest_path)
667        .map_err(|e| format!("{}: {e}", manifest_path.display()))?;
668    for path in modules {
669        if shared.contains(&path) {
670            continue;
671        }
672        if path.is_file() {
673            std::fs::remove_file(&path).map_err(|e| format!("{}: {e}", path.display()))?;
674        }
675    }
676    // A board's own schematic is not shared with any other manifest.
677    if let Some(schematic) = manifest
678        .board
679        .as_ref()
680        .and_then(|board| board.schematic.as_ref())
681    {
682        let path = base.join(schematic);
683        if path.is_file() {
684            std::fs::remove_file(&path).map_err(|e| format!("{}: {e}", path.display()))?;
685        }
686    }
687    // A board lives in its own directory. Once its files are gone the empty
688    // directory is noise; one that still holds the author's simulator source
689    // is left alone.
690    if base != destination && std::fs::read_dir(&base).is_ok_and(|mut d| d.next().is_none()) {
691        let _ = std::fs::remove_dir(&base);
692    }
693    Ok(manifest_path)
694}
695
696// -------------------------------------------------------------- file helpers
697
698/// Every `*.toml` in `dir`, sorted. A missing directory is empty, not an
699/// error.
700fn toml_files(dir: &Path) -> Result<Vec<PathBuf>, String> {
701    let entries = match std::fs::read_dir(dir) {
702        Ok(entries) => entries,
703        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
704        Err(error) => return Err(format!("{}: {error}", dir.display())),
705    };
706    let mut files = Vec::new();
707    for entry in entries {
708        let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?;
709        let path = entry.path();
710        if path.is_dir() {
711            // A board bundle is `boards/<id>/board.toml`; its simulator
712            // crate's `Cargo.toml` is not a manifest.
713            if let Ok(children) = std::fs::read_dir(&path) {
714                for child in children {
715                    let child = child.map_err(|e| format!("{}: {e}", path.display()))?;
716                    let candidate = child.path();
717                    if candidate.extension().is_some_and(|ext| ext == "toml")
718                        && candidate
719                            .file_name()
720                            .is_none_or(|name| name != "Cargo.toml")
721                    {
722                        files.push(candidate);
723                    }
724                }
725            }
726        } else if path
727            .extension()
728            .is_some_and(|extension| extension == "toml")
729        {
730            files.push(path);
731        }
732    }
733    files.sort();
734    Ok(files)
735}
736
737fn parse_file(path: &Path) -> Result<PartManifest, String> {
738    let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
739    parse_text(&text).map_err(|e| format!("{}: {e}", path.display()))
740}
741
742fn parse_text(text: &str) -> Result<PartManifest, String> {
743    let mut registry = Registry::new();
744    let id = registry.insert_text(text)?;
745    registry
746        .get(&id)
747        .cloned()
748        .ok_or_else(|| format!("{id}: missing after parsing"))
749}
750
751#[cfg(test)]
752mod tests {
753    use super::*;
754
755    fn field<'a>(entry: &'a Value, name: &str) -> &'a Value {
756        entry
757            .get(name)
758            .unwrap_or_else(|| panic!("catalog entry has no {name:?}: {entry}"))
759    }
760
761    #[test]
762    fn catalog_json_names_every_builtin_entry_once() {
763        let registry = Registry::builtin();
764        let catalog = value(&registry);
765        let entries = catalog.as_array().expect("the catalog is an array");
766        assert_eq!(entries.len(), registry.ids().count());
767
768        let mut ids: Vec<&str> = entries
769            .iter()
770            .map(|entry| field(entry, "id").as_str().expect("id is a string"))
771            .collect();
772        let sorted = ids.clone();
773        ids.sort_unstable();
774        assert_eq!(ids, sorted, "entries are ordered by id");
775        let unique: std::collections::BTreeSet<_> = ids.iter().copied().collect();
776        assert_eq!(unique.len(), ids.len(), "an id appears once");
777    }
778
779    #[test]
780    fn catalog_entries_have_the_front_end_shape() {
781        let catalog = value(&Registry::builtin());
782        let entries = catalog.as_array().unwrap();
783
784        for entry in entries {
785            let object = entry.as_object().expect("an entry is an object");
786            let keys: std::collections::BTreeSet<&str> =
787                object.keys().map(String::as_str).collect();
788            assert_eq!(
789                keys,
790                ["id", "kind", "name", "description", "pins", "attrs"]
791                    .into_iter()
792                    .collect::<std::collections::BTreeSet<_>>(),
793                "unexpected keys on {entry}"
794            );
795            assert!(matches!(
796                field(entry, "kind").as_str(),
797                Some("part" | "board")
798            ));
799            assert!(field(entry, "name").is_string());
800            assert!(field(entry, "description").is_string());
801
802            let pins = field(entry, "pins").as_array().expect("pins is an array");
803            for pin in pins {
804                let keys: std::collections::BTreeSet<&str> = pin
805                    .as_object()
806                    .unwrap()
807                    .keys()
808                    .map(String::as_str)
809                    .collect();
810                assert_eq!(keys, ["name", "kind"].into_iter().collect());
811                assert!(pin["name"].is_string());
812                assert!(pin["kind"].is_string());
813            }
814
815            let attrs = field(entry, "attrs").as_array().expect("attrs is an array");
816            for attr in attrs {
817                let keys: std::collections::BTreeSet<&str> = attr
818                    .as_object()
819                    .unwrap()
820                    .keys()
821                    .map(String::as_str)
822                    .collect();
823                assert_eq!(
824                    keys,
825                    ["name", "type", "values", "default"].into_iter().collect()
826                );
827                assert!(attr["name"].is_string());
828                assert!(attr["type"].is_string());
829                assert!(attr["values"].is_array());
830            }
831        }
832    }
833
834    #[test]
835    fn a_part_and_a_board_describe_themselves() {
836        let catalog = value(&Registry::builtin());
837        let entries = catalog.as_array().unwrap();
838
839        let led = entries
840            .iter()
841            .find(|entry| entry["id"] == "litz-led")
842            .expect("litz-led");
843        assert_eq!(led["kind"], "part");
844        assert_eq!(led["name"], "LED");
845        let pins = led["pins"].as_array().unwrap();
846        assert!(
847            pins.iter()
848                .any(|pin| pin["name"] == "A" && pin["kind"] == "digital-in")
849        );
850        assert!(
851            pins.iter()
852                .any(|pin| pin["name"] == "C" && pin["kind"] == "ground")
853        );
854        let color = led["attrs"]
855            .as_array()
856            .unwrap()
857            .iter()
858            .find(|attr| attr["name"] == "color")
859            .expect("LED has a colour");
860        assert_eq!(color["type"], "enum");
861        assert_eq!(color["default"], "red");
862        assert!(
863            color["values"]
864                .as_array()
865                .unwrap()
866                .iter()
867                .any(|value| value == "green")
868        );
869
870        let board = entries
871            .iter()
872            .find(|entry| entry["id"] == "board-esp32-c3-devkitm-1")
873            .expect("the ESP32-C3 board");
874        assert_eq!(board["kind"], "board");
875        let pins = board["pins"].as_array().unwrap();
876        assert!(
877            pins.iter()
878                .any(|pin| pin["name"] == "GPIO8" && pin["kind"] == "digital-io")
879        );
880        assert!(
881            pins.iter()
882                .any(|pin| pin["name"] == "GND" && pin["kind"] == "ground")
883        );
884    }
885
886    #[test]
887    fn the_text_form_is_valid_json() {
888        let text = builtin_json();
889        let parsed: Value = serde_json::from_str(&text).expect("the command prints JSON");
890        assert_eq!(
891            parsed.as_array().unwrap().len(),
892            Registry::builtin().ids().count()
893        );
894    }
895
896    // ------------------------------------------------------------ scratch dirs
897
898    struct TempDir(PathBuf);
899
900    impl TempDir {
901        fn new(tag: &str) -> Self {
902            use std::sync::atomic::{AtomicUsize, Ordering};
903            static NEXT: AtomicUsize = AtomicUsize::new(0);
904            let n = NEXT.fetch_add(1, Ordering::Relaxed);
905            let path =
906                std::env::temp_dir().join(format!("litz-catalog-{tag}-{}-{n}", std::process::id()));
907            let _ = std::fs::remove_dir_all(&path);
908            std::fs::create_dir_all(&path).expect("create the scratch directory");
909            Self(path)
910        }
911
912        fn path(&self) -> &Path {
913            &self.0
914        }
915    }
916
917    impl Drop for TempDir {
918        fn drop(&mut self) {
919            let _ = std::fs::remove_dir_all(&self.0);
920        }
921    }
922
923    fn part_text(id: &str, name: &str) -> String {
924        format!(
925            r#"
926[part]
927id = "{id}"
928name = "{name}"
929version = "0.1.0"
930[pins.P]
931kind = "passive"
932[simulation]
933backend = "builtin"
934engine = "x"
935"#
936        )
937    }
938
939    fn board_text(id: &str, name: &str) -> String {
940        format!(
941            r#"
942[board]
943id = "{id}"
944name = "{name}"
945chip = "esp32c3"
946[[pins]]
947name = "GPIO0"
948gpio = 0
949"#
950        )
951    }
952
953    fn wasm_part_text(id: &str, module: &str) -> String {
954        format!(
955            r#"
956[part]
957id = "{id}"
958name = "Mirror"
959version = "1.0.0"
960[pins.IN]
961kind = "digital-in"
962[pins.OUT]
963kind = "digital-out"
964[simulation]
965backend = "wasm"
966module = "{module}"
967"#
968        )
969    }
970
971    fn row<'a>(rows: &'a [Row], id: &str) -> &'a Row {
972        rows.iter()
973            .find(|row| row.id == id)
974            .unwrap_or_else(|| panic!("{id} is missing from the listing"))
975    }
976
977    // ------------------------------------------------------------------ tables
978
979    #[test]
980    fn the_human_table_lists_every_builtin_entry() {
981        let text = builtin_table();
982        let lines: Vec<&str> = text.lines().collect();
983        assert_eq!(
984            lines.len(),
985            Registry::builtin().ids().count() + 1,
986            "one header and one row per entry"
987        );
988        assert!(lines[0].starts_with("id"), "{}", lines[0]);
989        assert!(lines[0].contains("kind"), "{}", lines[0]);
990        assert!(lines[0].contains("name"), "{}", lines[0]);
991        assert!(lines[0].contains("pins"), "{}", lines[0]);
992        let led = lines
993            .iter()
994            .find(|line| line.starts_with("litz-led "))
995            .expect("litz-led is listed");
996        assert!(led.contains("part"), "{led}");
997        assert!(led.ends_with('2'), "the LED has two pins: {led}");
998        assert!(
999            !lines[0].contains("source"),
1000            "the plain catalog has no source column"
1001        );
1002    }
1003
1004    #[test]
1005    fn listing_marks_builtin_parts_and_boards() {
1006        let dir = TempDir::new("listing");
1007        std::fs::create_dir_all(dir.path().join("parts")).unwrap();
1008        std::fs::write(
1009            dir.path().join("parts/vendor-thing.toml"),
1010            part_text("vendor-thing", "Vendor Thing"),
1011        )
1012        .unwrap();
1013        std::fs::create_dir_all(dir.path().join("boards")).unwrap();
1014        std::fs::write(
1015            dir.path().join("boards/board-vendor.toml"),
1016            board_text("board-vendor", "Vendor Board"),
1017        )
1018        .unwrap();
1019
1020        let rows = listing(dir.path()).expect("the project lists");
1021        assert_eq!(row(&rows, "litz-led").source, "builtin");
1022        let part = row(&rows, "vendor-thing");
1023        assert_eq!(part.source, "parts/");
1024        assert_eq!(part.kind, "part");
1025        assert_eq!(part.name, "Vendor Thing");
1026        assert_eq!(part.pins, 1);
1027        let board = row(&rows, "board-vendor");
1028        assert_eq!(board.source, "boards/");
1029        assert_eq!(board.kind, "board");
1030
1031        let ids: Vec<&str> = rows.iter().map(|row| row.id.as_str()).collect();
1032        let mut sorted = ids.clone();
1033        sorted.sort_unstable();
1034        assert_eq!(ids, sorted, "rows are ordered by id");
1035
1036        let table = table(&rows, true);
1037        assert!(table.lines().next().unwrap().contains("source"));
1038        assert!(table.contains("vendor-thing"), "{table}");
1039    }
1040
1041    // ------------------------------------------------------------------ checks
1042
1043    #[test]
1044    fn check_counts_manifests_and_names_the_bad_file() {
1045        let dir = TempDir::new("check");
1046        std::fs::create_dir_all(dir.path().join("parts")).unwrap();
1047        std::fs::write(
1048            dir.path().join("parts/good.toml"),
1049            part_text("good", "Good"),
1050        )
1051        .unwrap();
1052        std::fs::write(
1053            dir.path().join("parts/bad.toml"),
1054            "[part]\nid = \"bad\"\nname = \"Bad\"\n",
1055        )
1056        .unwrap();
1057
1058        let report = check_dir(dir.path());
1059        assert_eq!(report.checked, 2);
1060        assert_eq!(report.errors.len(), 1, "{:?}", report.errors);
1061        assert!(report.errors[0].contains("bad.toml"), "{:?}", report.errors);
1062        assert!(
1063            report.errors[0].contains("version"),
1064            "the parse error explains itself: {:?}",
1065            report.errors
1066        );
1067    }
1068
1069    #[test]
1070    fn check_of_a_missing_project_is_empty() {
1071        let dir = TempDir::new("check-empty");
1072        let report = check_dir(dir.path());
1073        assert_eq!(report.checked, 0);
1074        assert!(report.errors.is_empty(), "{:?}", report.errors);
1075    }
1076
1077    // -------------------------------------------------------------------- add
1078
1079    fn write_bundle(dir: &Path, id: &str, module: &str, with_module: bool) {
1080        std::fs::create_dir_all(dir).unwrap();
1081        std::fs::write(dir.join("part.toml"), wasm_part_text(id, module)).unwrap();
1082        if with_module {
1083            std::fs::write(dir.join(module), b"\0asm").unwrap();
1084        }
1085    }
1086
1087    #[test]
1088    fn add_copies_the_manifest_and_its_module() {
1089        let scratch = TempDir::new("add");
1090        let bundle = scratch.path().join("bundle");
1091        let project = scratch.path().join("project");
1092        write_bundle(&bundle, "vendor-mirror", "mirror.wasm", true);
1093
1094        let installed = add(&bundle, &project, "parts").expect("the bundle installs");
1095        assert_eq!(installed.id, "vendor-mirror");
1096        assert_eq!(installed.path, project.join("parts/part.toml"));
1097        assert!(installed.path.is_file());
1098        assert!(project.join("parts/mirror.wasm").is_file());
1099
1100        let rows = listing(&project).expect("the project lists");
1101        let added = row(&rows, "vendor-mirror");
1102        assert_eq!(added.source, "parts/");
1103    }
1104
1105    #[test]
1106    fn add_refuses_a_builtin_id() {
1107        let scratch = TempDir::new("add-builtin");
1108        let bundle = scratch.path().join("bundle");
1109        write_bundle(&bundle, "litz-led", "mirror.wasm", true);
1110
1111        let error = add(&bundle, &scratch.path().join("project"), "parts").unwrap_err();
1112        assert!(error.contains("builtin"), "{error}");
1113        assert!(!scratch.path().join("project/parts").exists());
1114    }
1115
1116    #[test]
1117    fn add_refuses_a_second_install_of_the_same_id() {
1118        let scratch = TempDir::new("add-twice");
1119        let bundle = scratch.path().join("bundle");
1120        let project = scratch.path().join("project");
1121        write_bundle(&bundle, "vendor-mirror", "mirror.wasm", true);
1122
1123        add(&bundle, &project, "parts").expect("the first install works");
1124        let error = add(&bundle, &project, "parts").unwrap_err();
1125        assert!(error.contains("already installed"), "{error}");
1126    }
1127
1128    #[test]
1129    fn add_refuses_a_missing_module_without_copying_anything() {
1130        let scratch = TempDir::new("add-missing");
1131        let bundle = scratch.path().join("bundle");
1132        let project = scratch.path().join("project");
1133        write_bundle(&bundle, "vendor-mirror", "mirror.wasm", false);
1134
1135        let error = add(&bundle, &project, "parts").unwrap_err();
1136        assert!(error.contains("mirror.wasm"), "{error}");
1137        assert!(!project.join("parts").exists(), "nothing was written");
1138    }
1139
1140    #[test]
1141    fn add_refuses_a_module_outside_the_bundle() {
1142        let scratch = TempDir::new("add-escape");
1143        let bundle = scratch.path().join("bundle");
1144        write_bundle(&bundle, "vendor-mirror", "../evil.wasm", true);
1145
1146        let error = add(&bundle, &scratch.path().join("project"), "parts").unwrap_err();
1147        assert!(error.contains("relative"), "{error}");
1148        assert!(error.contains("evil.wasm"), "{error}");
1149    }
1150
1151    // -------------------------------------------------------------------- new
1152
1153    #[test]
1154    fn new_writes_a_parseable_manifest_and_refuses_to_overwrite() {
1155        let scratch = TempDir::new("new");
1156        let path = new_part(
1157            scratch.path(),
1158            "parts",
1159            "vendor-switch",
1160            Some("Vendor Switch"),
1161        )
1162        .expect("the scaffold is written");
1163        assert_eq!(path, scratch.path().join("parts/vendor-switch.toml"));
1164
1165        let text = std::fs::read_to_string(&path).unwrap();
1166        toml::from_str::<toml::Value>(&text).expect("the scaffold is valid TOML");
1167        assert!(text.contains("id = \"vendor-switch\""), "{text}");
1168        assert!(text.contains("name = \"Vendor Switch\""), "{text}");
1169        assert!(text.contains("[pins.\"1\"]"), "{text}");
1170        assert!(text.contains("[pins.\"2\"]"), "{text}");
1171        assert!(
1172            !text
1173                .lines()
1174                .any(|line| !line.trim_start().starts_with('#') && line.contains("backend")),
1175            "the backend is left for the author: {text}"
1176        );
1177
1178        let error = new_part(scratch.path(), "parts", "vendor-switch", None).unwrap_err();
1179        assert!(error.contains("already exists"), "{error}");
1180    }
1181
1182    #[test]
1183    fn new_refuses_an_id_that_is_not_a_plain_name() {
1184        let scratch = TempDir::new("new-id");
1185        for id in ["", ".hidden", "../escape", "two words", "a/b"] {
1186            let error = new_part(scratch.path(), "parts", id, None).unwrap_err();
1187            assert!(error.contains("may contain only"), "{id:?}: {error}");
1188        }
1189    }
1190
1191    // -------------------------------------------------------------- new board
1192
1193    #[test]
1194    fn new_board_writes_a_buildable_bundle_and_refuses_to_overwrite() {
1195        let scratch = TempDir::new("new-board");
1196        let path = new_board(scratch.path(), "boards", "vendor-mcu", Some("Vendor MCU"))
1197            .expect("the board scaffold is written");
1198
1199        let board = scratch.path().join("boards/board-vendor-mcu");
1200        assert_eq!(path, board);
1201        for relative in [
1202            "board.toml",
1203            "board-vendor-mcu.onboard.json",
1204            "simulator/Cargo.toml",
1205            "simulator/src/lib.rs",
1206            "simulator/build.sh",
1207            "wit-v2/litz-mcu.wit",
1208            "README.md",
1209        ] {
1210            assert!(board.join(relative).is_file(), "{relative} is missing");
1211        }
1212
1213        let text = std::fs::read_to_string(board.join("board.toml")).unwrap();
1214        let manifest = parse_text(&text).expect("the generated manifest parses");
1215        assert_eq!(manifest.id, "board-vendor-mcu");
1216        assert_eq!(manifest.name, "Vendor MCU");
1217        let info = manifest.board.as_ref().expect("a board");
1218        assert_eq!(
1219            info.schematic.as_deref(),
1220            Some("board-vendor-mcu.onboard.json")
1221        );
1222        let simulator = info.simulator.as_ref().expect("a wasm MCU");
1223        assert_eq!(simulator.abi, "litz-mcu-2");
1224        assert_eq!(simulator.module, "board-vendor-mcu.wasm");
1225
1226        // The Cargo package and the core module derive from the same id.
1227        let cargo = std::fs::read_to_string(board.join("simulator/Cargo.toml")).unwrap();
1228        assert!(cargo.contains("name = \"board-vendor-mcu-sim\""), "{cargo}");
1229        let build = std::fs::read_to_string(board.join("simulator/build.sh")).unwrap();
1230        assert!(
1231            build.contains("board_vendor_mcu_sim.wasm"),
1232            "the cargo target name is snake_case: {build}"
1233        );
1234        assert!(
1235            build.contains("../board-vendor-mcu.wasm"),
1236            "the component is written next to the manifest: {build}"
1237        );
1238
1239        let error = new_board(scratch.path(), "boards", "vendor-mcu", None).unwrap_err();
1240        assert!(error.contains("already exists"), "{error}");
1241    }
1242
1243    #[test]
1244    fn new_board_keeps_an_existing_prefix_and_validates_the_id() {
1245        let scratch = TempDir::new("new-board-id");
1246        let path = new_board(scratch.path(), "boards", "board-already", None)
1247            .expect("the scaffold is written");
1248        assert_eq!(path, scratch.path().join("boards/board-already"));
1249        assert!(path.join("board-already.onboard.json").is_file());
1250        assert!(
1251            !scratch.path().join("boards/board-board-already").exists(),
1252            "an id that already names a board is not prefixed twice"
1253        );
1254
1255        for id in ["", ".hidden", "../escape", "two words", "a/b"] {
1256            let error = new_board(scratch.path(), "boards", id, None).unwrap_err();
1257            assert!(error.contains("may contain only"), "{id:?}: {error}");
1258        }
1259    }
1260
1261    #[test]
1262    fn the_board_templates_are_the_source_of_every_generated_file() {
1263        // The copy of the contract in templates/board must not drift from the
1264        // one the host is built against.
1265        assert_eq!(
1266            BOARD_WIT,
1267            include_str!("../../litz-mcu-wit/wit-v2/litz-mcu.wit"),
1268            "templates/board/wit-v2 must mirror crates/litz-mcu-wit/wit-v2"
1269        );
1270
1271        let scratch = TempDir::new("new-board-template");
1272        let path = new_board(scratch.path(), "boards", "example", Some("Example")).unwrap();
1273        let render = |template: &str| {
1274            template
1275                .replace("{{id}}", "board-example")
1276                .replace("{{crate_snake}}", "board_example_sim")
1277                .replace("{{crate}}", "board-example-sim")
1278                .replace("{{name}}", "Example")
1279        };
1280        for (relative, template) in [
1281            ("board.toml", BOARD_MANIFEST),
1282            ("board-example.onboard.json", BOARD_SCHEMATIC),
1283            ("simulator/Cargo.toml", SIMULATOR_MANIFEST),
1284            ("simulator/src/lib.rs", SIMULATOR_SOURCE),
1285            ("simulator/build.sh", SIMULATOR_BUILD),
1286            ("wit-v2/litz-mcu.wit", BOARD_WIT),
1287            ("README.md", BOARD_README),
1288        ] {
1289            let written = std::fs::read_to_string(path.join(relative)).unwrap();
1290            assert_eq!(written, render(template), "{relative} is not its template");
1291        }
1292    }
1293
1294    // ----------------------------------------------------------------- remove
1295
1296    #[test]
1297    fn remove_deletes_the_manifest_and_its_own_module() {
1298        let scratch = TempDir::new("remove");
1299        let bundle = scratch.path().join("bundle");
1300        let project = scratch.path().join("project");
1301        write_bundle(&bundle, "vendor-mirror", "mirror.wasm", true);
1302        add(&bundle, &project, "parts").expect("install");
1303
1304        let removed = remove(&project, "parts", "vendor-mirror").expect("remove");
1305        assert_eq!(removed, project.join("parts/part.toml"));
1306        assert!(!removed.exists());
1307        assert!(
1308            !project.join("parts/mirror.wasm").exists(),
1309            "the module went with its only manifest"
1310        );
1311    }
1312
1313    #[test]
1314    fn remove_keeps_a_module_another_manifest_uses() {
1315        let scratch = TempDir::new("remove-shared");
1316        let project = scratch.path().join("project");
1317        let parts = project.join("parts");
1318        std::fs::create_dir_all(&parts).unwrap();
1319        std::fs::write(
1320            parts.join("a.toml"),
1321            wasm_part_text("vendor-a", "shared.wasm"),
1322        )
1323        .unwrap();
1324        std::fs::write(
1325            parts.join("b.toml"),
1326            wasm_part_text("vendor-b", "shared.wasm"),
1327        )
1328        .unwrap();
1329        std::fs::write(parts.join("shared.wasm"), b"\0asm").unwrap();
1330
1331        remove(&project, "parts", "vendor-a").expect("remove a");
1332        assert!(!parts.join("a.toml").exists());
1333        assert!(parts.join("shared.wasm").is_file(), "b still names it");
1334
1335        remove(&project, "parts", "vendor-b").expect("remove b");
1336        assert!(!parts.join("shared.wasm").exists());
1337    }
1338
1339    #[test]
1340    fn remove_refuses_a_builtin_id() {
1341        let scratch = TempDir::new("remove-builtin");
1342        let error = remove(scratch.path(), "parts", "litz-led").unwrap_err();
1343        assert!(error.contains("builtin"), "{error}");
1344    }
1345
1346    #[test]
1347    fn remove_refuses_an_id_the_project_does_not_have() {
1348        let scratch = TempDir::new("remove-missing");
1349        std::fs::create_dir_all(scratch.path().join("parts")).unwrap();
1350        let error = remove(scratch.path(), "parts", "vendor-nothing").unwrap_err();
1351        assert!(error.contains("not installed"), "{error}");
1352    }
1353}