dev-prune 1.4.1

Universal, lockfile-safe workspace pruner and background dependency cleaner
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

// Handler for `dev-prune update`, and the periodic release check behind it.
//
// The check is opt-*out*. An out-of-date cleanup tool is a tool whose safety fixes you do
// not have, so `devp update` asks GitHub for the latest release by default, and `devp
// run` / `devp status` repeat that quietly at most once a week. Both are switched off by
// `devp config set update_check false`, and `devp update --offline` skips a single run.
//
// What leaves the machine is one unauthenticated GET to the public releases endpoint. It
// carries no identifier, no configuration, no repository paths and no usage data — the
// only thing the server learns is that some copy of dev-prune asked what the latest
// version is. Nothing else in the binary opens a socket. See `docs/PRIVACY.md`.
//
// By default the command does not download or install anything: replacing a binary is
// the package manager's job, and doing it ourselves would mean writing to a PATH
// directory with whatever privileges the user happened to have. `--install` keeps that
// division of labour — it works out which package manager owns the running binary and
// runs *that manager's* own upgrade command, rather than writing files itself. The
// scheduled pass is never interrupted by an upgrade: it runs the managed copy under
// `<config>/bin`, which is replaced by atomic rename and refreshed from the new binary
// on the next healthy run (`setup::stable_exe_path`), so a pass already in flight keeps
// its loaded image and the next pass picks up the new one.

use std::cmp::Ordering;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};
use chrono::Utc;

use crate::config::Registry;
use crate::constants;
use crate::output;

pub fn run(offline: bool, install: bool) -> Result<()> {
    if install {
        return run_install();
    }
    output::print_header("dev-prune version & upgrade");

    output::print_info(&format!("Installed version: v{}", constants::VERSION));

    if offline {
        output::print_info("Skipping the release check because `--offline` was passed.");
    } else if let Ok(mut registry) = Registry::load() {
        if registry.settings.update_check {
            // An explicit `devp update` always asks, regardless of when the last
            // automatic check ran — the user is standing there waiting for the answer.
            match refresh_latest(&mut registry) {
                Ok(latest) => report_comparison(&latest),
                // A failed check is not a failed command. Someone offline, behind a
                // proxy, or hitting a rate limit still wants the upgrade instructions.
                Err(e) => output::print_warning(&format!(
                    "Could not reach the release API ({e}). The upgrade commands below still apply."
                )),
            }
            let _ = registry.save();
        } else {
            output::print_info(
                "The release check is off (`devp config set update_check true` re-enables it).",
            );
        }
    }

    println!();
    println!("  Latest releases:  {}", constants::RELEASES_URL);
    println!();
    print_upgrade_commands();

    Ok(())
}

/// Ask GitHub right now — no interval — and say where the installed build stands.
///
/// For `devp init`, which is deliberate and infrequent enough to be worth a round trip:
/// setting a machine up is exactly the moment to learn the binary is a version behind.
/// `devp run` deliberately does not use this; it goes through [`notify_if_outdated`],
/// which is interval-gated so everyday work never waits on the network.
///
/// Returns `true` when the registry changed and needs saving.
pub fn check_now(registry: &mut Registry) -> bool {
    if !registry.settings.update_check {
        return false;
    }

    match refresh_latest(registry) {
        Ok(latest) => {
            report_comparison(&latest);
            if compare_versions(constants::VERSION, &latest) == Some(Ordering::Less) {
                print_upgrade_commands();
            }
        }
        // Not being able to reach GitHub is not a failed `init`.
        Err(e) => output::print_info(&format!("Could not check for a newer release ({e}).")),
    }
    true
}

/// Every install channel, in one place so they cannot drift apart.
fn print_upgrade_commands() {
    println!("  Upgrade with whichever channel you installed from:");
    println!("    cargo binstall dev-prune --force");
    println!("    cargo install dev-prune --force");
    println!("    npm install -g dev-prune@latest");
    println!("    uv tool upgrade dev-prune  /  pipx upgrade dev-prune");
    println!("    curl -fsSL {} | sh", constants::INSTALL_SH_URL);
    println!("    iwr -useb {} | iex", constants::INSTALL_PS1_URL);
}

/// The package manager that owns the running binary — the one whose upgrade command
/// `--install` runs. One channel owns one binary: a copy installed through uv is
/// upgraded through uv, never through npm, because two managers writing the same PATH
/// entry would fight over it forever.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Channel {
    /// `install.sh` / `install.ps1` put it under the managed `<config>/bin`.
    Installer,
    /// `cargo install` / `cargo binstall` put it under `~/.cargo/bin`.
    Cargo,
    /// `npm install -g` — the binary lives under a `node_modules` tree.
    Npm,
    /// `uv tool install` — under uv's tool environments.
    UvTool,
    /// `pipx install` — under a `pipx` venv.
    Pipx,
    /// Anywhere else: a dev build, a hand-copied binary, a distro package.
    Unknown,
}

/// Classify where `exe` came from by the directories in its path.
///
/// Purely lexical on purpose: this must not touch the network or spawn anything, and
/// each channel's layout is stable enough that its marker directory is a reliable
/// fingerprint. `managed` is passed in (rather than resolved here) so tests can probe
/// the classification without a config directory on disk.
fn detect_channel(exe: &std::path::Path, managed: Option<&std::path::Path>) -> Channel {
    if let Some(managed) = managed
        && exe == managed
    {
        return Channel::Installer;
    }
    let has_dir = |name: &str| {
        exe.components()
            .any(|c| c.as_os_str().to_string_lossy().eq_ignore_ascii_case(name))
    };
    if has_dir(".cargo") {
        Channel::Cargo
    } else if has_dir("node_modules") {
        Channel::Npm
    } else if has_dir("uv") || has_dir("uv-tool") {
        Channel::UvTool
    } else if has_dir("pipx") {
        Channel::Pipx
    } else {
        Channel::Unknown
    }
}

/// `devp update --install`: upgrade this installation to the latest release.
///
/// Downloads the release binary from GitHub and replaces the files itself, rather than
/// asking whichever package manager delivered the first copy to do it. That inversion is
/// deliberate. There is exactly one binary that matters — the managed copy under
/// `<config>/bin`, which the git hooks, the scheduler and `PATH` all point at — and it
/// does not live inside `node_modules`, a uv tool directory or `~/.cargo/bin`. Asking
/// `uv` to upgrade a file it has never heard of was never going to work, and asking it to
/// upgrade its *own* copy left the one that actually runs untouched.
///
/// So both are replaced: the managed copy first, because that is what runs unattended,
/// then the running binary if it is a different file, because that is what the user
/// types. The channel's own bookkeeping (what `uv tool list` believes is installed) is
/// left stale on purpose — correcting it means running the channel's installer, which is
/// the one thing this route exists to avoid — and the command to resync it is printed.
///
/// Falls back to the channel's own upgrade command when there is no published binary for
/// this platform or the download fails, so a release-page outage costs the fast path and
/// not the upgrade.
fn run_install() -> Result<()> {
    output::print_header("dev-prune self-update");

    if crate::setup::offline_requested() {
        anyhow::bail!(
            "{} is set — an install needs the network by definition.",
            constants::ENV_OFFLINE
        );
    }

    // Know before downloading whether there is anything to download. A failed check is
    // fatal here (unlike `devp update`): running an installer blind would "upgrade" to
    // the version already installed.
    let mut registry = Registry::load()?;
    let latest = refresh_latest(&mut registry)?;
    let _ = registry.save();
    if compare_versions(constants::VERSION, &latest) != Some(Ordering::Less) {
        output::print_success(&format!(
            "v{} is already the latest release — nothing to install.",
            constants::VERSION
        ));
        return Ok(());
    }
    output::print_info(&format!("Upgrading v{} -> v{latest}", constants::VERSION));

    let exe = std::env::current_exe().context("could not locate the running binary")?;
    let managed = crate::setup::managed_exe_path().ok();
    let channel = detect_channel(&exe, managed.as_deref());

    match install_directly(&latest, &exe, managed.as_deref()) {
        Ok(()) => {
            output::print_success(&format!("dev-prune v{latest} installed."));
            report_channel_bookkeeping(channel);
            output::print_info(
                "The scheduled pass was not interrupted: it runs the managed copy, which \
                 was replaced by atomic rename, so a pass already in flight keeps the \
                 image it loaded and the next one picks up the new binary.",
            );
            return Ok(());
        }
        Err(e) => output::print_warning(&format!(
            "Direct download did not work ({e:#}).\nFalling back to the channel that \
             installed this copy."
        )),
    }

    // On Windows a running executable's file is locked against replacement but not
    // against rename. Moving it aside first lets the channel write a fresh file at the
    // real path; the `.old` left behind is swept up by the *next* run, when nothing is
    // executing it any more.
    #[cfg(windows)]
    let aside = {
        let aside = exe.with_extension("exe.old");
        let _ = fs::remove_file(&aside);
        fs::rename(&exe, &aside).ok().map(|_| aside)
    };

    let result = spawn_channel_upgrade(channel);

    #[cfg(windows)]
    if let Some(aside) = aside {
        if result.is_ok() {
            // Best effort: the file is still our running image, so Windows may refuse
            // the delete. The sweep at the top of the next `--install` gets it then.
            let _ = fs::remove_file(&aside);
        } else if !exe.exists() {
            // The upgrade never wrote a new binary — put the old one back so the
            // command the user has on PATH still exists.
            let _ = fs::rename(&aside, &exe);
        }
    }
    result?;

    output::print_success(&format!("dev-prune v{latest} installed."));
    output::print_info(
        "The scheduled pass was not interrupted: it runs the managed copy, which \
         refreshes itself from the new binary on its next run.",
    );
    Ok(())
}

/// Replace every copy of the binary this installation actually runs, from one download.
///
/// The managed copy is done first and is the only one whose failure aborts the upgrade:
/// it is what the scheduler and the git hooks invoke, so a machine with a fresh managed
/// copy is upgraded even if nothing else could be written.
///
/// Every other path is then written from the same verified bytes, and each is written
/// with the same rename-aside dance rather than through `ensure_alias`. That matters on
/// Windows: `ensure_alias` deletes the twin before relinking, and the delete fails when
/// the twin is the running image — which is exactly the case when the user typed `devp
/// update --install`. Renaming a running executable is allowed where deleting it is not,
/// so this route leaves no copy behind on the previous release.
fn install_directly(latest: &str, exe: &Path, managed: Option<&Path>) -> Result<()> {
    let bytes = fetch_release_binary(latest)?;
    let primary = managed.unwrap_or(exe);
    install_bytes_at(&bytes, primary)?;

    // Every other file that is a copy of the binary just replaced. Left alone they would
    // keep running the previous release — silently, because the scheduler and the hooks
    // both discard their own output by design.
    let mut also: Vec<PathBuf> = Vec::new();
    if let Some(dir) = primary.parent() {
        also.push(dir.join(if cfg!(windows) { "devp.exe" } else { "devp" }));
    }
    if primary != exe && exe.is_file() {
        also.push(exe.to_path_buf());
    }
    for path in also {
        if path == primary {
            continue;
        }
        if let Err(e) = install_bytes_at(&bytes, &path) {
            output::print_warning(&format!(
                "The managed copy is now v{latest}, but {} could not be replaced ({e:#}).                  Until it is, that copy runs the previous version whenever it is the one                  invoked.",
                path.display()
            ));
        }
    }

    // The windowless scheduler twin is a *patched* copy, not a plain one, so it is
    // rebuilt rather than written — from the managed binary that was just replaced.
    crate::daemon::refresh_hidden_twin();
    Ok(())
}

/// Name the channel's own upgrade command after a direct install, for the one thing the
/// direct route deliberately leaves untouched: the manager's record of what it installed.
fn report_channel_bookkeeping(channel: Channel) {
    let resync = match channel {
        Channel::Cargo => "cargo install dev-prune --force",
        Channel::Npm => "npm install -g dev-prune@latest",
        Channel::UvTool => "uv tool upgrade dev-prune",
        Channel::Pipx => "pipx upgrade dev-prune",
        // Nothing else keeps a version record to disagree with the binary.
        Channel::Installer | Channel::Unknown => return,
    };
    output::print_info(&format!(
        "The binaries are up to date. `{resync}` also updates that manager's own record \
         of the version, which still reads v{}.",
        constants::VERSION
    ));
}

/// Download release `version`'s binary for this platform and put it at `target`.
///
/// The direct route, and the reason `devp update --install` no longer depends on the
/// package manager that happened to deliver the first copy. Whatever installed it, the
/// binary the hooks, the scheduler and `PATH` all point at is one file in the config
/// directory, and this replaces that file. `uv`, `npm` and `cargo` are delivery
/// channels; they are not the source of truth, and asking one of them to upgrade a file
/// living under another one's directory was never going to work.
///
/// Refuses to install anything whose SHA-256 does not match the sidecar published beside
/// it. That check is the entire safety story for this path: the bytes are about to
/// become the binary the machine runs on a schedule.
fn fetch_release_binary(version: &str) -> Result<Vec<u8>> {
    let asset = constants::release_asset_name(version).with_context(|| {
        format!(
            "no published binary for {}-{}; upgrade through the channel that installed \
             this copy instead",
            std::env::consts::OS,
            std::env::consts::ARCH
        )
    })?;
    let base = format!("{}/v{version}/{asset}", constants::RELEASE_DOWNLOAD_BASE);

    let expected = fetch_expected_hash(&format!("{base}.sha256"))?;
    output::print_info(&format!("Downloading {asset}"));
    let bytes = fetch_bytes(&base)?;

    let actual = {
        use sha2::{Digest, Sha256};
        use std::fmt::Write as _;
        let mut h = Sha256::new();
        h.update(&bytes);
        // Hex-encoded by hand: sha2 0.11 returns a `hybrid_array::Array`, which has no
        // `LowerHex`, and the sidecar is lower-case hex either way.
        h.finalize().iter().fold(String::new(), |mut s, b| {
            let _ = write!(s, "{b:02x}");
            s
        })
    };
    if actual != expected {
        anyhow::bail!(
            "checksum mismatch for {asset}\n  expected {expected}\n  got      {actual}\n\
             The download was corrupted or tampered with; nothing was installed."
        );
    }

    Ok(bytes)
}

/// Write already-verified bytes over one binary.
///
/// Separate from the download so a single transfer can serve every copy that has to be
/// replaced — the managed binary, its `devp` twin, and whatever the user is running —
/// instead of fetching the same megabytes once per path.
fn install_bytes_at(bytes: &[u8], target: &Path) -> Result<()> {
    // Staged beside the target and renamed in, so a write that dies half-way leaves the
    // working binary untouched rather than a truncated file where the scheduler expects
    // an executable.
    let staging = target.with_extension("new");
    if let Some(parent) = target.parent() {
        fs::create_dir_all(parent).ok();
    }
    fs::write(&staging, bytes).with_context(|| format!("could not write {}", staging.display()))?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        // Downloaded files are 0644; the scheduler needs to be able to run this.
        let _ = fs::set_permissions(&staging, fs::Permissions::from_mode(0o755));
    }

    replace_binary(&staging, target)
}

/// Read the hash out of a `.sha256` sidecar published beside a release asset.
fn fetch_expected_hash(url: &str) -> Result<String> {
    let body = String::from_utf8(fetch_bytes(url)?).context("the checksum sidecar was not text")?;
    parse_sha256_sidecar(&body)
}

/// The parsing half of [`fetch_expected_hash`], which is `sha256sum` format: the hex
/// digest, two spaces, the file name.
///
/// Validated rather than trusted, because the failure this guards against is not a
/// malformed checksum — it is a 404 page or a proxy error blob arriving where the sidecar
/// should be. Comparing a digest against `<!DOCTYPE html>` would report a checksum
/// mismatch, which reads as "someone tampered with the download" and sends the user
/// somewhere alarming and wrong.
fn parse_sha256_sidecar(body: &str) -> Result<String> {
    let hash = body
        .split_whitespace()
        .next()
        .context("the checksum sidecar was empty")?
        .to_ascii_lowercase();
    if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
        anyhow::bail!("the checksum sidecar did not contain a SHA-256 digest");
    }
    Ok(hash)
}

fn fetch_bytes(url: &str) -> Result<Vec<u8>> {
    let mut body = ureq::get(url)
        .header("User-Agent", &format!("dev-prune/{}", constants::VERSION))
        .config()
        .timeout_global(Some(Duration::from_secs(
            constants::UPDATE_DOWNLOAD_TIMEOUT_SECS,
        )))
        .build()
        .call()
        .with_context(|| format!("could not download {url}"))?;
    let mut buf = Vec::new();
    body.body_mut()
        .as_reader()
        .read_to_end(&mut buf)
        .with_context(|| format!("could not read {url}"))?;
    Ok(buf)
}

/// Move `staged` onto `target`, working around the one platform that will not overwrite
/// a file it is executing.
fn replace_binary(staged: &Path, target: &Path) -> Result<()> {
    // On Windows a running image is locked against replacement but not against rename,
    // so the live file steps aside and the new one takes its name. The `.old` is swept
    // by the next run, when nothing holds it open any more.
    #[cfg(windows)]
    let aside = {
        let aside = target.with_extension("exe.old");
        let _ = fs::remove_file(&aside);
        target
            .exists()
            .then(|| fs::rename(target, &aside).ok().map(|_| aside))
            .flatten()
    };

    match fs::rename(staged, target) {
        Ok(()) => {
            #[cfg(windows)]
            if let Some(aside) = aside {
                let _ = fs::remove_file(&aside);
            }
            Ok(())
        }
        Err(e) => {
            let _ = fs::remove_file(staged);
            #[cfg(windows)]
            if let Some(aside) = aside
                && !target.exists()
            {
                // Put the working binary back rather than leaving the machine with no
                // `dev-prune` at all.
                let _ = fs::rename(&aside, target);
            }
            Err(e).with_context(|| format!("could not install {}", target.display()))
        }
    }
}

/// Run one channel's own upgrade command, wired to the terminal so its progress and
/// prompts reach the user directly.
fn spawn_channel_upgrade(channel: Channel) -> Result<()> {
    let install_ps1 = format!("iwr -useb {} | iex", constants::INSTALL_PS1_URL);
    let install_sh = format!("curl -fsSL {} | sh", constants::INSTALL_SH_URL);
    let argv: Vec<&str> = match channel {
        Channel::Cargo => {
            // binstall pulls the prebuilt release; plain `cargo install` compiles for
            // minutes. Prefer the fast one when it exists.
            if crate::adapters::binary_available("cargo-binstall") {
                vec!["cargo", "binstall", "dev-prune", "--force", "-y"]
            } else {
                vec!["cargo", "install", "dev-prune", "--force"]
            }
        }
        Channel::Npm => vec!["npm", "install", "-g", "dev-prune@latest"],
        Channel::UvTool => vec!["uv", "tool", "upgrade", "dev-prune"],
        Channel::Pipx => vec!["pipx", "upgrade", "dev-prune"],
        Channel::Installer => {
            if cfg!(windows) {
                vec!["powershell", "-NoProfile", "-Command", &install_ps1]
            } else {
                vec!["sh", "-c", &install_sh]
            }
        }
        Channel::Unknown => {
            output::print_warning(
                "Could not tell which channel installed this binary, so nothing was \
                 changed. Upgrade it yourself with one of:",
            );
            print_upgrade_commands();
            anyhow::bail!("unrecognised install channel");
        }
    };

    output::print_info(&format!("Running: {}", argv.join(" ")));
    let status = crate::spawn::command(crate::adapters::resolve_program(argv[0]))
        .args(&argv[1..])
        .status()
        .with_context(|| format!("could not start `{}`", argv[0]))?;
    if !status.success() {
        anyhow::bail!("`{}` exited with {status}", argv.join(" "));
    }
    Ok(())
}

/// The end-of-run hook behind `auto_update`: when the setting is on and the last release
/// check already knows a newer version exists, run the self-update without being asked.
///
/// Warn-never-fail, like everything else that runs as a side effect of `devp run` — a
/// broken upgrade path must not turn a successful prune into a failed command.
pub fn maybe_auto_update(registry: &Registry) {
    if !registry.settings.auto_update
        || crate::setup::offline_requested()
        || crate::setup::no_auto_setup_requested()
    {
        return;
    }
    let Some(latest) = registry.latest_known_version.as_deref() else {
        return;
    };
    if compare_versions(constants::VERSION, latest) != Some(Ordering::Less) {
        return;
    }
    println!();
    if let Err(e) = run_install() {
        output::print_warning(&format!(
            "Automatic update failed ({e}). Run `devp update --install` yourself, or \
             `devp config set auto_update false` to stop trying."
        ));
    }
}

/// Quietly keep the release check current and print a one-line notice when the installed
/// build is behind. Returns `true` when the registry changed and needs saving.
///
/// Called from `devp run` and `devp status`. Never returns an error: a background
/// convenience must not be able to fail the command the user actually asked for.
pub fn notify_if_outdated(registry: &mut Registry) -> bool {
    if !registry.settings.update_check {
        return false;
    }

    let interval = registry.settings.update_check_interval_days;
    let due = registry
        .last_update_check
        .is_none_or(|last| Utc::now().signed_duration_since(last).num_days() >= interval);

    if due {
        // The result is deliberately ignored: `refresh_latest` moves the timestamp even
        // when the request fails, and retrying on every command while the machine is
        // offline would put a five-second stall in front of everyday work.
        let _ = refresh_latest(registry);
    }

    if let Some(latest) = registry.latest_known_version.as_deref()
        && compare_versions(constants::VERSION, latest) == Some(Ordering::Less)
    {
        output::print_info(&format!(
            "dev-prune v{latest} is out (you have v{}). `devp update` has the commands; \
                 `devp config set update_check false` silences this.",
            constants::VERSION
        ));
    }

    due
}

/// Ask GitHub for the latest release and record the answer on the registry.
///
/// The caller is responsible for saving; that keeps this usable from both the
/// already-loaded-registry path and the standalone command.
fn refresh_latest(registry: &mut Registry) -> Result<String> {
    let result = latest_release(registry.settings.update_check_timeout_secs);
    registry.last_update_check = Some(Utc::now());
    let latest = result?;
    registry.latest_known_version = Some(latest.clone());
    Ok(latest)
}

/// Say whether the installed build is behind, current, or ahead of the latest release.
fn report_comparison(latest: &str) {
    let installed = constants::VERSION;
    match compare_versions(installed, latest) {
        Some(Ordering::Less) => {
            output::print_warning(&format!(
                "Latest release:    v{latest} — an upgrade is available."
            ));
        }
        Some(Ordering::Equal) => {
            output::print_success(&format!(
                "Latest release:    v{latest} — you are up to date."
            ));
        }
        Some(Ordering::Greater) => {
            // Normal when running a local build between releases.
            output::print_info(&format!(
                "Latest release:    v{latest} — your build is newer than the last published one."
            ));
        }
        None => {
            output::print_info(&format!(
                "Latest release:    v{latest} (could not compare it to v{installed})."
            ));
        }
    }
}

/// Fetch the tag name of the most recent published release.
///
/// Returns the version without any leading `v`, so it can be compared to
/// `CARGO_PKG_VERSION` directly.
fn latest_release(timeout_secs: u64) -> Result<String> {
    if crate::setup::offline_requested() {
        anyhow::bail!("{} is set", constants::ENV_OFFLINE);
    }
    let body = ureq::get(constants::LATEST_RELEASE_API_URL)
        .header("User-Agent", &format!("dev-prune/{}", constants::VERSION))
        .header("Accept", "application/vnd.github+json")
        .config()
        .timeout_global(Some(Duration::from_secs(timeout_secs.max(1))))
        .build()
        .call()
        .context("request failed")?
        .body_mut()
        .read_to_string()
        .context("could not read the response")?;

    let json: serde_json::Value =
        serde_json::from_str(&body).context("the response was not JSON")?;
    let tag = json
        .get("tag_name")
        .and_then(|v| v.as_str())
        .context("the response carried no tag_name")?;

    Ok(tag.trim_start_matches('v').to_string())
}

/// Compare two dotted numeric versions, ignoring any pre-release suffix.
///
/// Returns `None` when either side is not `major.minor.patch` — better to say "could not
/// compare" than to claim an upgrade exists because `1.0.0` sorts before `1.0.0-rc.1`
/// as a string.
pub(crate) fn compare_versions(a: &str, b: &str) -> Option<Ordering> {
    let parse = |v: &str| -> Option<[u64; 3]> {
        let core = v.split(['-', '+']).next()?;
        let mut parts = core.split('.');
        let out = [
            parts.next()?.parse().ok()?,
            parts.next()?.parse().ok()?,
            parts.next()?.parse().ok()?,
        ];
        // A fourth component means this is not the scheme we release under.
        if parts.next().is_some() {
            return None;
        }
        Some(out)
    };
    Some(parse(a)?.cmp(&parse(b)?))
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration as ChronoDuration;

    #[test]
    fn orders_by_component_not_lexically() {
        // "1.10.0" < "1.9.0" as strings, which is the bug this function exists to avoid.
        assert_eq!(compare_versions("1.9.0", "1.10.0"), Some(Ordering::Less));
        assert_eq!(compare_versions("1.0.0", "1.0.0"), Some(Ordering::Equal));
        assert_eq!(
            compare_versions("2.0.0", "1.99.99"),
            Some(Ordering::Greater)
        );
    }

    #[test]
    fn pre_release_suffixes_compare_by_their_core() {
        assert_eq!(
            compare_versions("1.0.0", "1.0.0-rc.1"),
            Some(Ordering::Equal)
        );
        assert_eq!(
            compare_versions("1.0.0+build7", "1.0.1"),
            Some(Ordering::Less)
        );
    }

    #[test]
    fn unparseable_versions_report_no_answer_rather_than_a_wrong_one() {
        assert_eq!(compare_versions("1.0", "1.0.0"), None);
        assert_eq!(compare_versions("1.0.0.1", "1.0.0"), None);
        assert_eq!(compare_versions("nightly", "1.0.0"), None);
    }

    #[test]
    fn the_check_is_on_unless_the_user_turns_it_off() {
        assert!(Registry::default().settings.update_check);
    }

    #[test]
    fn a_disabled_check_touches_neither_the_network_nor_the_registry() {
        let mut registry = Registry::default();
        registry.settings.update_check = false;
        assert!(!notify_if_outdated(&mut registry));
        assert!(registry.last_update_check.is_none());
    }

    #[test]
    fn each_channel_is_recognised_by_its_marker_directory() {
        use std::path::Path;
        let cases: &[(&str, Channel)] = &[
            ("/home/k/.cargo/bin/dev-prune", Channel::Cargo),
            (
                "/usr/lib/node_modules/dev-prune/bin/dev-prune",
                Channel::Npm,
            ),
            (
                "/home/k/.local/share/uv/tools/dev-prune/bin/dev-prune",
                Channel::UvTool,
            ),
            (
                "/home/k/.local/pipx/venvs/dev-prune/bin/dev-prune",
                Channel::Pipx,
            ),
            ("/opt/somewhere/dev-prune", Channel::Unknown),
        ];
        for (path, expected) in cases {
            assert_eq!(detect_channel(Path::new(path), None), *expected, "{path}");
        }
    }

    #[test]
    fn the_managed_copy_wins_over_every_path_heuristic() {
        use std::path::Path;
        // Even a managed dir that happens to live under `.cargo` is the installer's.
        let managed = Path::new("/home/k/.cargo/odd/dev-prune/bin/dev-prune");
        assert_eq!(detect_channel(managed, Some(managed)), Channel::Installer);
    }

    #[test]
    fn auto_update_is_off_by_default_and_silent_when_off() {
        let registry = Registry::default();
        assert!(!registry.settings.auto_update);
        // Must return without touching the network or the terminal.
        maybe_auto_update(&registry);
    }

    #[test]
    fn a_recent_check_is_not_repeated() {
        let mut registry = Registry::default();
        let stamp = Utc::now() - ChronoDuration::days(constants::UPDATE_CHECK_INTERVAL_DAYS - 1);
        registry.last_update_check = Some(stamp);
        // No network call, so the stamp survives untouched and nothing needs saving.
        assert!(!notify_if_outdated(&mut registry));
        assert_eq!(registry.last_update_check, Some(stamp));
    }

    #[test]
    fn the_asset_name_matches_what_the_release_workflow_builds() {
        // This string is a contract with `.github/workflows/release.yml`. Getting it
        // wrong is not a compile error and not a test failure anywhere else — it is a
        // self-update that 404s for every user on the day of a release.
        let name = constants::release_asset_name("1.4.0");
        let expected = match (std::env::consts::OS, std::env::consts::ARCH) {
            ("windows", "x86_64") => Some("dev-prune-v1.4.0-windows-x64.exe"),
            ("windows", "aarch64") => Some("dev-prune-v1.4.0-windows-arm64.exe"),
            ("windows", "x86") => Some("dev-prune-v1.4.0-windows-x86.exe"),
            ("linux", "x86_64") => Some("dev-prune-v1.4.0-linux-x64"),
            ("linux", "aarch64") => Some("dev-prune-v1.4.0-linux-arm64"),
            ("macos", "x86_64") => Some("dev-prune-v1.4.0-darwin-x64"),
            ("macos", "aarch64") => Some("dev-prune-v1.4.0-darwin-arm64"),
            // A platform the release does not build for must decline the direct route
            // rather than download some other platform's binary.
            _ => None,
        };
        assert_eq!(name.as_deref(), expected);
    }

    #[test]
    fn only_windows_has_a_32_bit_asset() {
        // The matrix builds `x86` for Windows alone. On a 32-bit Linux there is nothing
        // to download, and guessing `x64` would install a binary that cannot run.
        let name = constants::release_asset_name("9.9.9");
        if std::env::consts::ARCH == "x86" {
            assert_eq!(name.is_some(), std::env::consts::OS == "windows");
        }
    }

    #[test]
    fn a_sidecar_is_read_as_the_first_field_of_sha256sum_format() {
        let digest = "a".repeat(64);
        assert_eq!(
            parse_sha256_sidecar(&format!("{digest}  dev-prune-v1.4.0-linux-x64\n")).unwrap(),
            digest
        );
        // The Windows step writes it with no trailing newline, and GitHub may serve
        // either line ending.
        assert_eq!(
            parse_sha256_sidecar(&format!("{digest}  asset.exe")).unwrap(),
            digest
        );
        assert_eq!(
            parse_sha256_sidecar(&format!("{}  asset\r\n", digest.to_uppercase())).unwrap(),
            digest,
            "an upper-case digest must compare equal to the one we compute"
        );
    }

    #[test]
    fn anything_that_is_not_a_digest_is_refused_before_it_is_compared() {
        // A 404 page, an error blob or a truncated read must fail as "not a digest"
        // rather than as a mismatch — the two send the user to very different places.
        for bad in [
            "",
            "   ",
            "<!DOCTYPE html>",
            "not-a-hash  asset",
            &"a".repeat(63),
            &"a".repeat(65),
            &format!("{}g  asset", "a".repeat(63)),
        ] {
            assert!(
                parse_sha256_sidecar(bad).is_err(),
                "{bad:?} must not be accepted as a digest"
            );
        }
    }
}