corundum-framework-update 0.4.0

Find newer GitHub releases of an app's binary, and replace it with one
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! Replacing the running executable with a newer release.

#[cfg(all(feature = "cli", feature = "self-update"))]
use std::io::BufRead;
#[cfg(feature = "self-update")]
use std::io::Write as _;
use std::path::{Path, PathBuf};
#[cfg(feature = "self-update")]
use std::time::Duration;

use serde::Deserialize;

#[cfg(feature = "self-update")]
use crate::Error;
#[cfg(feature = "self-update")]
use crate::Result;
#[cfg(all(feature = "cli", feature = "self-update"))]
use crate::release::latest_release;
use crate::release::{Release, ReleaseSource};

/// The most a download may weigh. A release binary is tens of megabytes; this only stops a
/// runaway response from filling memory.
#[cfg(feature = "self-update")]
const MAX_DOWNLOAD: u64 = 512 * 1024 * 1024;

/// How long one download may take.
#[cfg(feature = "self-update")]
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);

/// The `update` subcommand's arguments: replace this executable with its newest release.
#[cfg(feature = "cli")]
#[derive(Clone, Debug, Default, clap::Args)]
pub struct UpdateArgs {
    /// Only say whether a newer release exists; download nothing.
    #[arg(long)]
    pub check: bool,
    /// Install without asking first.
    #[arg(long, short = 'y')]
    pub yes: bool,
}

/// How the running executable came to be where it is, which decides whether `update` may
/// replace it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InstallMethod {
    /// Downloaded from a release and placed by hand: `update` replaces it.
    Release,
    /// `cargo install`, under `$CARGO_HOME/bin`: cargo's records would no longer match a
    /// replaced file, so `update` says to run `cargo install` instead.
    Cargo,
    /// `cargo binstall`, under `$CARGO_HOME/bin` and recorded in
    /// `$CARGO_HOME/binstall/crates-v1.json`: `update` says to run `cargo binstall` again.
    Binstall {
        /// The crate it was installed from.
        crate_name: String,
        /// Where that crate came from.
        source: BinstallSource,
    },
    /// A system or package-manager location (`/usr/bin`, the Nix store, Homebrew): the
    /// package manager updates it.
    PackageManager,
    /// A store's own package (Flatpak, Snap, MSIX, Mac App Store): the store updates it, and
    /// replacing a file inside it would fail or be undone.
    Store(StoreKind),
    /// A Velopack package (an installed Windows app, a macOS bundle, an AppImage): the app
    /// updates itself from its own settings, not by replacing the file.
    Velopack,
}

/// The store an app was installed from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StoreKind {
    /// Flathub, or another Flatpak remote.
    Flatpak,
    /// The Snap Store.
    Snap,
    /// The Microsoft Store (an MSIX package).
    Msix,
    /// The Mac App Store.
    MacAppStore,
}

/// What the running process says about the package it runs in: the facts that are not in the
/// executable's path.
#[derive(Clone, Debug)]
pub(crate) struct Probe {
    /// The file system root, where Flatpak puts `.flatpak-info`.
    pub root: PathBuf,
    /// Running as a snap (`$SNAP` is set).
    pub snap: bool,
    /// Running with MSIX package identity.
    pub msix: bool,
    /// `$APPIMAGE`, the AppImage file the process runs from.
    pub appimage: Option<PathBuf>,
}

impl Probe {
    /// Ask this process.
    pub(crate) fn detect() -> Self {
        Self {
            root: PathBuf::from("/"),
            snap: std::env::var_os("SNAP").is_some_and(|v| !v.is_empty()),
            msix: has_package_identity(),
            appimage: std::env::var_os("APPIMAGE")
                .filter(|v| !v.is_empty())
                .map(PathBuf::from),
        }
    }
}

/// Whether the process has MSIX package identity.
#[cfg(windows)]
fn has_package_identity() -> bool {
    use windows::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
    use windows::Win32::Storage::Packaging::Appx::GetCurrentPackageFullName;
    let mut len = 0u32;
    // SAFETY: a null buffer with a zero length only asks for the length.
    let status = unsafe { GetCurrentPackageFullName(&mut len, None) };
    // With a package the zero length is too small; without one the error is NO_PACKAGE.
    status == ERROR_INSUFFICIENT_BUFFER
}

#[cfg(not(windows))]
fn has_package_identity() -> bool {
    false
}

/// Where `cargo binstall` took a crate from, which decides how to run it again.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BinstallSource {
    /// crates.io: `cargo binstall <crate>`.
    Registry,
    /// A git repository, by its URL without the commit: `cargo binstall --git <url> <crate>`.
    /// The crates that are only released on GitHub, such as the desktop apps.
    Git(String),
    /// A local manifest, or a source this does not know.
    Other,
}

/// How the executable at `exe` was installed, judged by where it is and, under
/// `$CARGO_HOME/bin`, by `cargo binstall`'s records. `cargo_home` is `$CARGO_HOME`, or
/// `~/.cargo` when unset.
pub fn install_method(exe: &Path, cargo_home: Option<&Path>) -> InstallMethod {
    install_method_with(exe, cargo_home, &Probe::detect())
}

/// [`install_method`] with what the process says about its package given as `probe`.
pub(crate) fn install_method_with(
    exe: &Path,
    cargo_home: Option<&Path>,
    probe: &Probe,
) -> InstallMethod {
    if probe.root.join(".flatpak-info").exists() {
        return InstallMethod::Store(StoreKind::Flatpak);
    }
    if probe.snap {
        return InstallMethod::Store(StoreKind::Snap);
    }
    if probe.msix {
        return InstallMethod::Store(StoreKind::Msix);
    }
    // `App.app/Contents/MacOS/<exe>`, with the App Store's receipt beside `MacOS`.
    if let Some(macos) = exe.parent()
        && let Some(contents) = macos.parent()
        && macos.file_name().is_some_and(|d| d == "MacOS")
        && contents.file_name().is_some_and(|d| d == "Contents")
        && contents.join("_MASReceipt").join("receipt").exists()
    {
        return InstallMethod::Store(StoreKind::MacAppStore);
    }
    if corundum_framework_platform::package::current_with(exe, probe.appimage.as_deref()).is_some()
    {
        return InstallMethod::Velopack;
    }
    if let Some(home) = cargo_home
        && exe.starts_with(home.join("bin"))
    {
        let records = std::fs::read_to_string(home.join("binstall").join("crates-v1.json"));
        let bin = exe.file_name().and_then(|name| name.to_str()).map(|name| {
            name.strip_suffix(std::env::consts::EXE_SUFFIX)
                .unwrap_or(name)
        });
        return match (records, bin) {
            (Ok(records), Some(bin)) => binstalled(&records, bin),
            _ => None,
        }
        .unwrap_or(InstallMethod::Cargo);
    }
    // `/usr/local` is where binaries placed by hand go; the rest of `/usr` is the
    // distribution's.
    if exe.starts_with("/usr/local") {
        return InstallMethod::Release;
    }
    const MANAGED: [&str; 7] = [
        "/usr",
        "/bin",
        "/sbin",
        "/nix",
        "/opt/homebrew",
        "/home/linuxbrew",
        "/snap",
    ];
    if MANAGED.iter().any(|dir| exe.starts_with(dir)) {
        return InstallMethod::PackageManager;
    }
    InstallMethod::Release
}

/// One crate in `$CARGO_HOME/binstall/crates-v1.json`, as far as this reads it.
#[derive(Deserialize)]
struct BinstallRecord {
    name: String,
    #[serde(default)]
    source: Option<BinstallRecordSource>,
    #[serde(default)]
    bins: Vec<String>,
}

#[derive(Deserialize)]
struct BinstallRecordSource {
    source_type: String,
    url: String,
}

/// How `cargo binstall` installed the binary `bin`, from `records`, the contents of
/// `$CARGO_HOME/binstall/crates-v1.json`: one JSON object per crate, one after another. `None`
/// when binstall did not install it, which leaves `cargo install`.
///
/// A binary binstall installed and `cargo install` replaced afterwards still reads as
/// binstall's; running binstall again puts the release back, which is what `update` is for.
fn binstalled(records: &str, bin: &str) -> Option<InstallMethod> {
    serde_json::Deserializer::from_str(records)
        .into_iter::<BinstallRecord>()
        .map_while(std::result::Result::ok)
        .filter(|record| record.bins.iter().any(|b| b == bin))
        .last()
        .map(|record| InstallMethod::Binstall {
            source: match record.source {
                Some(source) if source.source_type == "Registry" => BinstallSource::Registry,
                Some(source) if source.source_type == "Git" => {
                    let url = source
                        .url
                        .split_once('#')
                        .map_or(source.url.as_str(), |(u, _)| u);
                    BinstallSource::Git(url.to_owned())
                }
                _ => BinstallSource::Other,
            },
            crate_name: record.name,
        })
}

/// This machine as release files name it: `linux-x86_64`, `macos-aarch64`,
/// `windows-x86_64`.
pub fn platform() -> String {
    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
}

/// The file a release publishes `base` under for this machine:
/// `<base>-<os>-<arch>`, with `.exe` on Windows.
pub fn asset_name(base: &str) -> String {
    format!("{base}-{}{}", platform(), std::env::consts::EXE_SUFFIX)
}

/// Write `bytes` to a new executable file `.update-*` in `dir`, flushed to disk. It is removed
/// when the returned file is dropped.
#[cfg(feature = "self-update")]
pub(crate) fn stage(dir: &Path, bytes: &[u8]) -> Result<tempfile::NamedTempFile> {
    let mut staged = tempfile::Builder::new()
        .prefix(".update-")
        .tempfile_in(dir)?;
    staged.write_all(bytes)?;
    staged.as_file().sync_all()?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(staged.path(), std::fs::Permissions::from_mode(0o755))?;
    }
    Ok(staged)
}

/// Write `bytes` beside `exe` and hand the new file to `replace`, which puts it in `exe`'s
/// place. The staging file is removed afterwards, whatever `replace` did.
///
/// The staging file is in `exe`'s directory so the replacement is a rename on one file
/// system, never a half-written executable.
#[cfg(feature = "self-update")]
pub fn install(
    bytes: &[u8],
    exe: &Path,
    replace: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<()> {
    let dir = exe.parent().ok_or_else(|| {
        Error::Io(std::io::Error::other(format!(
            "{} has no directory",
            exe.display()
        )))
    })?;
    let staged = stage(dir, bytes)?;
    replace(staged.path())?;
    Ok(())
}

/// Download `url`, refusing anything larger than [`MAX_DOWNLOAD`].
#[cfg(feature = "self-update")]
async fn download(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
    let response = client
        .get(url)
        .timeout(DOWNLOAD_TIMEOUT)
        .send()
        .await
        .and_then(reqwest::Response::error_for_status)
        .map_err(|e| Error::Http(format!("downloading {url}: {e}")))?;
    if response.content_length().is_some_and(|n| n > MAX_DOWNLOAD) {
        return Err(Error::Http(format!(
            "{url} is larger than {MAX_DOWNLOAD} bytes"
        )));
    }
    let bytes = response
        .bytes()
        .await
        .map_err(|e| Error::Http(format!("downloading {url}: {e}")))?;
    if bytes.len() as u64 > MAX_DOWNLOAD {
        return Err(Error::Http(format!(
            "{url} is larger than {MAX_DOWNLOAD} bytes"
        )));
    }
    Ok(bytes.to_vec())
}

/// Download `release`'s file for this machine, the one `source` names with
/// [`ReleaseSource::asset`].
///
/// [`Error::NotConfigured`] when `source` names none, [`Error::NoAsset`] when the release has
/// no file for this platform, and [`Error::Http`] when the download fails, is empty or is
/// larger than [`MAX_DOWNLOAD`].
#[cfg(feature = "self-update")]
pub async fn download_asset(
    client: &reqwest::Client,
    source: &ReleaseSource,
    release: &Release,
) -> Result<Vec<u8>> {
    let base = source.asset_base().ok_or_else(|| {
        Error::NotConfigured(format!(
            "{} does not name a release file to download",
            source.repository()
        ))
    })?;
    let name = asset_name(base);
    let binary = release
        .assets
        .iter()
        .find(|a| a.name == name)
        .ok_or_else(|| {
            Error::NoAsset(format!(
                "{} {} has no {name}",
                source.repository(),
                release.version
            ))
        })?;
    let bytes = download(client, &binary.download_url).await?;
    if bytes.is_empty() {
        return Err(Error::Http(format!("{name} downloaded empty")));
    }
    Ok(bytes)
}

/// The command that updates a binary installed as `method`, when there is one to run:
/// `cargo install` or `cargo binstall` with what it was installed from.
pub fn advice_command(source: &ReleaseSource, method: &InstallMethod) -> Option<String> {
    match (method, source.crate_name()) {
        (InstallMethod::Cargo, Some(name)) => Some(format!("cargo install {name} --locked")),
        (InstallMethod::Binstall { crate_name, source }, _) => match source {
            BinstallSource::Registry => Some(format!("cargo binstall {crate_name}")),
            BinstallSource::Git(url) => Some(format!("cargo binstall --git {url} {crate_name}")),
            BinstallSource::Other => None,
        },
        _ => None,
    }
}

/// What to tell the user to do about `release` when the binary installed as `method` is not
/// replaced in place: where to download it, or which package manager to ask.
pub fn advice(source: &ReleaseSource, release: &Release, method: &InstallMethod) -> String {
    if let Some(command) = advice_command(source, method) {
        let tool = match method {
            InstallMethod::Cargo => "cargo",
            _ => "cargo binstall",
        };
        return format!("installed with {tool}; run: {command}");
    }
    match method {
        InstallMethod::Cargo => "installed with cargo; update it with cargo install".to_owned(),
        InstallMethod::Binstall { .. } => {
            "installed with cargo binstall; update it with cargo binstall".to_owned()
        }
        InstallMethod::PackageManager => {
            "installed by a package manager; update it with that".to_owned()
        }
        InstallMethod::Store(store) => format!(
            "installed from {}; it updates there",
            match store {
                StoreKind::Flatpak => "Flathub",
                StoreKind::Snap => "the Snap Store",
                StoreKind::Msix => "the Microsoft Store",
                StoreKind::MacAppStore => "the Mac App Store",
            }
        ),
        InstallMethod::Velopack => "Updated by the app itself.".to_owned(),
        InstallMethod::Release => format!("download it from {}", release.url),
    }
}

/// `$CARGO_HOME`, or `~/.cargo`.
pub fn cargo_home() -> Option<PathBuf> {
    std::env::var_os("CARGO_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::home_dir().map(|home| home.join(".cargo")))
}

#[cfg(all(feature = "cli", feature = "self-update"))]
/// Carry out `update` for the binary `name` at `current`, whose releases `source` names;
/// returns the exit code.
///
/// Prints what it finds and does. Exit 0 is up to date, installed, or (with `--check`) a
/// newer release found; 1 is a newer release this binary does not install itself.
pub async fn run(
    args: &UpdateArgs,
    source: &ReleaseSource,
    name: &str,
    current: &str,
) -> Result<i32> {
    let current_v = semver::Version::parse(current).map_err(|e| {
        Error::NotConfigured(format!(
            "this binary's version {current:?} is not semver: {e}"
        ))
    })?;
    let client = crate::client(&format!("{name}/{current}"))?;
    let release = latest_release(&client, source).await?;
    if release.version <= current_v {
        println!(
            "{name} {current} is up to date (latest release {})",
            release.version
        );
        return Ok(0);
    }
    println!(
        "{name} {} is available (installed: {current}): {}",
        release.version, release.url
    );
    if args.check {
        return Ok(0);
    }

    if source.asset_base().is_none() {
        println!(
            "{name} does not update itself; {}",
            advice(source, &release, &InstallMethod::Release)
        );
        return Ok(1);
    }
    let exe = std::env::current_exe()?;
    let exe = exe.canonicalize().unwrap_or(exe);
    let method = install_method(&exe, cargo_home().as_deref());
    if method != InstallMethod::Release {
        println!("{} is {}", exe.display(), advice(source, &release, &method));
        return Ok(1);
    }

    if !args.yes
        && !confirm(&format!(
            "replace {} with {}?",
            exe.display(),
            release.version
        ))?
    {
        println!("not updated");
        return Ok(1);
    }
    let bytes = download_asset(&client, source, &release).await?;
    install(&bytes, &exe, |staged| self_replace::self_replace(staged))?;
    println!(
        "installed {name} {}; restart the {name} service to run it",
        release.version
    );
    Ok(0)
}

#[cfg(all(feature = "cli", feature = "self-update"))]
/// Ask `question` on the terminal; only `y` or `yes` is a yes.
fn confirm(question: &str) -> Result<bool> {
    print!("{question} [y/N] ");
    std::io::stdout().flush()?;
    let mut answer = String::new();
    std::io::stdin().lock().read_line(&mut answer)?;
    Ok(matches!(
        answer.trim().to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}

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

    fn probe(root: &Path) -> Probe {
        Probe {
            root: root.to_owned(),
            snap: false,
            msix: false,
            appimage: None,
        }
    }

    #[test]
    fn a_velopack_package_is_the_package_s_to_update() {
        let tmp = tempfile::tempdir().unwrap();
        let current = tmp.path().join("current");
        std::fs::create_dir(&current).unwrap();
        std::fs::write(tmp.path().join("Update.exe"), "").unwrap();
        let exe = current.join("app.exe");
        let empty = tempfile::tempdir().unwrap();
        let method = install_method_with(&exe, None, &probe(empty.path()));
        assert_eq!(method, InstallMethod::Velopack);
        let source = ReleaseSource::github("o", "r");
        assert_eq!(advice_command(&source, &method), None);
    }

    #[test]
    fn advice_carries_the_command_to_run() {
        let source = ReleaseSource::github("o", "r").cargo_crate("app-crate");
        let release = Release {
            version: "1.0.0".parse().unwrap(),
            url: "https://example.test/r".to_owned(),
            assets: vec![],
        };
        let binstall = |source| InstallMethod::Binstall {
            crate_name: "app-crate".to_owned(),
            source,
        };
        let git = binstall(BinstallSource::Git("https://github.com/o/r".to_owned()));
        let cases = [
            (
                InstallMethod::Cargo,
                Some("cargo install app-crate --locked"),
                "installed with cargo; run: cargo install app-crate --locked",
            ),
            (
                binstall(BinstallSource::Registry),
                Some("cargo binstall app-crate"),
                "installed with cargo binstall; run: cargo binstall app-crate",
            ),
            (
                git,
                Some("cargo binstall --git https://github.com/o/r app-crate"),
                "installed with cargo binstall; run: cargo binstall --git https://github.com/o/r app-crate",
            ),
            (
                binstall(BinstallSource::Other),
                None,
                "installed with cargo binstall; update it with cargo binstall",
            ),
            (
                InstallMethod::PackageManager,
                None,
                "installed by a package manager; update it with that",
            ),
            (
                InstallMethod::Release,
                None,
                "download it from https://example.test/r",
            ),
        ];
        for (method, command, words) in cases {
            assert_eq!(advice_command(&source, &method).as_deref(), command);
            assert_eq!(advice(&source, &release, &method), words);
        }
        let bare = ReleaseSource::github("o", "r");
        assert_eq!(advice_command(&bare, &InstallMethod::Cargo), None);
        assert_eq!(
            advice(&bare, &release, &InstallMethod::Cargo),
            "installed with cargo; update it with cargo install"
        );
    }

    #[test]
    fn a_binary_is_replaced_only_where_it_was_placed_by_hand() {
        let home = Path::new("/home/u/.cargo");
        let root = tempfile::tempdir().unwrap();
        let method = |p: &str| install_method_with(Path::new(p), Some(home), &probe(root.path()));
        assert_eq!(method("/home/u/.cargo/bin/app"), InstallMethod::Cargo);
        assert_eq!(method("/usr/bin/app"), InstallMethod::PackageManager);
        assert_eq!(
            method("/nix/store/abc-app/bin/app"),
            InstallMethod::PackageManager
        );
        assert_eq!(
            method("/opt/homebrew/bin/app"),
            InstallMethod::PackageManager
        );
        assert_eq!(method("/usr/local/bin/app"), InstallMethod::Release);
        assert_eq!(method("/home/u/.local/bin/app"), InstallMethod::Release);
    }

    #[test]
    fn an_app_in_a_store_package_is_the_store_s_to_update() {
        let tmp = tempfile::tempdir().unwrap();
        let exe = Path::new("/home/u/.local/bin/app");
        let method = |p: &Probe| install_method_with(exe, None, p);
        assert_eq!(method(&probe(tmp.path())), InstallMethod::Release);

        std::fs::write(tmp.path().join(".flatpak-info"), "").unwrap();
        assert_eq!(
            method(&probe(tmp.path())),
            InstallMethod::Store(StoreKind::Flatpak)
        );

        let empty = tempfile::tempdir().unwrap();
        let snap = Probe {
            snap: true,
            ..probe(empty.path())
        };
        assert_eq!(method(&snap), InstallMethod::Store(StoreKind::Snap));
        let msix = Probe {
            msix: true,
            ..probe(empty.path())
        };
        assert_eq!(method(&msix), InstallMethod::Store(StoreKind::Msix));
    }

    #[test]
    fn a_mac_app_store_bundle_is_recognised_by_its_receipt() {
        let tmp = tempfile::tempdir().unwrap();
        let contents = tmp.path().join("App.app").join("Contents");
        std::fs::create_dir_all(contents.join("MacOS")).unwrap();
        let exe = contents.join("MacOS").join("app");
        let p = probe(tmp.path());
        assert_eq!(install_method_with(&exe, None, &p), InstallMethod::Release);
        std::fs::create_dir(contents.join("_MASReceipt")).unwrap();
        std::fs::write(contents.join("_MASReceipt").join("receipt"), "").unwrap();
        assert_eq!(
            install_method_with(&exe, None, &p),
            InstallMethod::Store(StoreKind::MacAppStore)
        );
    }

    #[test]
    fn binstall_s_records_name_the_crate_and_where_it_came_from() {
        let records = concat!(
            r#"{"name":"dioxus-cli","version_req":"*","current_version":"0.7.3","#,
            r#""source":{"source_type":"Registry","url":"https://github.com/rust-lang/crates.io-index"},"#,
            r#""target":"x86_64-unknown-linux-gnu","bins":["dx"]}"#,
            r#"{"name":"sapphire-journal-desktop","version_req":"*","current_version":"0.3.0","#,
            r#""source":{"source_type":"Git","url":"https://github.com/sapphire-turtle/sapphire-journal#b05d5c2"},"#,
            r#""target":"x86_64-unknown-linux-gnu","bins":["sapphire-journal-desktop"]}"#,
        );
        assert_eq!(
            binstalled(records, "dx"),
            Some(InstallMethod::Binstall {
                crate_name: "dioxus-cli".to_owned(),
                source: BinstallSource::Registry,
            })
        );
        assert_eq!(
            binstalled(records, "sapphire-journal-desktop"),
            Some(InstallMethod::Binstall {
                crate_name: "sapphire-journal-desktop".to_owned(),
                source: BinstallSource::Git(
                    "https://github.com/sapphire-turtle/sapphire-journal".to_owned()
                ),
            })
        );
        assert_eq!(binstalled(records, "sapphire-journal"), None);
        assert_eq!(binstalled("", "dx"), None);
    }

    #[test]
    fn a_binary_under_cargo_s_bin_is_binstall_s_only_when_it_says_so() {
        let tmp = tempfile::tempdir().unwrap();
        let exe = tmp
            .path()
            .join("bin")
            .join(format!("dx{}", std::env::consts::EXE_SUFFIX));
        assert_eq!(
            install_method_with(&exe, Some(tmp.path()), &probe(tmp.path())),
            InstallMethod::Cargo
        );
        std::fs::create_dir(tmp.path().join("binstall")).unwrap();
        std::fs::write(
            tmp.path().join("binstall").join("crates-v1.json"),
            r#"{"name":"dioxus-cli","source":{"source_type":"Registry","url":""},"bins":["dx"]}"#,
        )
        .unwrap();
        assert_eq!(
            install_method_with(&exe, Some(tmp.path()), &probe(tmp.path())),
            InstallMethod::Binstall {
                crate_name: "dioxus-cli".to_owned(),
                source: BinstallSource::Registry,
            }
        );
    }

    #[test]
    fn the_asset_names_this_machine() {
        let name = asset_name("sapphire-bridge");
        assert!(name.starts_with("sapphire-bridge-"));
        assert!(name.contains(std::env::consts::OS));
        assert!(name.contains(std::env::consts::ARCH));
    }

    #[test]
    #[cfg(feature = "self-update")]
    fn install_puts_the_bytes_in_place_and_leaves_no_staging_file() {
        let tmp = tempfile::tempdir().unwrap();
        let exe = tmp.path().join("app");
        std::fs::write(&exe, b"old").unwrap();
        install(b"new", &exe, |staged| {
            std::fs::copy(staged, &exe).map(|_| ())
        })
        .unwrap();
        assert_eq!(std::fs::read(&exe).unwrap(), b"new");
        let left: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().collect();
        assert_eq!(left.len(), 1, "the staging file is gone");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let staged_mode = std::fs::metadata(&exe).unwrap().permissions().mode();
            assert_eq!(
                staged_mode & 0o111,
                0o111,
                "the copy keeps the executable bit"
            );
        }
    }

    #[cfg(feature = "self-update")]
    mod download {
        use super::*;
        use crate::latest_release;

        fn v(s: &str) -> semver::Version {
            semver::Version::parse(s).unwrap()
        }

        /// Serve the routes `routes` builds from the server's own root (path → body) on a
        /// loopback port until the test ends; returns the root.
        async fn serve(routes: impl FnOnce(&str) -> Vec<(String, Vec<u8>)>) -> String {
            use tokio::io::{AsyncReadExt, AsyncWriteExt};
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let root = format!("http://{}", listener.local_addr().unwrap());
            let routes = routes(&root);
            tokio::spawn(async move {
                loop {
                    let (mut socket, _) = listener.accept().await.unwrap();
                    let mut buf = vec![0u8; 8192];
                    let n = socket.read(&mut buf).await.unwrap();
                    let request = String::from_utf8_lossy(&buf[..n]);
                    let path = request.split_whitespace().nth(1).unwrap_or("").to_owned();
                    let (status, body) = match routes.iter().find(|(p, _)| *p == path) {
                        Some((_, body)) => ("200 OK", body.clone()),
                        None => ("404 Not Found", Vec::new()),
                    };
                    let head = format!(
                        "HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
                        body.len()
                    );
                    socket.write_all(head.as_bytes()).await.unwrap();
                    socket.write_all(&body).await.unwrap();
                }
            });
            root
        }

        const RELEASES: &str = "/repos/o/r/releases?per_page=100";

        /// A repository with release 0.20.0 of `app`: its file for this machine.
        async fn repository(binary: &[u8]) -> String {
            let name = asset_name("app");
            let binary = binary.to_vec();
            serve(move |root| {
                let releases = format!(
                    r#"[{{"tag_name":"v0.20.0","html_url":"{root}/r/v0.20.0","assets":[
                        {{"name":"{name}","browser_download_url":"{root}/dl/{name}"}}]}}]"#
                );
                vec![
                    (RELEASES.to_owned(), releases.into_bytes()),
                    (format!("/dl/{name}"), binary),
                ]
            })
            .await
        }

        #[tokio::test]
        async fn a_release_is_fetched_end_to_end() {
            let root = repository(b"new binary").await;
            let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
            let client = crate::client("test/0.0.0").unwrap();
            let release = latest_release(&client, &source).await.unwrap();
            assert_eq!(release.version, v("0.20.0"));
            let bytes = download_asset(&client, &source, &release).await.unwrap();
            assert_eq!(bytes, b"new binary");
        }

        #[tokio::test]
        async fn an_empty_download_is_refused() {
            let root = repository(b"").await;
            let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
            let client = crate::client("test/0.0.0").unwrap();
            let release = latest_release(&client, &source).await.unwrap();
            let err = download_asset(&client, &source, &release)
                .await
                .unwrap_err();
            assert!(matches!(err, Error::Http(_)), "{err}");
        }

        #[tokio::test]
        async fn a_release_without_this_platforms_file_is_refused() {
            let root = serve(|_| {
                vec![(
                    RELEASES.to_owned(),
                    br#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid","assets":[]}]"#
                        .to_vec(),
                )]
            })
            .await;
            let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
            let client = crate::client("test/0.0.0").unwrap();
            let release = latest_release(&client, &source).await.unwrap();
            let err = download_asset(&client, &source, &release)
                .await
                .unwrap_err();
            assert!(matches!(err, Error::NoAsset(_)), "{err}");
        }
    }
}