geolith-dataset-builder 0.5.0

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! `geolith dataset schedule`: the daily refresh job, installed on the binary.
//!
//! Ported from the `schedule` command of the former `scripts/datasets/refresh.ts`, with
//! one deliberate change of shape (plan Decision 4): the job runs the installed
//! binary at `~/.local/share/geolith/bin/geolith`, never a worktree and never
//! `bash`. Updating the pipeline is `schedule install` again after a build;
//! there is no per-commit checkout to go stale.
//!
//! macOS writes `~/Library/LaunchAgents/app.geolith.datasets-refresh.plist`
//! (`StartCalendarInterval` 08:30 local, `RunAtLoad` false, `ThrottleInterval`
//! 3600) and bootstraps it; a failed bootstrap prints the `launchctl` command
//! and exits 1. Elsewhere the two systemd user units are written and the two
//! `systemctl --user` commands are printed.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::error::{DatasetError, IoOp, IoResultExt as _, IoStepExt as _, Result};

use crate::cli::{ScheduleAction, ScheduleArgs};
use crate::layout::{data_root, hex, sha256_file};
use crate::settings;

/// The launchd job label.
pub const JOB_LABEL: &str = "app.geolith.datasets-refresh";
/// The installed binary, under `$HOME`.
pub const INSTALL_BIN: &str = ".local/share/geolith/bin/geolith";
/// The one line both platforms print for the schedule.
pub const SCHEDULE_TEXT: &str = "daily at 08:30 local time (StartCalendarInterval 8:30, \
                                 RunAtLoad false); a missed run happens at the next wake";
/// The launchd template.
const PLIST_TEMPLATE: &str = include_str!("launchd/app.geolith.datasets-refresh.plist.tmpl");
/// The systemd service template.
const SERVICE_TEMPLATE: &str = include_str!("systemd/geolith-datasets-refresh.service.tmpl");
/// The systemd timer template.
const TIMER_TEMPLATE: &str = include_str!("systemd/geolith-datasets-refresh.timer.tmpl");

/// Everything the job definition needs.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PlistVars {
    /// The installed binary.
    pub bin: PathBuf,
    /// Its sha256, hex.
    pub bin_sha256: String,
    /// The data root the job works in.
    pub data_root: PathBuf,
    /// Where launchd writes the job's stdout and stderr.
    pub log_dir: PathBuf,
    /// `$HOME`.
    pub home: PathBuf,
    /// `PATH` of the job.
    pub path: String,
    /// The `.env` file the job reads, set as `GEOLITH_ENV_FILE`, when one is
    /// in use. A path, never a secret.
    pub env_file: Option<PathBuf>,
    /// The JSON config file the job reads, set as `GEOLITH_CONFIG`, when one
    /// is in use. The job's arguments never carry it.
    pub config: Option<PathBuf>,
    /// Hour of the local run.
    pub hour: u8,
    /// Minute of the local run.
    pub minute: u8,
}

impl PlistVars {
    /// The vars of `data_root` and `home`, with the run at 08:30.
    #[must_use]
    pub fn new(
        bin: PathBuf,
        bin_sha256: String,
        data_root: PathBuf,
        log_dir: PathBuf,
        home: PathBuf,
        path: String,
    ) -> Self {
        Self {
            bin,
            bin_sha256,
            data_root,
            log_dir,
            home,
            path,
            env_file: None,
            config: None,
            hour: 8,
            minute: 30,
        }
    }

    /// The same vars with the job reading the `.env` file `env_file` and the
    /// JSON config file `config`.
    #[must_use]
    pub fn with_settings(mut self, env_file: Option<PathBuf>, config: Option<PathBuf>) -> Self {
        self.env_file = env_file;
        self.config = config;
        self
    }

    /// Fills every placeholder of `template`.
    #[must_use]
    pub fn fill(&self, template: &str) -> String {
        // The plist lists the variables as key and string elements, the
        // systemd unit as `Environment=` lines.
        let plist = template.contains("<plist");
        let mut env_vars = String::new();
        for (name, path) in [
            ("GEOLITH_ENV_FILE", &self.env_file),
            ("GEOLITH_CONFIG", &self.config),
        ] {
            let Some(path) = path else { continue };
            let text = path.display().to_string();
            if plist {
                env_vars.push_str(&format!(
                    "\n    <key>{name}</key>\n    <string>{}</string>",
                    xml_escape(&text)
                ));
            } else {
                env_vars.push_str(&format!(
                    "\nEnvironment={}",
                    shell_word(&format!("{name}={text}"))
                ));
            }
        }
        template
            .replace("__ENV_VARS__", &env_vars)
            .replace("__BIN__", &self.bin.display().to_string())
            .replace("__BIN_SHA256__", &self.bin_sha256)
            .replace("__DATA_ROOT__", &self.data_root.display().to_string())
            .replace("__LOG_DIR__", &self.log_dir.display().to_string())
            .replace("__HOME__", &self.home.display().to_string())
            .replace("__PATH__", &self.path)
            .replace("__HOUR__", &self.hour.to_string())
            .replace("__MINUTE__", &self.minute.to_string())
    }
}

/// `text` for the body of an XML element.
fn xml_escape(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// `text` as one word of a systemd `ExecStart` line.
fn shell_word(text: &str) -> String {
    if text
        .chars()
        .any(|c| c.is_whitespace() || c == '"' || c == '\\')
    {
        format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
    } else {
        text.to_owned()
    }
}

/// The launchd plist of `vars`.
#[must_use]
pub fn render_plist(vars: &PlistVars) -> String {
    vars.fill(PLIST_TEMPLATE)
}

/// The systemd service of `vars`.
#[must_use]
pub fn render_service(vars: &PlistVars) -> String {
    vars.fill(SERVICE_TEMPLATE)
}

/// The systemd timer, unchanged by `vars`.
#[must_use]
pub fn render_timer() -> String {
    TIMER_TEMPLATE.to_owned()
}

/// Copies `from` to `to` through `<to>.part` + rename, mode 755.
///
/// # Errors
///
/// Fails when the copy, the rename or the mode change fails.
pub fn install_binary(from: &Path, to: &Path) -> Result<String> {
    if let Some(parent) = to.parent() {
        fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
    }
    let partial = to.with_extension("part");
    fs::copy(from, &partial).io_step(format!(
        "copying {} to {}",
        from.display(),
        partial.display()
    ))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        let mode = fs::Permissions::from_mode(0o755);
        fs::set_permissions(&partial, mode)
            .io_step(format!("setting the mode of {}", partial.display()))?;
    }
    fs::rename(&partial, to).io_at(IoOp::RenameTo, to)?;
    let digest = sha256_file(to)?;
    fs::metadata(to).io_at(IoOp::Read, to)?;
    Ok(hex(&digest))
}

/// Writes the plist into `dir`, mode 644.
///
/// # Errors
///
/// Fails when the directory or the file cannot be written.
pub fn write_plist(dir: &Path, vars: &PlistVars) -> Result<PathBuf> {
    fs::create_dir_all(dir).io_at(IoOp::Create, dir)?;
    let path = dir.join(format!("{JOB_LABEL}.plist"));
    fs::write(&path, render_plist(vars)).io_at(IoOp::Write, &path)?;
    Ok(path)
}

/// The `status` lines of the job, without running it.
#[must_use]
pub fn status_lines(
    plist: &Path,
    bin: &Path,
    installed: Option<&str>,
    running: &str,
    history: &[String],
) -> Vec<String> {
    let mut lines = vec![format!(
        "plist: {} ({})",
        plist.display(),
        if plist.is_file() {
            "installed"
        } else {
            "not installed"
        }
    )];
    lines.push(match installed {
        Some(digest) => format!(
            "binary: {} ({}, {})",
            bin.display(),
            &digest[..digest.len().min(12)],
            if digest == running {
                "current"
            } else {
                "stale"
            }
        ),
        None => format!("binary: {} (missing)", bin.display()),
    });
    lines.push(format!("schedule: {SCHEDULE_TEXT}"));
    for line in history {
        lines.push(format!("history: {line}"));
    }
    lines
}

/// The uid of this process, from `id -u`.
fn uid() -> u32 {
    Command::new("id")
        .arg("-u")
        .output()
        .ok()
        .and_then(|output| String::from_utf8_lossy(&output.stdout).trim().parse().ok())
        .unwrap_or(501)
}

/// Runs `launchctl <args>`, returning stdout on success.
fn launchctl(args: &[&str]) -> Result<String> {
    let output = Command::new("/bin/launchctl")
        .args(args)
        .output()
        .io_step("running launchctl")?;
    if !output.status.success() {
        return Err(DatasetError::config(
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// The last `count` lines of the refresh history, oldest first.
fn last_history(data_root: &Path, count: usize) -> Vec<String> {
    let path = data_root.join("datasets/refresh/history.jsonl");
    let Ok(text) = fs::read_to_string(path) else {
        return Vec::new();
    };
    let lines: Vec<&str> = text
        .lines()
        .filter(|line| !line.trim().is_empty())
        .collect();
    lines[lines.len().saturating_sub(count)..]
        .iter()
        .map(|line| (*line).to_owned())
        .collect()
}

/// The digest of the installed binary, when it is there.
fn installed_digest(path: &Path) -> Option<String> {
    sha256_file(path).ok().map(|digest| hex(&digest))
}

/// Run `geolith dataset schedule`.
///
/// # Errors
///
/// Fails when the binary cannot be installed, the plist written or the job
/// bootstrapped.
pub fn run(args: &ScheduleArgs) -> Result<()> {
    let root = data_root()?;
    let deployment = settings::current();
    let home = deployment
        .home
        .clone()
        .ok_or_else(|| DatasetError::config("HOME is not set"))?;
    let dest = home.join(INSTALL_BIN);
    let log_dir = root.join("datasets/refresh/logs");
    let history = last_history(&root, 3);
    let macos = cfg!(target_os = "macos");
    let plist_dir = home.join("Library/LaunchAgents");
    let plist = plist_dir.join(format!("{JOB_LABEL}.plist"));
    let units = home.join(".config/systemd/user");
    let running = std::env::current_exe().ok();
    let running_digest = running
        .as_deref()
        .and_then(installed_digest)
        .unwrap_or_default();

    match args.action {
        ScheduleAction::Status => {
            let lines = status_lines(
                &plist,
                &dest,
                installed_digest(&dest).as_deref(),
                &running_digest,
                &history,
            );
            for line in &lines {
                println!("{line}");
            }
            if macos {
                match launchctl(&["print", &format!("gui/{}/{JOB_LABEL}", uid())]) {
                    Ok(text) => {
                        let field = |name: &str| {
                            text.lines()
                                .find_map(|line| line.trim().strip_prefix(name))
                                .map(|value| value.trim().to_owned())
                                .unwrap_or_else(|| "unknown".to_owned())
                        };
                        println!(
                            "job: loaded, state = {}, last exit code = {}",
                            field("state = "),
                            field("last exit code = ")
                        );
                    }
                    Err(err) => println!("job: not loaded ({err})"),
                }
            } else {
                println!(
                    "systemd: {}",
                    units.join("geolith-datasets-refresh.timer").display()
                );
            }
            Ok(())
        }
        ScheduleAction::Uninstall => {
            if macos {
                let _ = launchctl(&["bootout", &format!("gui/{}/{JOB_LABEL}", uid())]);
                fs::remove_file(&plist).ok();
                println!("schedule: {JOB_LABEL} removed ({})", plist.display());
            } else {
                for unit in ["timer", "service"] {
                    fs::remove_file(units.join(format!("geolith-datasets-refresh.{unit}"))).ok();
                }
                println!(
                    "schedule: units removed from {}; run `systemctl --user daemon-reload`",
                    units.display()
                );
            }
            println!("schedule: the binary stays at {}", dest.display());
            Ok(())
        }
        ScheduleAction::Install => {
            let from =
                running.ok_or_else(|| DatasetError::config("cannot find the running binary"))?;
            let digest = install_binary(&from, &dest)?;
            println!("BINARY {} {digest}", dest.display());
            let path = deployment.path.clone().unwrap_or_else(|| {
                "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin".to_owned()
            });
            let vars = PlistVars::new(dest.clone(), digest, root, log_dir, home, path)
                .with_settings(deployment.env_file.clone(), deployment.config_file.clone());
            if macos {
                let written = write_plist(&plist_dir, &vars)?;
                let _ = launchctl(&["bootout", &format!("gui/{}/{JOB_LABEL}", uid())]);
                let domain = format!("gui/{}", uid());
                if let Err(err) = launchctl(&["bootstrap", &domain, &written.display().to_string()])
                {
                    eprintln!("schedule: launchctl bootstrap failed: {err}");
                    println!(
                        "schedule: fix it by hand: launchctl bootstrap {domain} {}",
                        written.display()
                    );
                    return Err(crate::exit::Exit(1).into());
                }
                launchctl(&["enable", &format!("{domain}/{JOB_LABEL}")])?;
                println!("schedule: installed {}", written.display());
            } else {
                fs::create_dir_all(&units).io_at(IoOp::Create, &units)?;
                fs::write(
                    units.join("geolith-datasets-refresh.service"),
                    render_service(&vars),
                )
                .io_step("writing the systemd service")?;
                fs::write(units.join("geolith-datasets-refresh.timer"), render_timer())
                    .io_step("writing the systemd timer")?;
                println!("systemctl --user daemon-reload");
                println!("systemctl --user enable --now geolith-datasets-refresh.timer");
            }
            println!("schedule: {SCHEDULE_TEXT}");
            Ok(())
        }
    }
}

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

    fn vars(dir: &Path) -> PlistVars {
        PlistVars::new(
            dir.join("bin/geolith"),
            "9f2c1d4e5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f".to_owned(),
            dir.join("data"),
            dir.join("data/datasets/refresh/logs"),
            dir.to_path_buf(),
            "/usr/bin:/bin".to_owned(),
        )
    }

    #[test]
    fn the_plist_runs_the_installed_binary_and_never_the_script_folder() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let plist = render_plist(&vars(dir.path()));
        assert!(!plist.contains("scripts/datasets"), "{plist}");
        assert!(!plist.contains("/bin/bash"), "{plist}");
        assert!(plist.contains("<string>dataset</string>"));
        assert!(plist.contains("<string>refresh</string>"));
        assert!(plist.contains(&dir.path().join("bin/geolith").display().to_string()));
    }

    #[test]
    fn the_written_plist_is_the_hand_written_expected_one() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let home = PathBuf::from("/home/test");
        let vars = PlistVars::new(
            home.join(INSTALL_BIN),
            "0123456789abcdef".to_owned(),
            PathBuf::from("/home/test/.data"),
            PathBuf::from("/home/test/.data/datasets/refresh/logs"),
            home.clone(),
            "/usr/bin:/bin".to_owned(),
        );
        let written = write_plist(dir.path(), &vars).expect("plist");
        let text = fs::read_to_string(&written).expect("read the plist");
        let expected = "\
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
  <key>Label</key>
  <string>app.geolith.datasets-refresh</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/bin/caffeinate</string>
    <string>-dimsu</string>
    <string>/home/test/.local/share/geolith/bin/geolith</string>
    <string>dataset</string>
    <string>refresh</string>
  </array>
  <key>WorkingDirectory</key>
  <string>/home/test/.data</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>/usr/bin:/bin</string>
    <key>HOME</key>
    <string>/home/test</string>
    <key>DATA_ROOT</key>
    <string>/home/test/.data</string>
    <key>GEOLITH_BIN</key>
    <string>/home/test/.local/share/geolith/bin/geolith</string>
    <key>GEOLITH_BIN_SHA256</key>
    <string>0123456789abcdef</string>
  </dict>
  <key>RunAtLoad</key>
  <false/>
  <key>StartCalendarInterval</key>
  <dict>
    <key>Hour</key>
    <integer>8</integer>
    <key>Minute</key>
    <integer>30</integer>
  </dict>
  <key>StandardOutPath</key>
  <string>/home/test/.data/datasets/refresh/logs/launchd.out.log</string>
  <key>StandardErrorPath</key>
  <string>/home/test/.data/datasets/refresh/logs/launchd.err.log</string>
  <key>ProcessType</key>
  <string>Background</string>
  <key>LowPriorityIO</key>
  <true/>
  <key>ThrottleInterval</key>
  <integer>3600</integer>
</dict>
</plist>
";
        // The template's comment block sits between the doctype and <plist>;
        // the expected value names the elements from <plist> on.
        let start = text.find("<plist").expect("plist element");
        let actual = &text[start..];
        let want = &expected[expected.find("<plist").expect("expected plist element")..];
        assert_eq!(actual, want);
    }

    #[test]
    fn a_job_with_an_env_file_names_it_in_its_environment_and_not_in_its_arguments() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let with_env = vars(dir.path()).with_settings(
            Some(PathBuf::from("/home/test/geolith/.env")),
            Some(PathBuf::from("/home/test/a&b.json")),
        );
        let plist = render_plist(&with_env);
        let want = "\
    <key>GEOLITH_BIN_SHA256</key>
    <string>9f2c1d4e5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f</string>
    <key>GEOLITH_ENV_FILE</key>
    <string>/home/test/geolith/.env</string>
    <key>GEOLITH_CONFIG</key>
    <string>/home/test/a&amp;b.json</string>
  </dict>";
        assert!(plist.contains(want), "{plist}");
        assert!(!plist.contains("--config"), "{plist}");
        assert!(
            plist.contains("    <string>dataset</string>\n    <string>refresh</string>"),
            "{plist}"
        );
        // Without either, the environment ends at the binary's digest.
        let plain = render_plist(&vars(dir.path()));
        assert!(!plain.contains("GEOLITH_ENV_FILE"), "{plain}");
        assert!(!plain.contains("GEOLITH_CONFIG"), "{plain}");
    }

    #[test]
    fn the_systemd_service_sets_the_env_file_and_quotes_a_path_with_a_space() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let service = render_service(&vars(dir.path()).with_settings(
            Some(PathBuf::from("/home/op/my ops/.env")),
            Some(PathBuf::from("/home/op/geolith.json")),
        ));
        let lines: Vec<&str> = service.lines().collect();
        assert!(
            lines.contains(&"Environment=\"GEOLITH_ENV_FILE=/home/op/my ops/.env\""),
            "{service}"
        );
        assert!(
            lines.contains(&"Environment=GEOLITH_CONFIG=/home/op/geolith.json"),
            "{service}"
        );
        let exec = lines
            .iter()
            .find(|line| line.starts_with("ExecStart="))
            .expect("an ExecStart line");
        assert!(exec.ends_with(" dataset refresh"), "{exec}");
        assert!(!service.contains("--config"), "{service}");
    }

    #[test]
    fn the_install_copies_atomically_and_reports_the_digest_of_the_source() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let from = dir.path().join("geolith");
        fs::write(&from, b"binary").expect("write");
        let to = dir.path().join("bin/geolith");
        let digest = install_binary(&from, &to).expect("install");
        assert_eq!(digest, hex(&sha256_file(&from).expect("sha256")));
        assert_eq!(fs::read(&to).expect("read"), b"binary");
        assert!(!dir.path().join("bin/geolith.part").exists());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let mode = fs::metadata(&to).expect("metadata").permissions().mode();
            assert_eq!(mode & 0o777, 0o755);
        }
    }

    #[test]
    fn status_says_stale_when_the_installed_digest_differs() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let plist = write_plist(dir.path(), &vars(dir.path())).expect("plist");
        let stale = status_lines(
            &plist,
            &dir.path().join("bin/geolith"),
            Some("aaaa"),
            "bbbb",
            &[],
        );
        assert_eq!(stale[0], format!("plist: {} (installed)", plist.display()));
        assert!(stale[1].ends_with("(aaaa, stale)"), "{stale:?}");
        let current = status_lines(
            &plist,
            &dir.path().join("bin/geolith"),
            Some("bbbb"),
            "bbbb",
            &[],
        );
        assert!(current[1].ends_with("(bbbb, current)"), "{current:?}");
        let missing = status_lines(&plist, &dir.path().join("bin/geolith"), None, "bbbb", &[]);
        assert!(missing[1].ends_with("(missing)"), "{missing:?}");
    }

    #[test]
    fn status_reports_an_uninstalled_plist() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let lines = status_lines(
            &dir.path().join("nope.plist"),
            &dir.path().join("bin/geolith"),
            None,
            "x",
            &[],
        );
        assert!(lines[0].ends_with("(not installed)"), "{lines:?}");
    }

    #[test]
    fn the_systemd_units_run_the_binary_at_half_past_eight() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let service = render_service(&vars(dir.path()));
        assert!(service.contains(&format!(
            "ExecStart={} dataset refresh",
            dir.path().join("bin/geolith").display()
        )));
        assert!(service.contains("WorkingDirectory="));
        let timer = render_timer();
        assert!(timer.contains("OnCalendar=*-*-* 08:30:00"), "{timer}");
        assert!(timer.contains("Persistent=true"), "{timer}");
    }
}