devsandbox 0.11.1

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! Machines: remote hosts whose daemons this one talks to over the `API`
//! streams of one link per machine (docs/architecture/daemon/machines.md):
//! for an ssh machine the link this host holds to it
//! (`ssh <target> devsandbox fleet-link --peer <this host>`,
//! `fleet::dialer`), for an inbound neighbor the one it holds to this host
//! (`inbound`, docs/architecture/daemon/fleet.md); either way reached at
//! `fleet-<name>.sock` (`fleet::dialer::dial`).
//!
//! - this module: the registry, `machines.toml` next to `state.toml`
//! - `ssh`: the add-time ssh argvs and quoting, and the injectable
//!   [`ssh::Dial`] that opens a [`ssh::Duplex`] to a machine
//! - `link`: a connection to a machine's daemon (the hello)
//! - `service`: the held link per machine, its rows and forwarded calls
//! - `api`: the `machines.*` methods
//! - `leave`: `machine rm` (a revoke on the authority, a proposal from
//!   another member) and the step-9 removal over the links
//! - `changes`: signed membership changes pushed (`fleet.sync`), proposals
//!   (`fleet.propose`) and their approval (`membership.pending|approve|deny`)
//! - `forward`: requests with `machine` (quick calls, verbs) and the
//!   federated resolve and sandboxes listing
//! - `cli`: the CLI's side: where a `<name>` points, `--machine`, and a
//!   command's calls and `PTY` dials over the machine's link
//! - `install`: the CLI's check of a machine's devsandbox and the copy of
//!   this binary there
//! - `saved`: a control plane's `remotes.json`, the machines' last known rows
//!
//! Only the daemon writes the registry (`machines.add` / `set` / `rm`);
//! the CLI reads it later to know whether any machine exists. Two
//! daemons can briefly overlap during a handoff, so every write is a
//! read-modify-write under an exclusive lock on the sibling `machines.lock`,
//! written to a temp file and renamed (`serve::locked_file`).

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

pub mod api;
pub mod changes;
pub mod cli;
pub mod forward;
pub mod inbound;
pub mod install;
pub mod join;
pub mod leave;
pub mod link;
pub mod saved;
pub mod service;
pub mod ssh;

/// One registered machine, as `machines.toml` holds it under
/// `[machine.<name>]` (docs/architecture/daemon/machines.md, *Registry:
/// `machines.toml`*): an ssh machine, `target = "…"` ([`RawEntry`]). The
/// service also holds an [`Entry::inbound`] per inbound neighbor, never
/// saved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "RawEntry", into = "RawEntry")]
pub struct Entry {
    /// The table key, so not a field of its own in the file.
    pub name: String,
    pub kind: Kind,
    /// The machine's live roots: what its daemon's last `roots.list` over
    /// its link answered (`service::Handle::entries`, `machines.get`).
    /// Never in `machines.toml`: empty as loaded.
    pub roots: Vec<PathBuf>,
    /// The remote devsandbox as shell text (`~/bin/devsandbox`); `None` is
    /// `devsandbox` on the login shell's `PATH`.
    pub command: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Kind {
    /// This host sshes to it: `target` is what ssh takes (`me@host`, `host`,
    /// an ssh-config alias) or an `ssh://` URL ([`ssh::parse_target`]).
    Ssh { target: String },
    /// An inbound neighbor (`inbound::Neighbors`): it dialed this host, its
    /// `fleet-link --peer <it>` here binds `fleet-<name>.sock`. Never in
    /// `machines.toml`: the service makes one of each neighbor up now
    /// ([`Entry::inbound`]).
    Inbound,
}

/// [`Kind`] on the wire (`kind` of `machines.list` / `get` and the
/// federated snapshot's `machines`, next to a `target` that is `null` for an
/// inbound neighbor; fleet plan decision 29).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MachineKind {
    #[default]
    Ssh,
    /// An inbound neighbor (`inbound`): a machine whose link to this host
    /// is dialed from its end, a machine here while that link is up;
    /// never a registry entry.
    Inbound,
    /// A routed machine (`routed`): a fleet member this host has no link
    /// of its own to, reached over a route through other members (fleet
    /// plan decision 60); never a registry entry.
    Routed,
}

impl Kind {
    /// The wire's `kind` and `target`.
    pub fn wire(&self) -> (MachineKind, Option<String>) {
        match self {
            Kind::Ssh { target } => (MachineKind::Ssh, Some(target.clone())),
            Kind::Inbound => (MachineKind::Inbound, None),
        }
    }

    /// Back from the wire's `kind` and `target`: an ssh machine needs its
    /// target. A routed machine comes back as `Inbound`: like one, it has
    /// no ssh target and is reached over this host's sockets
    /// (`fleet::route::connect`), all the CLI asks of it.
    pub fn from_wire(kind: MachineKind, target: Option<String>) -> Result<Kind> {
        match (kind, target) {
            (MachineKind::Ssh, Some(target)) => Ok(Kind::Ssh { target }),
            (MachineKind::Ssh, None) => bail!("an ssh machine without a target"),
            (MachineKind::Inbound | MachineKind::Routed, _) => Ok(Kind::Inbound),
        }
    }
}

impl Entry {
    /// An ssh machine with no roots yet, `command` unset.
    pub fn ssh(name: impl Into<String>, target: impl Into<String>) -> Entry {
        Entry { name: name.into(), kind: Kind::Ssh { target: target.into() }, roots: Vec::new(), command: None }
    }

    /// Inbound neighbor `name` as the service holds it, no roots yet.
    pub fn inbound(name: impl Into<String>) -> Entry {
        Entry { name: name.into(), kind: Kind::Inbound, roots: Vec::new(), command: None }
    }

    pub fn command(&self) -> &str {
        self.command.as_deref().unwrap_or("devsandbox")
    }

    /// The ssh target; `None` for an inbound one.
    pub fn target(&self) -> Option<&str> {
        match &self.kind {
            Kind::Ssh { target } => Some(target),
            Kind::Inbound => None,
        }
    }

    /// What messages and listings call where it is: the target, or
    /// `inbound`.
    pub fn label(&self) -> &str {
        match self.kind {
            Kind::Ssh { ref target } => target,
            Kind::Inbound => "inbound",
        }
    }

    /// The ssh target, for the add-time argv builders ([`ssh`]): an inbound
    /// machine has none.
    pub fn ssh_target(&self) -> Result<&str> {
        let name = &self.name;
        self.target().with_context(|| format!("machine `{name}` links to this host from its end, reached over its fleet link, not ssh"))
    }
}

/// [`Entry`] as the file holds it. `offered` is only read, to name an
/// entry an older build wrote for a fleet worker ([`TryFrom`]). Unknown
/// keys are ignored (an older build's `agent`: agent grants live in
/// `member.toml`, `fleet::member::Grant`; its `roots`: a machine's are
/// what it lists), and dropped by the next write.
#[derive(Serialize, Deserialize)]
struct RawEntry {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    target: Option<String>,
    #[serde(default, skip_serializing)]
    offered: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    command: Option<String>,
}

impl TryFrom<RawEntry> for Entry {
    type Error = String;

    /// The name is the table key: [`parse`] fills it in.
    fn try_from(raw: RawEntry) -> Result<Entry, String> {
        let kind = match (raw.target, raw.offered) {
            (_, true) => {
                return Err("`offered = true` (an older devsandbox's fleet worker) is no longer read: \
                     delete the entry from the file by hand"
                    .into());
            }
            (Some(target), false) => Kind::Ssh { target },
            (None, false) => return Err("no `target`".into()),
        };
        Ok(Entry { name: String::new(), kind, roots: Vec::new(), command: raw.command })
    }
}

impl From<Entry> for RawEntry {
    fn from(e: Entry) -> RawEntry {
        let target = match e.kind {
            Kind::Ssh { target } => Some(target),
            // Never saved (`update` only holds what `load` read): it would
            // read back as an entry without a target.
            Kind::Inbound => None,
        };
        RawEntry { target, offered: false, command: e.command }
    }
}

#[derive(Default, Serialize, Deserialize)]
struct Doc {
    #[serde(default, rename = "machine")]
    machines: BTreeMap<String, RawEntry>,
}

/// [`path_from`] over the process env.
pub fn path() -> Result<PathBuf> {
    path_from(std::env::var_os("XDG_DATA_HOME"), std::env::var_os("HOME"))
}

/// `<data>/devsandbox/machines.toml`.
pub fn path_from(xdg_data_home: Option<OsString>, home: Option<OsString>) -> Result<PathBuf> {
    Ok(crate::daemon_config::data_dir_from(xdg_data_home, home)?.join("machines.toml"))
}

/// The entries, sorted by name. A hand-edited name that breaks
/// [`check_name`], or an entry that isn't one ([`RawEntry`]), fails the
/// whole file, naming the entry: a qualified `<machine>/<name>` could not
/// address it.
pub fn parse(text: &str) -> Result<Vec<Entry>> {
    let doc: Doc = toml::from_str(text)?;
    doc.machines
        .into_iter()
        .map(|(name, raw)| {
            check_name(&name)?;
            let entry = Entry::try_from(raw).map_err(|why| anyhow::anyhow!("[machine.{name}]: {why}"))?;
            Ok(Entry { name, ..entry })
        })
        .collect()
}

pub fn serialize(entries: &[Entry]) -> Result<String> {
    let doc = Doc { machines: entries.iter().map(|e| (e.name.clone(), RawEntry::from(e.clone()))).collect() };
    toml::to_string_pretty(&doc).context("cannot serialize machines")
}

/// The registered machines; a missing file is none.
pub fn load(path: &Path) -> Result<Vec<Entry>> {
    match std::fs::read_to_string(path) {
        Ok(text) => parse(&text).with_context(|| format!("invalid {}", path.display())),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
        Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
    }
}

/// Read-modify-write under the exclusive lock; saves only when `f` changed
/// the entries. A file that doesn't parse fails the update rather than being
/// overwritten.
pub fn update<T>(path: &Path, f: impl FnOnce(&mut Vec<Entry>) -> T) -> Result<T> {
    super::locked_file::update(path, load, |e| serialize(e), f)
}

/// A machine name is `[A-Za-z0-9._-]+`, not starting with `.` or `-`. Never
/// `/` or `@`: `my-server/web-2` splits at the first `/`, and `@/web-2` is
/// this host. No leading `-`, so it can't read as a flag either.
pub fn check_name(name: &str) -> Result<()> {
    if name.is_empty() {
        bail!("empty machine name");
    }
    if name.starts_with(['.', '-']) {
        bail!("machine name `{name}` starts with `{}`", &name[..1]);
    }
    if let Some(c) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))) {
        bail!("machine name `{}` has `{}` (letters, digits, `.`, `_` and `-` only)", name.escape_debug(), c.escape_debug());
    }
    Ok(())
}

/// Where a CLI `<name>` points (docs/architecture/daemon/machines.md,
/// *Registry: `machines.toml`*).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Where {
    /// `@/<name>`: this host only.
    Local,
    /// `<machine>/<name>`: that machine only.
    Machine(String),
    /// A bare name: this host and every machine.
    Any,
}

/// Split a CLI `<name>` into where it points and the name there. Docker
/// container names can't hold `/` or `@`, so neither can a working instance
/// or sandbox name: any `/` qualifies, at the first one, and a machine
/// part that isn't a valid machine name is an error rather than a bare name
/// that could never match.
pub fn parse_name(arg: &str) -> Result<(Where, String)> {
    let Some((machine, name)) = arg.split_once('/') else { return Ok((Where::Any, arg.to_string())) };
    if name.is_empty() {
        bail!("`{arg}`: no name after `/`");
    }
    if machine == "@" {
        return Ok((Where::Local, name.to_string()));
    }
    check_name(machine).with_context(|| format!("`{arg}` isn't `<machine>/<name>` or `@/<name>`"))?;
    Ok((Where::Machine(machine.to_string()), name.to_string()))
}

/// The registered machines' names, from the file: the one place the
/// CLI reads the daemon's registry itself, so that without machines no
/// command contacts a daemon it didn't before. Missing, empty or unreadable
/// is none.
pub fn registered_names() -> Vec<String> {
    path().and_then(|p| load(&p)).map(|entries| entries.into_iter().map(|e| e.name).collect()).unwrap_or_default()
}

/// The root a command on a machine takes when it names none, from the
/// machine's `roots.list` `rows` (docs/architecture/daemon/machines.md,
/// *Default root*; pure): its signed config's copy when there's one, of
/// several the one named `.devsandboxes`; else its `~/.devsandboxes`; else
/// its only root; else none (several, none of them the default).
pub fn default_root(rows: &[crate::serve::api::RootCandidate]) -> Option<PathBuf> {
    let copies: Vec<&crate::serve::api::RootCandidate> = rows.iter().filter(|r| r.copy.is_some()).collect();
    let copy = match copies.as_slice() {
        [one] => Some(*one),
        _ => copies.iter().copied().find(|r| r.copy.as_deref() == Some(".devsandboxes")),
    };
    let row = copy.or_else(|| rows.iter().find(|r| r.home)).or(match rows {
        [only] => Some(only),
        _ => None,
    })?;
    Some(row.root.clone())
}

/// Why machine `m`, with `roots` (`listed`: its link has answered
/// `roots.list` since this daemon started), has no [`default_root`]:
/// nothing listed yet, no roots, or several with none the default (named
/// as `m:<root>`, a command's root on a machine).
pub fn no_default_root(m: &str, roots: &[PathBuf], listed: bool) -> String {
    match roots {
        [] if !listed => format!("machine `{m}`'s link hasn't listed its roots yet (devsandbox machine ls)"),
        [] => format!("machine `{m}` has no config roots (devsandbox machine ls)"),
        _ => {
            let named: Vec<String> = roots.iter().map(|r| format!("{m}:{}", r.display())).collect();
            format!("machine `{m}` has {} config roots and none is its default: {}", roots.len(), named.join(", "))
        }
    }
}

/// The error for a machine nobody registered.
pub fn no_machine(name: &str) -> anyhow::Error {
    anyhow::anyhow!("no machine named `{name}` (devsandbox machine ls)")
}

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

    fn entry(name: &str, target: &str) -> Entry {
        Entry::ssh(name, target)
    }

    #[test]
    fn the_path_is_next_to_state_toml() {
        let p = path_from(Some("/xdg".into()), Some("/home/u".into())).unwrap();
        assert_eq!(p, PathBuf::from("/xdg/devsandbox/machines.toml"));
        let p = path_from(None, Some("/home/u".into())).unwrap();
        assert_eq!(p, PathBuf::from("/home/u/.local/share/devsandbox/machines.toml"));
        assert!(path_from(None, None).is_err());
    }

    #[test]
    fn entries_round_trip_sorted_by_name() {
        let entries = vec![
            Entry { command: Some("~/bin/devsandbox".into()), ..entry("b-box", "ssh://me@b:2200") },
            entry("a.box", "me@a"),
        ];
        let text = serialize(&entries).unwrap();
        assert!(text.contains("[machine.\"a.box\"]") && text.contains("[machine.b-box]"), "{text}");
        // `command` only when set; the name is the key, not a field.
        assert_eq!(text.matches("command").count(), 1, "{text}");
        assert!(!text.contains("name"), "{text}");
        let mut want = entries.clone();
        want.reverse();
        assert_eq!(parse(&text).unwrap(), want);
        assert_eq!(parse("").unwrap(), vec![]);
        let minimal = parse("[machine.m]\ntarget = \"m\"\n").unwrap();
        assert_eq!(minimal, vec![Entry::ssh("m", "m")]);
        // An older build's `agent` is ignored (grants are member.toml's).
        assert_eq!(parse("[machine.m]\ntarget = \"m\"\nagent = true\n").unwrap(), vec![Entry::ssh("m", "m")]);
        // An older build's `roots` too, and the next write drops it; live
        // roots in memory are never written.
        let old = parse("[machine.m]\ntarget = \"m\"\nroots = [\"/a\"]\n").unwrap();
        assert_eq!(old, vec![Entry::ssh("m", "m")]);
        let live = Entry { roots: vec!["/a".into()], ..Entry::ssh("m", "m") };
        assert!(!serialize(&[live]).unwrap().contains("roots"));
        assert!(parse("[machine.\"a/b\"]\ntarget = \"m\"\n").is_err(), "a bad name fails the file");
        assert!(parse("[machine.m]\n").is_err(), "no target");
    }

    #[test]
    fn an_old_offered_entry_fails_the_file_naming_it() {
        for text in ["[machine.lap]\noffered = true\n", "[machine.srv]\ntarget = \"s\"\n\n[machine.lap]\ntarget = \"m\"\noffered = true\n"] {
            let e = format!("{:#}", parse(text).unwrap_err());
            assert!(e.contains("[machine.lap]: `offered = true`") && e.contains("delete the entry from the file by hand"), "{e}");
        }
        // Never written.
        let text = serialize(&[entry("srv", "me@srv")]).unwrap();
        assert!(!text.contains("offered"), "{text}");
        assert!(parse("[machine.m]\noffered = false\n").is_err(), "no target");
        let e = format!("{:#}", parse("[machine.m]\n").unwrap_err());
        assert!(e.contains("[machine.m]: no `target`"), "{e}");
    }

    #[test]
    fn kinds_on_the_wire() {
        assert_eq!(entry("srv", "me@srv").ssh_target().unwrap(), "me@srv");
        assert_eq!(Kind::from_wire(MachineKind::Ssh, Some("t".into())).unwrap(), Kind::Ssh { target: "t".into() });
        assert!(Kind::from_wire(MachineKind::Ssh, None).is_err());
        assert!(serde_json::from_value::<MachineKind>(serde_json::json!("offered")).is_err(), "ssh | inbound | routed only");
        assert_eq!(Kind::from_wire(MachineKind::Inbound, None).unwrap(), Kind::Inbound);
        assert_eq!(serde_json::from_value::<MachineKind>(serde_json::json!("routed")).unwrap(), MachineKind::Routed);
        assert_eq!(Kind::from_wire(MachineKind::Routed, None).unwrap(), Kind::Inbound, "no ssh target either");
        let lap = Entry::inbound("lap");
        assert_eq!((lap.target(), lap.label(), lap.kind == Kind::Inbound, lap.kind.wire()), (None, "inbound", true, (MachineKind::Inbound, None)));
        assert!(format!("{:#}", lap.ssh_target().unwrap_err()).contains("links to this host from its end"));
    }

    #[test]
    fn update_writes_only_changes_and_keeps_a_bad_file() {
        let dir = std::env::temp_dir().join(format!("devsandbox-machines-store-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("machines.toml");
        assert_eq!(load(&path).unwrap(), vec![]);
        update(&path, |e| e.push(entry("a", "a"))).unwrap();
        update(&path, |e| e.push(entry("b", "b"))).unwrap();
        assert!(dir.join("machines.lock").exists());
        update(&path, |e| e.retain(|e| e.name != "a")).unwrap();
        assert_eq!(load(&path).unwrap(), vec![entry("b", "b")]);
        // A no-op doesn't write: no file appears where there was none.
        let other = dir.join("sub/machines.toml");
        update(&other, |_| ()).unwrap();
        assert!(!other.exists());
        let leftovers: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.file_name().to_string_lossy().ends_with(".tmp")).collect();
        assert!(leftovers.is_empty(), "{leftovers:?}");

        std::fs::write(&path, "[machine.m\n").unwrap();
        assert!(update(&path, |e| e.clear()).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[machine.m\n");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn concurrent_updates_lose_nothing() {
        let dir = std::env::temp_dir().join(format!("devsandbox-machines-race-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("machines.toml");
        let writers: Vec<_> = (0..8)
            .map(|i| {
                let path = path.clone();
                std::thread::spawn(move || update(&path, |e| e.push(entry(&format!("m{i}"), "t"))).unwrap())
            })
            .collect();
        for w in writers {
            w.join().unwrap();
        }
        assert_eq!(load(&path).unwrap().len(), 8);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn names_are_plain_words() {
        for good in ["my-server", "my-server.com", "a", "A_1", "10.0.0.1", "box-"] {
            assert!(check_name(good).is_ok(), "{good}");
        }
        for bad in ["", ".hidden", "-x", "a/b", "@", "me@box", "a b", "a:22", "é"] {
            assert!(check_name(bad).is_err(), "{bad:?} passed");
        }
    }

    #[test]
    fn names_parse_qualified_local_or_bare() {
        let p = |s: &str| parse_name(s).unwrap();
        assert_eq!(p("web-2"), (Where::Any, "web-2".into()));
        assert_eq!(p("@/web-2"), (Where::Local, "web-2".into()));
        assert_eq!(p("my-server/web-2"), (Where::Machine("my-server".into()), "web-2".into()));
        // Split at the first `/`: the rest is the name, whatever it holds.
        assert_eq!(p("a/b/c"), (Where::Machine("a".into()), "b/c".into()));
        assert_eq!(p("a/devsandbox-web"), (Where::Machine("a".into()), "devsandbox-web".into()));
        for bad in ["a/", "@/", "/web", "me@box/web", "a b/web", "-x/web", "@@/web"] {
            assert!(parse_name(bad).is_err(), "{bad:?} parsed");
        }
        assert_eq!(no_machine("m").to_string(), "no machine named `m` (devsandbox machine ls)");
    }

    /// The default root: the one signed copy (of several, `.devsandboxes`),
    /// else `~/.devsandboxes`, else the only root, else none.
    #[test]
    fn the_default_root_on_a_machine() {
        use crate::serve::api::RootCandidate;
        let row = |root: &str| RootCandidate { root: root.into(), sandboxes: vec![], error: None, fleet: false, copy: None, home: false };
        let copy = |root: &str, name: &str| RootCandidate { copy: Some(name.into()), ..row(root) };
        let home = |root: &str| RootCandidate { home: true, ..row(root) };
        let pick = |rows: Vec<RootCandidate>| default_root(&rows).map(|p| p.display().to_string());
        assert_eq!(pick(vec![row("/a"), home("/h"), copy("/t/cfg", "cfg")]).as_deref(), Some("/t/cfg"), "one copy");
        let two = vec![copy("/t/a", "a"), home("/h"), copy("/t/d", ".devsandboxes")];
        assert_eq!(pick(two).as_deref(), Some("/t/d"), "two copies, one `.devsandboxes`");
        assert_eq!(pick(vec![copy("/t/a", "a"), home("/h"), copy("/t/b", "b")]).as_deref(), Some("/h"), "two copies: home");
        assert_eq!(pick(vec![copy("/t/a", "a"), copy("/t/b", "b")]), None, "two copies, no home");
        assert_eq!(pick(vec![row("/a"), home("/h")]).as_deref(), Some("/h"), "home");
        assert_eq!(pick(vec![row("/a")]).as_deref(), Some("/a"), "the only root");
        assert_eq!(pick(vec![row("/a"), row("/b")]), None, "several");
        assert_eq!(pick(vec![]), None, "none");

        let roots = [PathBuf::from("/a"), PathBuf::from("/b")];
        assert_eq!(no_default_root("m", &roots, true), "machine `m` has 2 config roots and none is its default: m:/a, m:/b");
        assert_eq!(no_default_root("m", &[], false), "machine `m`'s link hasn't listed its roots yet (devsandbox machine ls)");
        assert_eq!(no_default_root("m", &[], true), "machine `m` has no config roots (devsandbox machine ls)");
    }
}