gitpoulpi-config 1.4.0

GitPoulpi config schema, TOML load/save, defaults, and OS-correct path resolution.
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
//! Desktop integration: shortcuts that start GitPoulpi from the OS launcher
//! (Settings > General, `gitpoulpi desktop shortcut`).
//!
//! | OS | Launcher | Desktop |
//! |---|---|---|
//! | Linux | `~/.local/share/applications/gitpoulpi.desktop` + hicolor icon | `~/Desktop/gitpoulpi.desktop` |
//! | Windows | Start menu `GitPoulpi.lnk` | Desktop `GitPoulpi.lnk` |
//! | macOS | `~/Applications/GitPoulpi.app` | - |
//!
//! Every file we write carries the marker [`MARKER`]; Remove and Update only
//! touch files that do. Every directory is injected through [`Dirs`], so the
//! tests (and a hand run) never touch the real home. Nothing here may run on
//! the UI thread: Windows spawns PowerShell, every OS does file I/O.

pub mod alias;
pub mod folder_menu;
pub mod icons;
mod linux;
mod macos;
pub mod owner;
pub mod path;
pub mod registry;
pub mod terminals;
mod windows;

use std::path::{Path, PathBuf};

pub use icons::IconSet;
pub use linux::{entry_text, entry_text_with_action, exec_quote};
pub use macos::sh_quote;
pub use windows::quote_arg;

use crate::open_in::Os;

/// Written into everything we create; its presence is what allows removal.
pub const MARKER: &str = "X-GitPoulpi=1";

/// The owner tag: `X-GitPoulpi-Install=<id>` names the installation an
/// artifact belongs to ([`owner::decide`]). Only the primary also writes the
/// legacy [`MARKER`], the one old builds look for.
pub const OWNER_TAG: &str = "X-GitPoulpi-Install";

/// Another installation known from the config, and whether its exe is still there.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KnownInstall {
    pub id: String,
    pub exists: bool,
}

/// Who is writing: the running installation, as the artifact writers and
/// [`owner::decide`] need it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallCtx {
    /// The installation id ([`crate::installation::Identity::id`]).
    pub id: String,
    /// `i<8hex>`, for file names, classes and GTK ids.
    pub short: String,
    /// The launcher name.
    pub name: String,
    /// The id of the primary installation, `None` while nobody is.
    pub primary: Option<String>,
    /// Every installation of the config.
    pub known: Vec<KnownInstall>,
    /// Which installation each alias name belongs to by the config (name,
    /// installation id): decides who owns an untagged legacy alias file.
    pub alias_claims: Vec<(String, String)>,
}

impl InstallCtx {
    /// Today's behaviour: the running installation is the only one and owns
    /// the legacy names. What the writers still assume until later slices
    /// switch them over.
    pub fn sole(identity: &crate::installation::Identity) -> Self {
        Self {
            id: identity.id.clone(),
            short: identity.short(),
            name: crate::installation::PRIMARY_NAME.to_string(),
            primary: Some(identity.id.clone()),
            known: Vec::new(),
            alias_claims: Vec::new(),
        }
    }

    /// [`InstallCtx::sole`] without an identity (tests, fakes).
    pub fn legacy() -> Self {
        Self::sole(&crate::installation::Identity {
            id: String::new(),
            kind: crate::Kind::default(),
            root: String::new(),
            channel: None,
        })
    }

    /// One shared [`InstallCtx::legacy`], for a `Request` that must borrow it.
    pub fn legacy_ref() -> &'static InstallCtx {
        static LEGACY: std::sync::OnceLock<InstallCtx> = std::sync::OnceLock::new();
        LEGACY.get_or_init(InstallCtx::legacy)
    }

    /// From the config: the effective name, the primary and every entry;
    /// `exists(path)` tells whether an installation's folder is still there.
    pub fn from_config(
        config: &crate::Config,
        identity: &crate::installation::Identity,
        exists: &dyn Fn(&str) -> bool,
    ) -> Self {
        let eff = crate::installation::effective(config, identity);
        Self {
            id: identity.id.clone(),
            short: identity.short(),
            name: eff.name,
            primary: config.installation.primary.clone(),
            known: config
                .installation
                .settings
                .iter()
                .map(|(id, e)| KnownInstall {
                    id: id.clone(),
                    exists: exists(&e.path),
                })
                .collect(),
            alias_claims: crate::installation::alias_claims(config),
        }
    }

    /// The installation the config gives the alias `name` to, if any.
    pub fn alias_claimed_by(&self, name: &str) -> Option<&str> {
        self.alias_claims
            .iter()
            .find(|(n, _)| n.eq_ignore_ascii_case(name))
            .map(|(_, id)| id.as_str())
    }

    /// Is the running installation the primary?
    pub fn is_primary(&self) -> bool {
        self.primary.as_deref() == Some(self.id.as_str())
    }
}

/// Where a shortcut goes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Place {
    /// The app launcher: the Linux `.desktop` entry, the macOS bundle.
    Launcher,
    /// The Desktop folder.
    Desktop,
    /// The Windows Start menu.
    StartMenu,
}

impl Place {
    pub fn as_str(self) -> &'static str {
        match self {
            Place::Launcher => "launcher",
            Place::Desktop => "desktop",
            Place::StartMenu => "startmenu",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "launcher" => Some(Place::Launcher),
            "desktop" => Some(Place::Desktop),
            "startmenu" => Some(Place::StartMenu),
            _ => None,
        }
    }

    /// The places `os` offers, in the order Settings lists them.
    pub fn for_os(os: Os) -> &'static [Place] {
        match os {
            Os::Linux => &[Place::Launcher, Place::Desktop],
            Os::Windows => &[Place::StartMenu, Place::Desktop],
            Os::Macos => &[Place::Launcher],
        }
    }
}

/// What is there now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    NotInstalled,
    /// Ours and matching the current exe and terminal.
    Installed,
    /// Ours, but the exe moved or another terminal is chosen: Update fixes it.
    Outdated,
    /// A file of that name exists and is not ours; it is left alone.
    Foreign,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Status {
    pub state: State,
    /// The icon file differs from the current one (the logo color changed).
    pub icon_stale: bool,
}

/// Every directory the module writes to.
#[derive(Debug, Clone, Default)]
pub struct Dirs {
    /// Linux: `<data>/applications`.
    pub applications: PathBuf,
    /// Linux: `<data>/icons/hicolor`.
    pub icon_root: PathBuf,
    /// The Desktop folder, when there is one.
    pub desktop: Option<PathBuf>,
    /// Windows: the user's Start menu `Programs` folder.
    pub start_menu: Option<PathBuf>,
    /// macOS: `~/Applications`.
    pub mac_apps: PathBuf,
    /// Windows: where the `.ico` the shortcuts point at is kept.
    pub assets: PathBuf,
    /// Windows: `User Pinned\TaskBar`, where Explorer keeps a copy of every
    /// shortcut pinned to the taskbar.
    pub taskbar_pinned: Option<PathBuf>,
    /// Windows: `User Pinned\ImplicitAppShortcuts`, the copies Explorer keeps
    /// (one folder deep) for pins it matched by AppUserModelID.
    pub implicit_pinned: Option<PathBuf>,
}

impl Dirs {
    /// The real directories for `os`, from the environment. Looks at the
    /// disk (is the Desktop folder there), so not on the UI thread.
    pub fn discover(os: Os, env: &dyn Fn(&str) -> Option<String>, home: &Path) -> Dirs {
        let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
        match os {
            Os::Linux => {
                let data = var("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"));
                let config = var("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config"));
                Dirs {
                    applications: data.join("applications"),
                    icon_root: data.join("icons/hicolor"),
                    desktop: linux::desktop_dir(home, &config),
                    ..Dirs::default()
                }
            }
            Os::Windows => {
                let profile = var("USERPROFILE").unwrap_or_else(|| home.to_path_buf());
                let one_drive = profile.join("OneDrive").join("Desktop");
                let desktop = if one_drive.is_dir() {
                    one_drive
                } else {
                    profile.join("Desktop")
                };
                let appdata = var("APPDATA").unwrap_or_else(|| profile.join("AppData/Roaming"));
                Dirs {
                    desktop: Some(desktop),
                    start_menu: Some(appdata.join("Microsoft/Windows/Start Menu/Programs")),
                    taskbar_pinned: Some(
                        appdata
                            .join("Microsoft/Internet Explorer/Quick Launch/User Pinned/TaskBar"),
                    ),
                    implicit_pinned: Some(appdata.join(
                        "Microsoft/Internet Explorer/Quick Launch/User Pinned/ImplicitAppShortcuts",
                    )),
                    assets: var("LOCALAPPDATA")
                        .unwrap_or_else(|| profile.join("AppData/Local"))
                        .join("GitPoulpi"),
                    ..Dirs::default()
                }
            }
            Os::Macos => Dirs {
                mac_apps: home.join("Applications"),
                ..Dirs::default()
            },
        }
    }

    /// The places that make sense here (a Linux box without a Desktop
    /// folder has no Desktop row).
    pub fn places(&self, os: Os) -> Vec<Place> {
        Place::for_os(os)
            .iter()
            .copied()
            .filter(|p| *p != Place::Desktop || self.desktop.is_some())
            .collect()
    }
}

/// What a shortcut should start.
#[derive(Debug, Clone, Copy)]
pub struct Request<'a> {
    pub os: Os,
    /// The absolute path of GitPoulpi's executable.
    pub exe: &'a Path,
    /// A terminal id of [`terminals`], already resolved (not `auto`).
    pub terminal: &'a str,
    /// Windows: the terminal's absolute path, when found on `PATH`.
    pub terminal_exe: Option<&'a Path>,
    /// The program that runs `launch` ([`terminals::launch_helper`]): the
    /// shortcut starts it, and it shows the window of a GitPoulpi that is
    /// already open or else runs the terminal command. `None`: the shortcut
    /// runs the terminal command itself.
    pub launch_exe: Option<&'a Path>,
    /// Dev mode with `ui.launcher_build = "newest"`
    /// ([`crate::dev_mode::launcher_newest`]): a shortcut naming the `dist`
    /// or the `release` build of this checkout's exe is up to date (starting
    /// either build never rewrites it), and what [`install`] writes names the
    /// newest build. `launch` swaps in the newest build again at click time.
    pub newest: bool,
    pub icons: &'a IconSet,
    /// Who writes (names, tags, classes). Not read by the writers yet.
    pub ctx: &'a InstallCtx,
    /// Linux: run `gtk-update-icon-cache` after writing the icon. Off in tests.
    pub refresh_icon_cache: bool,
}

pub fn status(place: Place, dirs: &Dirs, req: &Request) -> Status {
    if req.newest && req.os != Os::Windows {
        // Linux / macOS compare whole files: accept the one the other build
        // would have written. (Windows searches the file for the paths.)
        let mut first = None;
        for (exe, launch) in variants(req) {
            let r = Request {
                exe: &exe,
                launch_exe: launch.as_deref(),
                ..*req
            };
            let st = status_of(place, dirs, &r);
            if st.state == State::Installed {
                return st;
            }
            first.get_or_insert(st);
        }
        return first.unwrap_or_else(|| status_of(place, dirs, req));
    }
    status_of(place, dirs, req)
}

fn status_of(place: Place, dirs: &Dirs, req: &Request) -> Status {
    match req.os {
        Os::Linux => linux::status(place, dirs, req),
        Os::Windows => windows::status(place, dirs, req),
        Os::Macos => macos::status(place, dirs, req),
    }
}

/// `(exe, launch_exe)` as each build of the checkout would write them.
fn variants(req: &Request) -> Vec<(PathBuf, Option<PathBuf>)> {
    let exes = crate::dev_mode::build_variants(req.exe);
    let launches = req.launch_exe.map(crate::dev_mode::build_variants);
    exes.into_iter()
        .enumerate()
        .map(|(i, exe)| {
            let launch = match (&launches, req.launch_exe) {
                (Some(l), _) if l.len() == 2 => Some(l[i.min(1)].clone()),
                (_, l) => l.map(Path::to_path_buf),
            };
            (exe, launch)
        })
        .collect()
}

/// The request with the newest builds of the exe and the launch helper.
fn newest_paths(req: &Request) -> (PathBuf, Option<PathBuf>) {
    (
        crate::dev_mode::newest_build(req.exe),
        req.launch_exe.map(crate::dev_mode::newest_build),
    )
}

/// Creates or rewrites the shortcut; returns what was written.
pub fn install(place: Place, dirs: &Dirs, req: &Request) -> Result<PathBuf, String> {
    if req.newest {
        let (exe, launch) = newest_paths(req);
        let r = Request {
            exe: &exe,
            launch_exe: launch.as_deref(),
            ..*req
        };
        return install_of(place, dirs, &r);
    }
    install_of(place, dirs, req)
}

fn install_of(place: Place, dirs: &Dirs, req: &Request) -> Result<PathBuf, String> {
    match req.os {
        Os::Linux => linux::install(place, dirs, req),
        Os::Windows => windows::install(place, dirs, req),
        Os::Macos => macos::install(place, dirs, req),
    }
}

/// Windows: rewrites the command line of our copies pinned to the taskbar
/// (they keep what the shortcut said when the user pinned it, possibly before
/// `--launcher` existed). `false` elsewhere or when nothing needed it.
pub fn sync_pinned(dirs: &Dirs, req: &Request) -> bool {
    if req.os != Os::Windows {
        return false;
    }
    if req.newest {
        let (exe, launch) = newest_paths(req);
        let r = Request {
            exe: &exe,
            launch_exe: launch.as_deref(),
            ..*req
        };
        return windows::sync_pinned_args(dirs, &r);
    }
    windows::sync_pinned_args(dirs, req)
}

/// Deletes the shortcut if it is ours. `Ok(false)`: there was none.
pub fn remove(place: Place, dirs: &Dirs, os: Os, ctx: &InstallCtx) -> Result<bool, String> {
    match os {
        Os::Linux => linux::remove(place, dirs, ctx),
        Os::Windows => windows::remove(place, dirs, ctx),
        Os::Macos => macos::remove(place, dirs, ctx),
    }
}

/// Rewrites only the icon file (the logo color changed): cheap, no spawn.
///
/// The OS shows the new color without touching the shortcut: Linux
/// (`gtk-update-icon-cache`, in `write_icon`), macOS (the bundle's mtime is
/// bumped so Finder re-reads the `.icns`) and Windows. There the taskbar
/// caches an icon by its path, so the `.ico` file name carries a hash of the
/// icon: the new file is written, every shortcut of ours (Start menu,
/// Desktop, the copies in `User Pinned\TaskBar`) is re-pointed at it and the
/// shell told, then older files nothing points at are deleted
/// (`windows::refresh_icon`).
pub fn refresh_icon(dirs: &Dirs, req: &Request) -> Result<(), String> {
    match req.os {
        Os::Linux => linux::write_icon(dirs, req),
        Os::Windows => windows::refresh_icon(dirs, req),
        Os::Macos => {
            macos::write_icon(dirs, req)?;
            macos::touch_bundle(dirs, req.ctx);
            Ok(())
        }
    }
}

/// Windows: the `.ico` for `icons` (its name carries a hash of the picture),
/// which the shortcuts point at and the running GitPoulpi also puts on its
/// terminal window.
pub fn ico_path(dirs: &Dirs, icons: &IconSet) -> PathBuf {
    windows::ico_path(dirs, icons)
}

/// [`ico_path`] for `ctx`: the primary keeps `gitpoulpi-<hash>.ico`, every
/// other installation gets `gitpoulpi-i<8hex>-<hash>.ico`.
pub fn ico_path_for(dirs: &Dirs, icons: &IconSet, ctx: &InstallCtx) -> PathBuf {
    windows::ico_path_for(dirs, icons, ctx)
}

/// Deletes the icons `ctx` wrote once it keeps no shortcut of its own and
/// nothing else (a pin, a legacy `GitPoulpi.lnk`, another place's entry) still
/// names them: what a primary handover (the one that resigns, or the one that
/// takes over from its own names) and an uninstall leave behind when no
/// shortcut was there to carry the cleanup. Another installation's icons stay.
pub fn release_icons(dirs: &Dirs, os: Os, ctx: &InstallCtx) {
    match os {
        Os::Windows => windows::release_icons(dirs, ctx),
        Os::Linux => linux::release_icons(dirs, ctx),
        Os::Macos => {}
    }
}

/// [`ensure_ico`] for `ctx`.
pub fn ensure_ico_for(dirs: &Dirs, icons: &IconSet, ctx: &InstallCtx) -> Option<PathBuf> {
    windows::ensure_ico(dirs, icons, ctx)
}

/// Windows and Linux, primary handover: renames the old primary's legacy-named
/// shortcuts (Start menu, Desktop) to its own name, contents untouched, and
/// tells the shell. `old` is the installation that was primary. Elsewhere, and
/// when there is nothing to rename: an empty list.
pub fn hand_over_shortcuts(dirs: &Dirs, os: Os, old: &InstallCtx) -> Result<Vec<PathBuf>, String> {
    match os {
        Os::Windows => windows::hand_over(dirs, old),
        Os::Linux => linux::hand_over(dirs, old),
        Os::Macos => Ok(Vec::new()),
    }
}

/// Renames `from`'s shortcuts (Start menu, Desktop, the Linux entry) to the
/// names `to` uses, `to` being the same installation in its new role (it became
/// the primary, or stopped being it). Contents untouched and nothing removed
/// first: the shortcut is always there, and the install or sync that follows
/// rewrites it. Only `from`'s own files move. Returns the new paths; macOS
/// bundles are not renamed (an empty list).
pub fn rename_shortcuts(
    dirs: &Dirs,
    os: Os,
    from: &InstallCtx,
    to: &InstallCtx,
) -> Result<Vec<PathBuf>, String> {
    match os {
        Os::Windows => windows::rename(dirs, from, to),
        Os::Linux => linux::rename_entries(dirs, from, to),
        Os::Macos => Ok(Vec::new()),
    }
}

/// Windows: makes sure the `.ico` for `icons` exists and returns its path
/// (`None` for no icons or when it cannot be written).
pub fn ensure_ico(dirs: &Dirs, icons: &IconSet) -> Option<PathBuf> {
    windows::ensure_ico(dirs, icons, InstallCtx::legacy_ref())
}

/// Writes `bytes`, creating parents; `executable` sets mode 755 on Unix.
fn write_file(path: &Path, bytes: &[u8], executable: bool) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
    }
    std::fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display()))?;
    #[cfg(unix)]
    if executable {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
    }
    #[cfg(not(unix))]
    let _ = executable;
    Ok(())
}

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

    #[test]
    fn linux_dirs_honour_xdg_data_home_and_need_a_real_desktop_folder() {
        let tmp = tempfile::tempdir().unwrap();
        let env =
            |k: &str| (k == "XDG_DATA_HOME").then(|| tmp.path().join("data").display().to_string());
        let d = Dirs::discover(Os::Linux, &env, tmp.path());
        assert_eq!(d.applications, tmp.path().join("data/applications"));
        assert_eq!(d.icon_root, tmp.path().join("data/icons/hicolor"));
        assert!(d.desktop.is_none());
        assert_eq!(d.places(Os::Linux), [Place::Launcher]);
        std::fs::create_dir(tmp.path().join("Desktop")).unwrap();
        let d = Dirs::discover(Os::Linux, &env, tmp.path());
        assert_eq!(d.places(Os::Linux), [Place::Launcher, Place::Desktop]);
    }

    #[test]
    fn windows_dirs_follow_appdata_and_the_profile() {
        let env = |k: &str| match k {
            "USERPROFILE" => Some("/u/me".to_string()),
            "APPDATA" => Some("/u/me/AppData/Roaming".to_string()),
            _ => None,
        };
        let d = Dirs::discover(Os::Windows, &env, Path::new("/h"));
        assert_eq!(
            d.start_menu.unwrap(),
            Path::new("/u/me/AppData/Roaming/Microsoft/Windows/Start Menu/Programs")
        );
        assert_eq!(d.desktop.unwrap(), Path::new("/u/me/Desktop"));
    }

    #[test]
    fn places_parse_and_print() {
        for p in [Place::Launcher, Place::Desktop, Place::StartMenu] {
            assert_eq!(Place::parse(p.as_str()), Some(p));
        }
        assert_eq!(Place::parse("x"), None);
    }

    #[test]
    fn newest_mode_keeps_a_linux_entry_installed_whichever_build_starts() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("co");
        std::fs::create_dir_all(root.join("crates/gitpoulpi-tui")).unwrap();
        std::fs::write(root.join("Cargo.toml"), "").unwrap();
        let mk = |profile: &str, name: &str, age: u64| {
            let dir = root.join("target").join(profile);
            std::fs::create_dir_all(&dir).unwrap();
            let p = dir.join(name);
            let f = std::fs::File::create(&p).unwrap();
            f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(age))
                .unwrap();
            p
        };
        let (dist, dist_cli) = (
            mk("dist", "gitpoulpi-tui", 100),
            mk("dist", "gitpoulpi", 100),
        );
        let (release, release_cli) = (
            mk("release", "gitpoulpi-tui", 1),
            mk("release", "gitpoulpi", 1),
        );
        let dirs = Dirs {
            applications: tmp.path().join("apps"),
            icon_root: tmp.path().join("icons"),
            ..Dirs::default()
        };
        let icons: &'static IconSet = Box::leak(Box::default());
        let req = |exe: &'static Path, launch: &'static Path, newest| Request {
            os: Os::Linux,
            exe,
            terminal: "kitty",
            terminal_exe: None,
            launch_exe: Some(launch),
            newest,
            icons,
            ctx: InstallCtx::legacy_ref(),
            refresh_icon_cache: false,
        };
        let leak = |p: &PathBuf| -> &'static Path { Box::leak(p.clone().into_boxed_path()) };
        let (dist, dist_cli) = (leak(&dist), leak(&dist_cli));
        let (release, release_cli) = (leak(&release), leak(&release_cli));
        // Written from the dist TUI in newest mode: names the newest (release).
        install(Place::Launcher, &dirs, &req(dist, dist_cli, true)).unwrap();
        let text = std::fs::read_to_string(dirs.applications.join("gitpoulpi.desktop")).unwrap();
        assert!(text.contains("release") && !text.contains("dist"), "{text}");
        for (exe, cli) in [(dist, dist_cli), (release, release_cli)] {
            assert_eq!(
                status(Place::Launcher, &dirs, &req(exe, cli, true)).state,
                State::Installed
            );
        }
        // Not in newest mode: the dist TUI sees an outdated entry, as before.
        assert_eq!(
            status(Place::Launcher, &dirs, &req(dist, dist_cli, false)).state,
            State::Outdated
        );
    }
}