eclipse-cli 0.13.4

Command-line interface for eclipse
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
//! `eclipse gateway`: the one long-lived process that keeps the whole thing running.
//!
//! The gateway is the dashboard — `eclipse-web` — with the API, the health readout and the
//! scheduled upgrade check inside it, all under one pid. The unit it installs is a **user**
//! unit in `~/.config/systemd/user`, the same shape `cron install-timer` uses: no root, no
//! system unit, no package. The unit itself runs `eclipse-web`; the CLI's `gateway run` is
//! the foreground spelling of the same thing.
//!
//! Deliberate stop is `eclipse gateway stop` (disable the unit, stop the service): a stop is
//! a fact about the user, not a failure, and a restart-on-failure unit must not fight it.

use crate::ui::Style;
use anyhow::{bail, Result};
use std::path::{Path, PathBuf};
use std::time::Duration;

pub const SERVICE_NAME: &str = "eclipse-gateway.service";

/// Where the unit file is, for a home: `~/.config/systemd/user/eclipse-gateway.service`.
///
/// The one place the name and the shape are written down, so `install`, `start` and `/gateway`
/// cannot look in three different places.
pub(crate) fn unit_path(home: &Path) -> PathBuf {
    home.join(".config")
        .join("systemd")
        .join("user")
        .join(SERVICE_NAME)
}

/// Where a user unit lives: `~/.config/systemd/user`. `pub(crate)` because `/gateway` reads the
/// file the install wrote, and asking this module for the path is what keeps the two in step.
pub(crate) fn units_dir() -> Result<PathBuf> {
    let home = std::env::var("HOME").unwrap_or_else(|_| "".into());
    if home.is_empty() {
        bail!("HOME is not set");
    }
    Ok(unit_path(Path::new(&home))
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from(&home)))
}

/// The unit text. `Restart=always` is the point: a crash must not strand the dashboard.
/// `SuccessExitStatus` is not used — a deliberate stop is `systemctl stop`, which is not a
/// restart trigger.
///
/// The profile and the config path ride in `Environment=`, not in `ExecStart`: the gateway reads
/// both from the environment already (`ECLIPSE_PROFILE`, `ECLIPSE_CONFIG`), and a systemd value
/// quoted as one string survives a path with a space, which an unquoted argv does not.
fn unit_text(gateway_bin: &Path, docs: &Path, env: &[(String, String)]) -> String {
    let environment: String = env
        .iter()
        .map(|(key, value)| format!("Environment=\"{key}={value}\"\n"))
        .collect();
    format!(
        "[Unit]\n\
         Description=Eclipse gateway — dashboard and API on one pid\n\
         Documentation=file:{}\n\
         \n\
         [Service]\n\
         Type=simple\n\
         {environment}ExecStart={}\n\
         Restart=always\n\
         RestartSec=5\n\
         \n\
         [Install]\n\
         WantedBy=default.target\n",
        docs.display(),
        systemd_word(gateway_bin)
    )
}

/// The `ECLIPSE_*` settings the gateway has to be given to serve the profile that was named.
///
/// `--profile` and `--config` are the same two settings spelled as flags, and a user unit inherits
/// nothing from the shell that installed it — so an install that drops them serves whatever the
/// default happens to be, under the name of a profile the person thinks they installed. A relative
/// config path is made absolute here, because the unit's working directory is not this one.
fn service_env(profile: Option<&str>, config: Option<&Path>) -> Vec<(String, String)> {
    let mut env = Vec::new();
    if let Some(profile) = profile {
        env.push(("ECLIPSE_PROFILE".to_string(), profile.to_string()));
    }
    if let Some(config) = config {
        let absolute = if config.is_absolute() {
            config.to_path_buf()
        } else {
            std::env::current_dir()
                .map(|cwd| cwd.join(config))
                .unwrap_or_else(|_| config.to_path_buf())
        };
        env.push(("ECLIPSE_CONFIG".to_string(), absolute.display().to_string()));
    }
    env
}

/// The `eclipse-gateway` binary the unit invokes: the sibling of the `eclipse` this process is.
/// Same install, same directory, same version — never a guess.
pub fn web_bin() -> Result<PathBuf> {
    let exe = std::env::current_exe()
        .map_err(|e| anyhow::anyhow!("cannot find this program to point the unit at: {e}"))?;
    let sibling = exe.with_file_name("eclipse-gateway");
    if sibling.is_file() {
        return Ok(sibling);
    }
    bail!(
        "no eclipse-gateway next to {}; re-run install.sh so the install has the gateway binary",
        exe.display()
    )
}

/// `eclipse gateway run`: the foreground spelling of what the unit does, in this terminal.
///
/// The same `ECLIPSE_*` the unit carries are set here, so "run it now" and "install it" serve the
/// same profile — that is the promise the two spellings make to each other.
pub fn run(profile: Option<&str>, config: Option<&Path>) -> Result<()> {
    let bin = web_bin()?;
    let mut command = std::process::Command::new(&bin);
    for (key, value) in service_env(profile, config) {
        command.env(key, value);
    }
    use std::os::unix::process::CommandExt;
    // `exec` replaces this process when it works; it returns only when it could not.
    let err = command.exec();
    bail!("could not start {}: {err}", bin.display())
}

/// `eclipse gateway install`: write the unit and enable it.
pub fn install(style: &Style, profile: Option<&str>, config: Option<&Path>) -> Result<()> {
    let gateway = web_bin()?;
    let dir = units_dir()?;
    std::fs::create_dir_all(&dir)?;
    let home = std::env::var("HOME").unwrap_or_else(|_| "".into());
    let docs = PathBuf::from(&home)
        .join(".eclipse")
        .join("docs")
        .join("USER.md");
    let service_path = dir.join(SERVICE_NAME);
    let env = service_env(profile, config);
    std::fs::write(&service_path, unit_text(&gateway, &docs, &env))?;
    println!("{} {}", style.green("wrote"), service_path.display());
    // Named, because this is what the unit will serve — an install that quietly served the default
    // profile was the whole defect.
    for (key, value) in &env {
        println!("{} {key}={value}", style.dim("  pinned"));
    }

    // `enable --now` on a unit that is already active is a no-op: systemd has nothing to start, so
    // the process that keeps serving is the one launched from the *previous* unit and the previous
    // binary, while this command reports the freshly written unit as up (`#603`).
    let was_active = is_active();
    let ran = std::process::Command::new("systemctl")
        .args(["--user", "daemon-reload"])
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
        && std::process::Command::new("systemctl")
            .args(["--user", "enable", "--now", SERVICE_NAME])
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
    if ran {
        if was_active {
            // The unit changed, so the process has to. Only when it was already running: an
            // inactive unit was just started by `enable --now`, and restarting that is a bounce
            // nobody asked for.
            let restarted = std::process::Command::new("systemctl")
                .args(["--user", "restart", SERVICE_NAME])
                .status()
                .map(|s| s.success())
                .unwrap_or(false);
            if !restarted {
                bail!(
                    "the unit was rewritten and enabled, but the running gateway could not be \
                     restarted, so it is still serving the old one; by hand:\n  \
                     systemctl --user restart {SERVICE_NAME}\n  \
                     journalctl --user -u {SERVICE_NAME} --no-pager -n 30"
                );
            }
            println!("{} {}", style.green("restarted"), SERVICE_NAME);
            println!(
                "{}",
                style.dim("  the unit changed, so the running process was replaced by this build")
            );
        } else {
            println!("{} {}", style.green("enabled"), SERVICE_NAME);
        }
        println!(
            "{}",
            style.dim(
                "  `systemctl --user status eclipse-gateway` shows one pid serving the dashboard and the API; \
                 `journalctl --user -u eclipse-gateway.service` shows the log"
            )
        );
        println!(
            "{}",
            style.dim(&format!(
                "  the unit runs `{}` — re-install after an upgrade with `eclipse gateway install`",
                gateway.display()
            ))
        );
        println!(
            "{}",
            style.dim(
                "  to run while you are logged out: loginctl enable-linger $USER (needs root)"
            )
        );
    } else {
        println!(
            "{}",
            style.yellow("systemctl did not take it; enable it by hand with:")
        );
        println!("  systemctl --user daemon-reload");
        println!("  systemctl --user enable --now {SERVICE_NAME}");
        // The unit file is on disk but nothing runs it: a half-install. Printing that and exiting 0
        // told a provisioning script everything was fine.
        bail!(
            "the unit is written to {} but systemctl did not enable it — run the two commands above",
            service_path.display()
        );
    }
    Ok(())
}

/// Where the unit file is, when it is installed. Callers that have to decide *before* printing a
/// plan (an upgrade that would restart it, a status that explains which command is missing) ask
/// this rather than re-deriving the path from the environment.
pub fn installed_unit() -> Option<PathBuf> {
    let dir = units_dir().ok()?;
    let path = dir.join(SERVICE_NAME);
    path.exists().then_some(path)
}

/// `eclipse gateway restart`: restart the unit, and touch nothing about whether it is enabled.
///
/// Not stop-then-start. `stop` is `disable --now`, so composing restart out of those two verbs
/// would disable the gateway on the way past and leave the next boot without one.
pub fn restart(style: &Style) -> Result<()> {
    let service_path = units_dir()?.join(SERVICE_NAME);
    if !service_path.exists() {
        bail!(
            "no unit at {} — `eclipse gateway install` writes one and enables it",
            service_path.display()
        );
    }
    // `systemctl restart` on a stopped unit starts it. That is not what "restart" means when
    // someone stopped the gateway on purpose, so the verb says which of the two it did.
    let was_active = is_active();
    let took_it = std::process::Command::new("systemctl")
        .args(["--user", "restart", SERVICE_NAME])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !took_it {
        bail!(
            "systemctl could not restart {SERVICE_NAME}; it may still be running the old binary — \
             `journalctl --user -u {SERVICE_NAME} --no-pager -n 30` says why"
        );
    }
    match wait_active(Duration::from_secs(10)) {
        Some(ms) => {
            let verb = if was_active { "restarted" } else { "started" };
            println!(
                "{} {} (active after {ms} ms)",
                style.green(verb),
                SERVICE_NAME
            );
            Ok(())
        }
        None => bail!(
            "{SERVICE_NAME} was restarted but is not active after 10s — \
             `journalctl --user -u {SERVICE_NAME} --no-pager -n 30` says why"
        ),
    }
}

/// `systemctl --user is-active` answering `active`, for callers that already have a [`Runner`].
pub(crate) fn is_active_text(stdout: &str) -> bool {
    stdout.trim() == "active"
}

/// `eclipse gateway stop`: stop the service and disable it. A deliberate stop stays stopped.
pub fn stop(style: &Style) -> Result<()> {
    let took_it = std::process::Command::new("systemctl")
        .args(["--user", "disable", "--now", SERVICE_NAME])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !took_it {
        // The exit status was ignored here, so a failed stop printed a green "stopped and disabled"
        // over a gateway that was still running and still reachable.
        bail!(
            "systemctl could not stop {SERVICE_NAME}; it may still be running — \
             `eclipse gateway status` and `journalctl --user -u {SERVICE_NAME}` say what happened"
        );
    }
    println!("{} {}", style.green("stopped and disabled"), SERVICE_NAME);
    // `disable --now` is a one-way door: `systemctl start` brings it back for this boot only, and
    // the unit is still disabled. The line that says how to undo what just happened costs nothing
    // and is the whole reason the `start` verb exists.
    println!(
        "{}",
        style.dim("  to bring it back, and keep it coming back: eclipse gateway start")
    );
    Ok(())
}

/// `eclipse gateway start`: enable the service and start it — the exact inverse of `stop`.
///
/// `stop` is `disable --now`, so a bare `systemctl --user start` afterwards comes back for the
/// current boot and is gone after the next reboot. This is the verb that restores both halves,
/// which is what makes the pair symmetrical instead of a one-way door.
///
/// The unit file is *not* rewritten here. Re-installing is a different decision — it takes the
/// `--profile`/`--config` the user has to choose — so a missing unit is a refusal that names
/// `install`, not an implicit install.
pub fn start(style: &Style) -> Result<()> {
    let service_path = units_dir()?.join(SERVICE_NAME);
    if !service_path.exists() {
        bail!(
            "no unit at {} — `eclipse gateway install` writes one and enables it",
            service_path.display()
        );
    }
    // Already running is not a failure. A start that exits non-zero because the thing was up is
    // a bug a script would trip over.
    if is_active() {
        // Up is not the same as enabled. An active unit that was never enabled looks fine until the
        // machine restarts and then nothing is there, so "nothing to do" was only ever true with
        // both halves. No `--now` on the enable: the process is already running, and bouncing it
        // here would drop in-flight requests for no gain (`#603`).
        if is_enabled() == Some(true) {
            println!(
                "{} {}",
                style.green("already up; nothing to do"),
                SERVICE_NAME
            );
            return Ok(());
        }
        let enabled = std::process::Command::new("systemctl")
            .args(["--user", "enable", SERVICE_NAME])
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        if !enabled {
            bail!(
                "{SERVICE_NAME} is running but not enabled, so it would not survive a reboot, and \
                 systemctl would not enable it; by hand:\n  \
                 systemctl --user enable {SERVICE_NAME}"
            );
        }
        println!(
            "{} {}",
            style.green("already up; enabled it so it survives a reboot"),
            SERVICE_NAME
        );
        return Ok(());
    }
    let took_it = std::process::Command::new("systemctl")
        .args(["--user", "enable", "--now", SERVICE_NAME])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !took_it {
        bail!(
            "systemctl could not enable {SERVICE_NAME}; by hand:\n  \
             systemctl --user enable --now {SERVICE_NAME}\n  \
             journalctl --user -u {SERVICE_NAME} --no-pager -n 30"
        );
    }
    // Enabled is not started: systemd returning success means it accepted the job, not that the
    // process came up. Watch the unit settle rather than reporting a green over a crash loop.
    match wait_active(Duration::from_secs(10)) {
        Some(ms) => {
            println!(
                "{} {} (active after {ms} ms)",
                style.green("started and enabled"),
                SERVICE_NAME
            );
            println!(
                "{}",
                style.dim("  status: eclipse gateway status   ·   down: eclipse gateway stop")
            );
            Ok(())
        }
        None => bail!(
            "{SERVICE_NAME} was enabled but is not active after 10s — \
             `journalctl --user -u {SERVICE_NAME} --no-pager -n 30` says why"
        ),
    }
}

/// `systemctl --user is-active` answering `active`.
fn is_active() -> bool {
    std::process::Command::new("systemctl")
        .args(["--user", "is-active", SERVICE_NAME])
        .output()
        .map(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).trim() == "active")
        .unwrap_or(false)
}

/// `systemctl --user is-enabled` answering `enabled`.
fn is_enabled() -> Option<bool> {
    std::process::Command::new("systemctl")
        .args(["--user", "is-enabled", SERVICE_NAME])
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "enabled")
}

/// Poll `is-active` until it reports up or `budget` runs out, returning how long it took.
fn wait_active(budget: Duration) -> Option<u128> {
    let started = std::time::Instant::now();
    loop {
        if is_active() {
            return Some(started.elapsed().as_millis());
        }
        if started.elapsed() >= budget {
            return None;
        }
        std::thread::sleep(Duration::from_millis(100));
    }
}

/// `eclipse gateway uninstall`: stop, disable, remove the unit.
pub fn uninstall(style: &Style) -> Result<()> {
    // Stopping first is the intent, but refusing to remove the unit because systemctl is
    // unavailable leaves the files behind and fixes nothing. Remove them, then report the stop.
    let stopped = stop(style);
    let path = units_dir()?.join(SERVICE_NAME);
    if path.exists() {
        std::fs::remove_file(&path)?;
        println!("{} {}", style.green("removed"), path.display());
    }
    let _ = std::process::Command::new("systemctl")
        .args(["--user", "daemon-reload"])
        .status();
    // The unit is gone, so it cannot come back on its own — but a process may still be running, and
    // a green exit would hide it.
    stopped
}

/// `eclipse gateway install --help`-style status line: is the service up?
pub fn status(style: &Style) -> Result<()> {
    let out = std::process::Command::new("systemctl")
        .args(["--user", "is-active", SERVICE_NAME])
        .output();
    match out {
        Ok(o) => {
            let stdout = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if o.status.success() && stdout == "active" {
                println!("{}", style.green("eclipse-gateway is up"));
                let _ = std::process::Command::new("systemctl")
                    .args([
                        "--user",
                        "status",
                        SERVICE_NAME,
                        "--no-pager",
                        "--lines",
                        "20",
                    ])
                    .status();
            } else {
                // The unit's own answer first, in systemctl's word: that is the line a script or
                // a reader greps for. Then what it means, because `is-active` alone cannot tell
                // the two ways a gateway can be down apart — and they need different commands.
                println!("{} {}", style.dim("eclipse-gateway:"), stdout);
                let installed = units_dir()
                    .map(|d| d.join(SERVICE_NAME).exists())
                    .unwrap_or(false);
                if !installed {
                    println!(
                        "{}",
                        style.dim("  not installed — `eclipse gateway install` writes the unit")
                    );
                } else {
                    let enabled = match is_enabled() {
                        Some(true) => "enabled",
                        Some(false) => "disabled",
                        None => "enablement unknown",
                    };
                    println!(
                        "{}",
                        style.dim(&format!(
                            "  installed, unit is {enabled} — `eclipse gateway start` brings it back"
                        ))
                    );
                }
                // A status subcommand exists so a script can branch on it: `is-active` answering
                // `inactive`/`failed` (exit 3/4) is a real answer, not a success. `doctor` and
                // `cron run` already propagate their failure — this one printed and exited 0.
                std::process::exit(1);
            }
        }
        Err(e) => bail!("systemctl did not answer: {e}"),
    }
    Ok(())
}

/// A path as one systemd word.
///
/// systemd splits `ExecStart` on whitespace, so an install under `~/My Apps/eclipse` produced a unit
/// that failed 203/EXEC — and `Restart=always` turned that into a crash loop instead of one clear
/// failure. Quoting is systemd's own: the whole word in double quotes, with `"` and `\` escaped.
pub(crate) fn systemd_word(path: &std::path::Path) -> String {
    let raw = path.display().to_string();
    let mut out = String::with_capacity(raw.len() + 2);
    out.push('"');
    for c in raw.chars() {
        if c == '"' || c == '\\' {
            out.push('\\');
        }
        out.push(c);
    }
    out.push('"');
    out
}

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

    #[test]
    fn the_unit_points_at_the_gateway_binary_and_restarts() {
        let path = Path::new("/usr/local/bin/eclipse-gateway");
        let docs = Path::new("/home/x/.eclipse/docs/USER.md");
        let text = unit_text(path, docs, &[]);
        assert!(
            text.contains("ExecStart=\"/usr/local/bin/eclipse-gateway\""),
            "{text}"
        );
        assert!(text.contains("Restart=always"));
        assert!(text.contains("WantedBy=default.target"));
        // A plain install pins nothing: the gateway then reads the configured default.
        assert!(!text.contains("Environment="), "{text}");
    }

    /// The profile named on the command line is the profile the unit serves. A user unit inherits
    /// nothing from the shell that wrote it, so dropping the flag installed the default under
    /// another name.
    #[test]
    fn the_unit_carries_the_profile_and_the_config_it_was_installed_for() {
        let path = Path::new("/usr/local/bin/eclipse-gateway");
        let docs = Path::new("/home/x/.eclipse/docs/USER.md");
        let env = service_env(Some("work"), Some(Path::new("/srv/eclipse/work.toml")));
        let text = unit_text(path, docs, &env);
        assert!(
            text.contains("Environment=\"ECLIPSE_PROFILE=work\"\n"),
            "{text}"
        );
        assert!(
            text.contains("Environment=\"ECLIPSE_CONFIG=/srv/eclipse/work.toml\"\n"),
            "{text}"
        );
        // In the environment, not the argv: `ExecStart` stays the bare binary, as the test above
        // pins, and a value with a space needs no quoting of its own.
        assert!(
            text.contains("ExecStart=\"/usr/local/bin/eclipse-gateway\"\n"),
            "{text}"
        );
    }

    /// systemd splits `ExecStart` on whitespace, so an install under a path with a space produced a
    /// unit that failed 203/EXEC — and `Restart=always` turned that into a crash loop. The path is
    /// one quoted word now, and a quote or backslash inside it is escaped the way systemd expects.
    #[test]
    fn a_path_with_spaces_or_quotes_survives_as_one_word() {
        let spaced = Path::new("/home/ann/My Apps/eclipse/bin/eclipse-gateway");
        let docs = Path::new("/home/ann/My Apps/eclipse/docs/USER.md");
        let text = unit_text(spaced, docs, &[]);
        assert!(
            text.contains("ExecStart=\"/home/ann/My Apps/eclipse/bin/eclipse-gateway\""),
            "the path is one quoted word: {text}"
        );

        let odd = Path::new("/tmp/we\"ird\\dir/eclipse-gateway");
        assert_eq!(
            systemd_word(odd),
            "\"/tmp/we\\\"ird\\\\dir/eclipse-gateway\""
        );
        // A plain path gains nothing but the quotes.
        assert_eq!(
            systemd_word(Path::new("/usr/local/bin/x")),
            "\"/usr/local/bin/x\""
        );
    }

    /// A profile on its own is a complete claim; the config keeps whatever the loader picks.
    #[test]
    fn a_profile_alone_pins_only_the_profile() {
        let env = service_env(Some("work"), None);
        assert_eq!(
            env,
            vec![("ECLIPSE_PROFILE".to_string(), "work".to_string())]
        );
    }

    /// The unit's working directory is not this one, so a relative `--config` has to be resolved
    /// before it is written down — otherwise the unit reads a different file, or none.
    #[test]
    fn a_relative_config_path_is_made_absolute() {
        let env = service_env(None, Some(Path::new("conf/eclipse.toml")));
        assert_eq!(env.len(), 1);
        assert_eq!(env[0].0, "ECLIPSE_CONFIG");
        let written = Path::new(&env[0].1);
        assert!(written.is_absolute(), "{}", env[0].1);
        assert!(written.ends_with("conf/eclipse.toml"), "{}", env[0].1);
    }
}