nanoflash 0.1.2

Lay out the flash of ESP32 and Arduino boards and write firmware to them through their bootloaders, natively or in the browser over Web Serial.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! The board of a Cargo package, named in `[package.metadata.nanoflash]` of its `Cargo.toml`.
//!
//! ```toml
//! [package.metadata.nanoflash]
//! board = "boards/board.toml"
//! board-identifier = "nano33ble"
//! ```
//!
//! `board` is the path of a board manifest, relative to the directory of `Cargo.toml`.
//! `board-identifier` names one board of that manifest. No other key is accepted.
//!
//! Only the `Cargo.toml` that [`package_manifest`] finds is read. A `Cargo.toml` without
//! `[package]` (a virtual workspace) or without the table names no board. No workspace level
//! table is read.

use crate::manifest::Manifest;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;
use std::ffi::OsString;
use std::path::{Path, PathBuf};

/// The file that describes a package.
const MANIFEST: &str = "Cargo.toml";

/// The board that the metadata of a package names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackageBoard {
    /// The `Cargo.toml` that holds the metadata.
    pub cargo_toml: PathBuf,
    /// The board manifest, joined to the directory of `cargo_toml`.
    pub board: PathBuf,
    /// The board of the manifest to use, when the metadata names one.
    pub board_identifier: Option<String>,
}

/// Why the metadata of a package could not be read.
#[derive(Debug)]
pub enum PackageError {
    /// The `Cargo.toml` could not be read.
    Io {
        /// The `Cargo.toml`.
        path: PathBuf,
        /// What the system said.
        error: std::io::Error,
    },
    /// The `Cargo.toml` is not valid TOML, or its metadata is wrong.
    Parse {
        /// The `Cargo.toml`.
        path: PathBuf,
        /// What is wrong.
        message: String,
    },
}

impl fmt::Display for PackageError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PackageError::Io { path, error } => {
                write!(formatter, "cannot read {}: {error}", path.display())
            }
            PackageError::Parse { path, message } => {
                write!(formatter, "{}: {message}", path.display())
            }
        }
    }
}

impl std::error::Error for PackageError {}

/// The `Cargo.toml` that Cargo names in the variables of `variable`.
pub fn manifest_from(variable: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
    let named = |name: &str| variable(name).filter(|value| !value.is_empty());
    named("CARGO_MANIFEST_PATH").map(PathBuf::from).or_else(|| {
        named("CARGO_MANIFEST_DIR").map(|directory| Path::new(&directory).join(MANIFEST))
    })
}

/// The `Cargo.toml` that Cargo names in the environment of this process.
pub fn manifest_from_environment() -> Option<PathBuf> {
    manifest_from(|name| std::env::var_os(name))
}

/// The nearest `Cargo.toml`: in `start`, or else in the nearest ancestor that has one.
///
/// A relative `start` is resolved first (`.` and `..` included), so the walk goes above the
/// working directory, and the result is an absolute path. An absolute `start` is walked as it is
/// written.
pub fn find_manifest(start: &Path) -> Option<PathBuf> {
    let resolved;
    let start = if start.is_relative() {
        resolved = std::fs::canonicalize(start)
            .or_else(|_| std::path::absolute(start))
            .unwrap_or_else(|_| start.to_path_buf());
        resolved.as_path()
    } else {
        start
    };
    start
        .ancestors()
        .map(|directory| directory.join(MANIFEST))
        .find(|candidate| candidate.is_file())
}

/// The `Cargo.toml` of the package: the one Cargo names in the environment, or else the nearest
/// one from `start`.
pub fn package_manifest(start: &Path) -> Option<PathBuf> {
    manifest_from_environment().or_else(|| find_manifest(start))
}

/// The directory of the workspace root of the package whose `Cargo.toml` is `cargo_toml`, found as
/// Cargo finds it:
///
/// - the directory of `cargo_toml` itself when the file has a `[workspace]` table;
/// - else the directory that `package.workspace` names, relative to `cargo_toml`;
/// - else the nearest ancestor directory whose `Cargo.toml` has a `[workspace]` table.
///
/// Returns `None` when the package is in no workspace, and when `cargo_toml` cannot be read. An
/// ancestor `Cargo.toml` that cannot be read or parsed is skipped. The members of the workspace
/// are not checked: Cargo itself refuses a package that its workspace does not list.
pub fn workspace_root(cargo_toml: &Path) -> Option<PathBuf> {
    let directory = cargo_toml.parent().unwrap_or_else(|| Path::new(""));
    let document = read_table(cargo_toml)?;
    if document.contains_key("workspace") {
        return Some(directory.to_path_buf());
    }
    let named = document
        .get("package")
        .and_then(toml::Value::as_table)
        .and_then(|package| package.get("workspace"))
        .and_then(toml::Value::as_str);
    if let Some(root) = named {
        return Some(directory.join(root));
    }
    directory
        .ancestors()
        .skip(1)
        .find(|candidate| {
            read_table(&candidate.join(MANIFEST))
                .is_some_and(|table| table.contains_key("workspace"))
        })
        .map(Path::to_path_buf)
}

/// The top level table of a `Cargo.toml`, or `None` when it cannot be read or parsed.
fn read_table(cargo_toml: &Path) -> Option<toml::Table> {
    let text = std::fs::read_to_string(cargo_toml).ok()?;
    toml::from_str(&text).ok()
}

/// Read the board of the package whose `Cargo.toml` is `cargo_toml`.
///
/// Returns `None` when the file has no `[package]` or no `[package.metadata.nanoflash]`.
pub fn read_board(cargo_toml: &Path) -> Result<Option<PackageBoard>, PackageError> {
    let text = std::fs::read_to_string(cargo_toml).map_err(|error| PackageError::Io {
        path: cargo_toml.to_path_buf(),
        error,
    })?;
    let parse_error = |message: String| PackageError::Parse {
        path: cargo_toml.to_path_buf(),
        message,
    };
    let document: toml::Table =
        toml::from_str(&text).map_err(|error| parse_error(error.to_string()))?;
    let Some(table) = document
        .get("package")
        .and_then(toml::Value::as_table)
        .and_then(|package| package.get("metadata"))
        .and_then(toml::Value::as_table)
        .and_then(|metadata| metadata.get("nanoflash"))
    else {
        return Ok(None);
    };
    let Some(table) = table.as_table() else {
        return Err(parse_error(String::from(
            "[package.metadata.nanoflash] must be a table with the key \"board\"",
        )));
    };
    if let Some(key) = table
        .keys()
        .find(|key| !matches!(key.as_str(), "board" | "board-identifier"))
    {
        return Err(parse_error(alloc::format!(
            "[package.metadata.nanoflash] has an unknown key \"{key}\": it takes \"board\" and \"board-identifier\""
        )));
    }
    let Some(board) = table.get("board").and_then(toml::Value::as_str) else {
        return Err(parse_error(String::from(
            "[package.metadata.nanoflash] needs \"board\", the path of the board manifest relative to Cargo.toml",
        )));
    };
    let board_identifier = match table.get("board-identifier") {
        None => None,
        Some(toml::Value::String(identifier)) => Some(identifier.clone()),
        Some(_) => {
            return Err(parse_error(String::from(
                "[package.metadata.nanoflash] has a \"board-identifier\" that is not text",
            )));
        }
    };
    let directory = cargo_toml.parent().unwrap_or_else(|| Path::new(""));
    Ok(Some(PackageBoard {
        cargo_toml: cargo_toml.to_path_buf(),
        board: directory.join(board),
        board_identifier,
    }))
}

/// The layout file of a board of `manifest`, as the manifest writes it.
///
/// Without `identifier`, every board of the manifest must use the same layout.
pub fn layout_of(manifest: &Manifest, identifier: Option<&str>) -> Result<String, String> {
    let boards = &manifest.boards;
    let quoted = |names: &mut dyn Iterator<Item = &str>| {
        names
            .map(|name| alloc::format!("\"{name}\""))
            .collect::<Vec<_>>()
            .join(", ")
    };
    let identifiers = || boards.iter().map(|board| board.identifier.as_str());
    if let Some(identifier) = identifier {
        let board = boards
            .iter()
            .find(|board| board.identifier == identifier)
            .ok_or_else(|| {
                alloc::format!(
                    "the manifest has no board \"{identifier}\"; it lists {}",
                    quoted(&mut identifiers())
                )
            })?;
        return board
            .layout
            .clone()
            .ok_or_else(|| alloc::format!("the board \"{identifier}\" has no layout"));
    }
    let Some(first) = boards.first() else {
        return Err(String::from("the manifest has no board"));
    };
    if boards.iter().any(|board| board.layout != first.layout) {
        return Err(alloc::format!(
            "the boards of the manifest ({}) use different layouts: name one with board-identifier",
            quoted(&mut identifiers())
        ));
    }
    match &first.layout {
        Some(layout) => Ok(layout.clone()),
        None if boards.len() == 1 => Err(alloc::format!(
            "the board \"{}\" has no layout",
            first.identifier
        )),
        None => Err(alloc::format!(
            "the boards of the manifest ({}) have no layout",
            quoted(&mut identifiers())
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    /// A directory for one test, removed when the test ends.
    struct Scratch(PathBuf);

    impl core::ops::Deref for Scratch {
        type Target = PathBuf;

        fn deref(&self) -> &PathBuf {
            &self.0
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn scratch(name: &str) -> Scratch {
        let directory = Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../target/test-scratch"
        ))
        .join(std::format!("cargo-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&directory);
        fs::create_dir_all(&directory).unwrap();
        Scratch(directory)
    }

    fn package(name: &str, cargo_toml: &str) -> (Scratch, PathBuf) {
        let directory = scratch(name);
        let path = directory.join("Cargo.toml");
        fs::write(&path, cargo_toml).unwrap();
        (directory, path)
    }

    fn read_error(cargo_toml: &str) -> String {
        let (_directory, path) = package("error", cargo_toml);
        let error = read_board(&path).unwrap_err();
        let text = error.to_string();
        assert!(
            text.starts_with(&std::format!("{}: ", path.display())),
            "{text}"
        );
        text
    }

    #[test]
    fn environment_variables_come_first() {
        let path_only =
            |name: &str| (name == "CARGO_MANIFEST_PATH").then(|| "/a/Cargo.toml".into());
        assert_eq!(
            manifest_from(path_only),
            Some(PathBuf::from("/a/Cargo.toml"))
        );
        let both = |name: &str| match name {
            "CARGO_MANIFEST_PATH" => Some("/a/Cargo.toml".into()),
            "CARGO_MANIFEST_DIR" => Some("/b".into()),
            _ => None,
        };
        assert_eq!(manifest_from(both), Some(PathBuf::from("/a/Cargo.toml")));
        let directory_only = |name: &str| (name == "CARGO_MANIFEST_DIR").then(|| "/b".into());
        assert_eq!(
            manifest_from(directory_only),
            Some(PathBuf::from("/b/Cargo.toml"))
        );
        let empty_path = |name: &str| match name {
            "CARGO_MANIFEST_PATH" => Some("".into()),
            "CARGO_MANIFEST_DIR" => Some("/b".into()),
            _ => None,
        };
        assert_eq!(
            manifest_from(empty_path),
            Some(PathBuf::from("/b/Cargo.toml"))
        );
        let both_empty = |name: &str| match name {
            "CARGO_MANIFEST_PATH" | "CARGO_MANIFEST_DIR" => Some("".into()),
            _ => None,
        };
        assert_eq!(manifest_from(both_empty), None);
        assert_eq!(manifest_from(|_| None), None);
    }

    #[test]
    fn the_nearest_manifest_decides() {
        let (directory, path) = package("nearest", "[package]\nname = \"outer\"\n");
        let deep = directory.join("src/deep");
        fs::create_dir_all(&deep).unwrap();
        assert_eq!(find_manifest(&deep), Some(path.clone()));
        assert_eq!(find_manifest(&directory), Some(path));
        let inner = directory.join("inner");
        fs::create_dir_all(&inner).unwrap();
        fs::write(inner.join("Cargo.toml"), "[package]\nname = \"inner\"\n").unwrap();
        assert_eq!(
            find_manifest(&inner.join("src")),
            Some(inner.join("Cargo.toml"))
        );
    }

    #[test]
    fn a_relative_start_is_resolved_before_the_walk() {
        // The tests of a crate run in its directory. The relative path goes up to the scratch
        // directory, and from there to the package: a walk over the text of the path would stop
        // at the empty path and find the Cargo.toml of this crate instead.
        let (directory, path) = package("relative", "[package]\nname = \"outer\"\n");
        let deep = directory.join("src/deep");
        fs::create_dir_all(&deep).unwrap();
        let relative = Path::new("../../target/test-scratch")
            .join(directory.file_name().unwrap())
            .join("src/deep");
        assert!(relative.is_relative());
        let found = find_manifest(&relative).unwrap();
        assert_eq!(
            fs::canonicalize(found).unwrap(),
            fs::canonicalize(path).unwrap()
        );
        // From the directory above the crate: a Cargo.toml above it, not the one of the crate.
        let found = find_manifest(Path::new("..")).unwrap();
        assert!(found.is_absolute(), "{}", found.display());
        assert_ne!(
            fs::canonicalize(found).unwrap(),
            fs::canonicalize(MANIFEST).unwrap()
        );
    }

    #[test]
    fn the_workspace_root_is_found_from_a_member() {
        let (root, _manifest) = package("workspace", "[workspace]\nmembers = [\"crates/*\"]\n");
        let member = root.join("crates/firmware");
        fs::create_dir_all(&member).unwrap();
        fs::write(
            member.join("Cargo.toml"),
            "[package]\nname = \"firmware\"\n",
        )
        .unwrap();
        assert_eq!(
            workspace_root(&member.join("Cargo.toml")),
            Some(root.clone())
        );
        // The root itself, and an ancestor that is a package without a workspace is skipped.
        assert_eq!(workspace_root(&root.join("Cargo.toml")), Some(root.clone()));
        let middle = root.join("crates");
        fs::write(middle.join("Cargo.toml"), "[package]\nname = \"middle\"\n").unwrap();
        assert_eq!(
            workspace_root(&member.join("Cargo.toml")),
            Some(root.to_path_buf())
        );
    }

    #[test]
    fn a_package_workspace_key_names_the_root() {
        let (root, _manifest) = package("workspace-key", "[workspace]\nmembers = [\"a/b\"]\n");
        let member = root.join("a/b");
        fs::create_dir_all(&member).unwrap();
        fs::write(
            member.join("Cargo.toml"),
            "[package]\nname = \"firmware\"\nworkspace = \"../..\"\n",
        )
        .unwrap();
        assert_eq!(
            workspace_root(&member.join("Cargo.toml")),
            Some(member.join("../.."))
        );
    }

    #[test]
    fn a_package_without_a_workspace_table_does_not_name_itself() {
        // The scratch directory is inside the workspace of this repository, so an ancestor is
        // found: only the directory of the package itself must not be the root.
        let (directory, path) = package("no-workspace", "[package]\nname = \"alone\"\n");
        assert_ne!(workspace_root(&path), Some(directory.clone()));
        assert_eq!(workspace_root(&directory.join("missing/Cargo.toml")), None);
        fs::write(&path, "not toml = [").unwrap();
        assert_eq!(workspace_root(&path), None);
    }

    #[test]
    fn a_directory_named_cargo_toml_is_not_a_manifest() {
        let directory = scratch("directory");
        fs::create_dir_all(directory.join("Cargo.toml")).unwrap();
        // The nearest file is the Cargo.toml above the scratch directory: the one of this crate's
        // workspace, which `target/test-scratch` sits in.
        let found = find_manifest(&directory).unwrap();
        assert_ne!(found, directory.join("Cargo.toml"));
        let above = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.toml");
        assert_eq!(
            fs::canonicalize(found).unwrap(),
            fs::canonicalize(above).unwrap()
        );
    }

    #[test]
    fn reads_the_board_of_a_package() {
        let (directory, path) = package(
            "board",
            "[package]\nname = \"firmware\"\n\n[package.metadata.nanoflash]\n\
             board = \"boards/b.toml\"\nboard-identifier = \"x\"\n",
        );
        assert_eq!(
            read_board(&path).unwrap(),
            Some(PackageBoard {
                cargo_toml: path,
                board: directory.join("boards/b.toml"),
                board_identifier: Some("x".into()),
            })
        );
        let (directory, path) = package(
            "board-only",
            "[package]\nname = \"firmware\"\n\n[package.metadata.nanoflash]\nboard = \"b.toml\"\n",
        );
        assert_eq!(
            read_board(&path).unwrap(),
            Some(PackageBoard {
                cargo_toml: path,
                board: directory.join("b.toml"),
                board_identifier: None,
            })
        );
    }

    #[test]
    fn packages_without_a_board() {
        for (name, text) in [
            ("none", "[package]\nname = \"firmware\"\n"),
            (
                "other",
                "[package]\nname = \"firmware\"\n\n[package.metadata.docs]\nrs = true\n",
            ),
            ("virtual", "[workspace]\nmembers = [\"a\"]\n"),
            (
                "virtual-metadata",
                "[workspace]\nmembers = [\"a\"]\n\n[workspace.metadata.nanoflash]\nboard = \"b.toml\"\n",
            ),
        ] {
            let (_directory, path) = package(name, text);
            assert_eq!(read_board(&path).unwrap(), None, "{name}");
        }
    }

    #[test]
    fn bad_metadata_is_explained() {
        let needs = "[package.metadata.nanoflash] needs \"board\", the path of the board manifest relative to Cargo.toml";
        let table = "[package]\nname = \"firmware\"\n\n[package.metadata.nanoflash]\n";
        assert!(read_error(table).ends_with(needs));
        assert!(read_error(&std::format!("{table}board-identifier = \"x\"\n")).ends_with(needs));
        assert!(read_error(&std::format!("{table}board = 3\n")).ends_with(needs));
        assert!(
            read_error(&std::format!("{table}board = \"b.toml\"\nport = \"x\"\n")).ends_with(
                "[package.metadata.nanoflash] has an unknown key \"port\": it takes \"board\" and \"board-identifier\""
            )
        );
        assert!(
            read_error(&std::format!(
                "{table}board = \"b.toml\"\nboard-identifier = 3\n"
            ))
            .ends_with("[package.metadata.nanoflash] has a \"board-identifier\" that is not text")
        );
        assert!(
            read_error("[package]\nname = \"x\"\n\n[package.metadata]\nnanoflash = \"b.toml\"\n")
                .ends_with("[package.metadata.nanoflash] must be a table with the key \"board\""),
        );
    }

    #[test]
    fn text_that_is_not_toml_is_a_parse_error() {
        let (_directory, path) = package("not-toml", "[package\n");
        let error = read_board(&path).unwrap_err();
        assert!(matches!(&error, PackageError::Parse { path: named, .. } if *named == path));
        let text = error.to_string();
        assert!(
            text.starts_with(&std::format!("{}: ", path.display())),
            "{text}"
        );
        assert!(text.len() > path.display().to_string().len() + 2, "{text}");
    }

    #[test]
    fn a_missing_file_is_an_input_error() {
        let directory = scratch("missing");
        let path = directory.join("Cargo.toml");
        let error = read_board(&path).unwrap_err();
        assert!(matches!(error, PackageError::Io { .. }));
        assert!(
            error
                .to_string()
                .starts_with(&std::format!("cannot read {}: ", path.display()))
        );
    }

    fn manifest(boards: &[(&str, Option<&str>)]) -> Manifest {
        let mut text = String::new();
        for (identifier, layout) in boards {
            text.push_str(&std::format!(
                "[[board]]\nidentifier = \"{identifier}\"\nprotocol = \"espressif\"\nchip = \"esp32\"\n"
            ));
            if let Some(layout) = layout {
                text.push_str(&std::format!("layout = \"{layout}\"\n"));
            }
        }
        Manifest::from_toml(&text).unwrap()
    }

    #[test]
    fn layout_of_a_manifest() {
        let one = manifest(&[("a", Some("a.toml"))]);
        assert_eq!(layout_of(&one, None).unwrap(), "a.toml");
        assert_eq!(layout_of(&one, Some("a")).unwrap(), "a.toml");
        assert_eq!(
            layout_of(&one, Some("z")).unwrap_err(),
            "the manifest has no board \"z\"; it lists \"a\""
        );

        let shared = manifest(&[("a", Some("same.toml")), ("b", Some("same.toml"))]);
        assert_eq!(layout_of(&shared, None).unwrap(), "same.toml");

        let different = manifest(&[("a", Some("a.toml")), ("b", Some("b.toml"))]);
        assert_eq!(
            layout_of(&different, None).unwrap_err(),
            "the boards of the manifest (\"a\", \"b\") use different layouts: name one with board-identifier"
        );
        assert_eq!(layout_of(&different, Some("b")).unwrap(), "b.toml");
        assert_eq!(
            layout_of(&different, Some("c")).unwrap_err(),
            "the manifest has no board \"c\"; it lists \"a\", \"b\""
        );

        let missing = manifest(&[("a", None)]);
        assert_eq!(
            layout_of(&missing, None).unwrap_err(),
            "the board \"a\" has no layout"
        );
        assert_eq!(
            layout_of(&missing, Some("a")).unwrap_err(),
            "the board \"a\" has no layout"
        );

        let partial = manifest(&[("a", Some("a.toml")), ("b", None)]);
        assert_eq!(layout_of(&partial, Some("a")).unwrap(), "a.toml");
        assert_eq!(
            layout_of(&partial, Some("b")).unwrap_err(),
            "the board \"b\" has no layout"
        );
        assert!(
            layout_of(&partial, None)
                .unwrap_err()
                .contains("different layouts")
        );

        let none = manifest(&[("a", None), ("b", None)]);
        assert_eq!(
            layout_of(&none, None).unwrap_err(),
            "the boards of the manifest (\"a\", \"b\") have no layout"
        );
    }
}