Skip to main content

dev_prune/commands/
update.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Handler for `dev-prune update`, and the periodic release check behind it.
5//
6// The check is opt-*out*. An out-of-date cleanup tool is a tool whose safety fixes you do
7// not have, so `devp update` asks GitHub for the latest release by default, and `devp
8// run` / `devp status` repeat that quietly at most once a week. Both are switched off by
9// `devp config set update_check false`, and `devp update --offline` skips a single run.
10//
11// What leaves the machine is one unauthenticated GET to the public releases endpoint. It
12// carries no identifier, no configuration, no repository paths and no usage data — the
13// only thing the server learns is that some copy of dev-prune asked what the latest
14// version is. Nothing else in the binary opens a socket. See `docs/PRIVACY.md`.
15//
16// By default the command does not download or install anything: replacing a binary is
17// the package manager's job, and doing it ourselves would mean writing to a PATH
18// directory with whatever privileges the user happened to have. `--install` keeps that
19// division of labour — it works out which package manager owns the running binary and
20// runs *that manager's* own upgrade command, rather than writing files itself. The
21// scheduled pass is never interrupted by an upgrade: it runs the managed copy under
22// `<config>/bin`, which is replaced by atomic rename and refreshed from the new binary
23// on the next healthy run (`setup::stable_exe_path`), so a pass already in flight keeps
24// its loaded image and the next pass picks up the new one.
25
26use std::cmp::Ordering;
27use std::fs;
28use std::io::Read;
29use std::path::{Path, PathBuf};
30use std::time::Duration;
31
32use anyhow::{Context, Result};
33use chrono::Utc;
34
35use crate::channel::Channel;
36use crate::config::Registry;
37use crate::constants;
38use crate::output;
39
40pub fn run(offline: bool, install: bool) -> Result<()> {
41    if install {
42        return run_install();
43    }
44    output::print_header("dev-prune version & upgrade");
45
46    output::print_info(&format!("Installed version: v{}", constants::VERSION));
47
48    if offline {
49        output::print_info("Skipping the release check because `--offline` was passed.");
50    } else if let Ok(mut registry) = Registry::load() {
51        if registry.settings.update_check {
52            // An explicit `devp update` always asks, regardless of when the last
53            // automatic check ran — the user is standing there waiting for the answer.
54            match refresh_latest(&mut registry) {
55                Ok(latest) => report_comparison(&latest),
56                // A failed check is not a failed command. Someone offline, behind a
57                // proxy, or hitting a rate limit still wants the upgrade instructions.
58                Err(e) => output::print_warning(&format!(
59                    "Could not reach the release API ({e}). The upgrade commands below still apply."
60                )),
61            }
62            let _ = registry.save();
63        } else {
64            output::print_info(
65                "The release check is off (`devp config set update_check true` re-enables it).",
66            );
67        }
68    }
69
70    println!();
71    println!("  Latest releases:  {}", constants::RELEASES_URL);
72    println!();
73    print_upgrade_commands();
74
75    Ok(())
76}
77
78/// Ask GitHub right now — no interval — and say where the installed build stands.
79///
80/// For `devp init`, which is deliberate and infrequent enough to be worth a round trip:
81/// setting a machine up is exactly the moment to learn the binary is a version behind.
82/// `devp run` deliberately does not use this; it goes through [`notify_if_outdated`],
83/// which is interval-gated so everyday work never waits on the network.
84///
85/// Returns `true` when the registry changed and needs saving.
86pub fn check_now(registry: &mut Registry) -> bool {
87    if !registry.settings.update_check {
88        return false;
89    }
90
91    match refresh_latest(registry) {
92        Ok(latest) => {
93            report_comparison(&latest);
94            if compare_versions(constants::VERSION, &latest) == Some(Ordering::Less) {
95                print_upgrade_commands();
96            }
97        }
98        // Not being able to reach GitHub is not a failed `init`.
99        Err(e) => output::print_info(&format!("Could not check for a newer release ({e}).")),
100    }
101    true
102}
103
104/// Name the one command that upgrades *this* copy, and only fall back to the menu.
105///
106/// The old version printed all eight channels and told the reader to pick the one they
107/// installed from. Nobody remembers that — it was a decision made once, possibly a year
108/// ago, on a machine they have since reimaged. The channel is written in the path of the
109/// running binary and `Channel::detect` already reads it, so asking the user to recall it
110/// was asking for information dev-prune already had.
111fn print_upgrade_commands() {
112    let channel = Channel::detect();
113    match channel.upgrade_command() {
114        Some(command) => {
115            println!("  Installed with {} — upgrade with:", channel.label());
116            println!("    {command}");
117            println!();
118            println!("  Or `devp update --install` to let dev-prune do it for you.");
119        }
120        // `Unknown` means the binary sits somewhere no channel owns — a dev build, a
121        // hand-copied file, a distro package. There is no manager to name, so this is the
122        // one case where the full list is the honest answer.
123        None => {
124            println!("  This copy is not in a location any install channel owns, so there");
125            println!("  is no package manager to name. Replace it in place with:");
126            println!("    devp update --install");
127            println!();
128            println!("  Or install through a channel, which keeps it upgradeable:");
129            println!("    cargo binstall dev-prune --force");
130            println!("    cargo install dev-prune --force");
131            println!("    npm install -g dev-prune@latest");
132            println!("    uv tool upgrade dev-prune  /  pipx upgrade dev-prune");
133            println!("    winget upgrade {}", constants::WINGET_PACKAGE_ID);
134            println!("    scoop update dev-prune  /  brew upgrade dev-prune");
135            println!("    curl -fsSL {} | sh", constants::INSTALL_SH_URL);
136            println!("    iwr -useb {} | iex", constants::INSTALL_PS1_URL);
137        }
138    }
139}
140
141/// `devp update --install`: upgrade this installation to the latest release.
142///
143/// Downloads the release binary from GitHub and replaces the files itself, rather than
144/// asking whichever package manager delivered the first copy to do it. That inversion is
145/// deliberate. There is exactly one binary that matters — the managed copy under
146/// `<config>/bin`, which the git hooks, the scheduler and `PATH` all point at — and it
147/// does not live inside `node_modules`, a uv tool directory or `~/.cargo/bin`. Asking
148/// `uv` to upgrade a file it has never heard of was never going to work, and asking it to
149/// upgrade its *own* copy left the one that actually runs untouched.
150///
151/// So both are replaced: the managed copy first, because that is what runs unattended,
152/// then the running binary if it is a different file, because that is what the user
153/// types. The channel's own bookkeeping (what `uv tool list` believes is installed) is
154/// left stale on purpose — correcting it means running the channel's installer, which is
155/// the one thing this route exists to avoid — and the command to resync it is printed.
156///
157/// Falls back to the channel's own upgrade command when there is no published binary for
158/// this platform or the download fails, so a release-page outage costs the fast path and
159/// not the upgrade.
160fn run_install() -> Result<()> {
161    output::print_header("dev-prune self-update");
162
163    if crate::setup::offline_requested() {
164        anyhow::bail!(
165            "{} is set — an install needs the network by definition.",
166            constants::ENV_OFFLINE
167        );
168    }
169
170    // Know before downloading whether there is anything to download. A failed check is
171    // fatal here (unlike `devp update`): running an installer blind would "upgrade" to
172    // the version already installed.
173    let mut registry = Registry::load()?;
174    let latest = refresh_latest(&mut registry)?;
175    let _ = registry.save();
176    if compare_versions(constants::VERSION, &latest) != Some(Ordering::Less) {
177        output::print_success(&format!(
178            "v{} is already the latest release — nothing to install.",
179            constants::VERSION
180        ));
181        return Ok(());
182    }
183    output::print_info(&format!("Upgrading v{} -> v{latest} …", constants::VERSION));
184
185    let exe = std::env::current_exe().context("could not locate the running binary")?;
186    let managed = crate::setup::managed_exe_path().ok();
187    let channel = Channel::detect_at(&exe, managed.as_deref());
188
189    match install_directly(&latest, &exe, managed.as_deref(), channel) {
190        Ok(()) => {
191            output::print_success(&format!("dev-prune v{latest} installed."));
192            report_channel_bookkeeping(channel);
193            output::print_info(
194                "The scheduled pass was not interrupted: it runs the managed copy, which \
195                 was replaced by atomic rename, so a pass already in flight keeps the \
196                 image it loaded and the next one picks up the new binary.",
197            );
198            return Ok(());
199        }
200        Err(e) => output::print_warning(&format!(
201            "Direct download did not work ({e:#}).\nFalling back to the channel that \
202             installed this copy."
203        )),
204    }
205
206    // On Windows a running executable's file is locked against replacement but not
207    // against rename. Moving it aside first lets the channel write a fresh file at the
208    // real path; the `.old` left behind is swept up by the *next* run, when nothing is
209    // executing it any more.
210    #[cfg(windows)]
211    let aside = {
212        let aside = exe.with_extension("exe.old");
213        let _ = fs::remove_file(&aside);
214        fs::rename(&exe, &aside).ok().map(|_| aside)
215    };
216
217    let result = spawn_channel_upgrade(channel);
218
219    #[cfg(windows)]
220    if let Some(aside) = aside {
221        if result.is_ok() {
222            // Best effort: the file is still our running image, so Windows may refuse
223            // the delete. The sweep at the top of the next `--install` gets it then.
224            let _ = fs::remove_file(&aside);
225        } else if !exe.exists() {
226            // The upgrade never wrote a new binary — put the old one back so the
227            // command the user has on PATH still exists.
228            let _ = fs::rename(&aside, &exe);
229        }
230    }
231    result?;
232
233    output::print_success(&format!("dev-prune v{latest} installed."));
234    output::print_info(
235        "The scheduled pass was not interrupted: it runs the managed copy, which \
236         refreshes itself from the new binary on its next run.",
237    );
238    Ok(())
239}
240
241/// Replace every copy of the binary this installation actually runs, from one download.
242///
243/// The managed copy is done first and is the only one whose failure aborts the upgrade:
244/// it is what the scheduler and the git hooks invoke, so a machine with a fresh managed
245/// copy is upgraded even if nothing else could be written.
246///
247/// Every other path is then written from the same verified bytes, and each is written
248/// with the same rename-aside dance rather than through `ensure_alias`. That matters on
249/// Windows: `ensure_alias` deletes the twin before relinking, and the delete fails when
250/// the twin is the running image — which is exactly the case when the user typed `devp
251/// update --install`. Renaming a running executable is allowed where deleting it is not,
252/// so this route leaves no copy behind on the previous release.
253fn install_directly(
254    latest: &str,
255    exe: &Path,
256    managed: Option<&Path>,
257    channel: Channel,
258) -> Result<()> {
259    let bytes = fetch_release_binary(latest)?;
260    let primary = managed.unwrap_or(exe);
261    install_bytes_at(&bytes, primary)?;
262
263    // Every other file that is a copy of the binary just replaced. Left alone they would
264    // keep running the previous release — silently, because the scheduler and the hooks
265    // both discard their own output by design.
266    let mut also: Vec<PathBuf> = Vec::new();
267    if let Some(dir) = primary.parent() {
268        also.push(dir.join(if cfg!(windows) { "devp.exe" } else { "devp" }));
269    }
270    // …except when a package manager owns the directory the running copy sits in and
271    // replaces that directory wholesale on upgrade. Writing new bytes there leaves WinGet,
272    // Scoop or Homebrew certain they still have the old version installed, and the next
273    // `winget upgrade` puts the old binary back over the top. Their copy is left exactly
274    // as the manager wrote it; `report_channel_bookkeeping` names the command that
275    // actually moves it forward.
276    if primary != exe && exe.is_file() && !channel.replaces_its_directory() {
277        also.push(exe.to_path_buf());
278    }
279    for path in also {
280        if path == primary {
281            continue;
282        }
283        if let Err(e) = install_bytes_at(&bytes, &path) {
284            output::print_warning(&format!(
285                "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.",
286                path.display()
287            ));
288        }
289    }
290
291    // The windowless scheduler twin is a *patched* copy, not a plain one, so it is
292    // rebuilt rather than written — from the managed binary that was just replaced.
293    crate::daemon::refresh_hidden_twin();
294    Ok(())
295}
296
297/// Name the channel's own upgrade command after a direct install, for the one thing the
298/// direct route deliberately leaves untouched: the manager's record of what it installed.
299fn report_channel_bookkeeping(channel: Channel) {
300    // The installer's copy *is* the managed one, and an unrecognised copy has no manager
301    // keeping a version record that could disagree with the binary.
302    let Some(resync) = channel
303        .owns_its_files()
304        .then(|| channel.upgrade_command())
305        .flatten()
306    else {
307        return;
308    };
309    if channel.replaces_its_directory() {
310        output::print_info(&format!(
311            "The managed copy is now v{}. The copy {} installed was left exactly as it \
312             wrote it — replacing a file inside a versioned package directory only makes \
313             the manager and the disk disagree. Run `{resync}` to move that one forward \
314             too.",
315            constants::VERSION,
316            channel.label()
317        ));
318    } else {
319        output::print_info(&format!(
320            "The binaries are up to date. `{resync}` also updates that manager's own \
321             record of the version, which still reads v{}.",
322            constants::VERSION
323        ));
324    }
325}
326
327/// Download release `version`'s binary for this platform and put it at `target`.
328///
329/// The direct route, and the reason `devp update --install` no longer depends on the
330/// package manager that happened to deliver the first copy. Whatever installed it, the
331/// binary the hooks, the scheduler and `PATH` all point at is one file in the config
332/// directory, and this replaces that file. `uv`, `npm` and `cargo` are delivery
333/// channels; they are not the source of truth, and asking one of them to upgrade a file
334/// living under another one's directory was never going to work.
335///
336/// Refuses to install anything whose SHA-256 does not match the sidecar published beside
337/// it. That check is the entire safety story for this path: the bytes are about to
338/// become the binary the machine runs on a schedule.
339fn fetch_release_binary(version: &str) -> Result<Vec<u8>> {
340    let asset = constants::release_asset_name(version).with_context(|| {
341        format!(
342            "no published binary for {}-{}; upgrade through the channel that installed \
343             this copy instead",
344            std::env::consts::OS,
345            std::env::consts::ARCH
346        )
347    })?;
348    let base = format!("{}/v{version}/{asset}", constants::RELEASE_DOWNLOAD_BASE);
349
350    let expected = fetch_expected_hash(&format!("{base}.sha256"))?;
351    output::print_info(&format!("Downloading {asset} …"));
352    let bytes = fetch_bytes(&base)?;
353
354    let actual = {
355        use sha2::{Digest, Sha256};
356        use std::fmt::Write as _;
357        let mut h = Sha256::new();
358        h.update(&bytes);
359        // Hex-encoded by hand: sha2 0.11 returns a `hybrid_array::Array`, which has no
360        // `LowerHex`, and the sidecar is lower-case hex either way.
361        h.finalize().iter().fold(String::new(), |mut s, b| {
362            let _ = write!(s, "{b:02x}");
363            s
364        })
365    };
366    if actual != expected {
367        anyhow::bail!(
368            "checksum mismatch for {asset}\n  expected {expected}\n  got      {actual}\n\
369             The download was corrupted or tampered with; nothing was installed."
370        );
371    }
372
373    Ok(bytes)
374}
375
376/// Write already-verified bytes over one binary.
377///
378/// Separate from the download so a single transfer can serve every copy that has to be
379/// replaced — the managed binary, its `devp` twin, and whatever the user is running —
380/// instead of fetching the same megabytes once per path.
381fn install_bytes_at(bytes: &[u8], target: &Path) -> Result<()> {
382    // Staged beside the target and renamed in, so a write that dies half-way leaves the
383    // working binary untouched rather than a truncated file where the scheduler expects
384    // an executable.
385    let staging = target.with_extension("new");
386    if let Some(parent) = target.parent() {
387        fs::create_dir_all(parent).ok();
388    }
389    fs::write(&staging, bytes).with_context(|| format!("could not write {}", staging.display()))?;
390
391    #[cfg(unix)]
392    {
393        use std::os::unix::fs::PermissionsExt;
394        // Downloaded files are 0644; the scheduler needs to be able to run this.
395        let _ = fs::set_permissions(&staging, fs::Permissions::from_mode(0o755));
396    }
397
398    replace_binary(&staging, target)
399}
400
401/// Read the hash out of a `.sha256` sidecar published beside a release asset.
402fn fetch_expected_hash(url: &str) -> Result<String> {
403    let body = String::from_utf8(fetch_bytes(url)?).context("the checksum sidecar was not text")?;
404    parse_sha256_sidecar(&body)
405}
406
407/// The parsing half of [`fetch_expected_hash`], which is `sha256sum` format: the hex
408/// digest, two spaces, the file name.
409///
410/// Validated rather than trusted, because the failure this guards against is not a
411/// malformed checksum — it is a 404 page or a proxy error blob arriving where the sidecar
412/// should be. Comparing a digest against `<!DOCTYPE html>` would report a checksum
413/// mismatch, which reads as "someone tampered with the download" and sends the user
414/// somewhere alarming and wrong.
415fn parse_sha256_sidecar(body: &str) -> Result<String> {
416    let hash = body
417        .split_whitespace()
418        .next()
419        .context("the checksum sidecar was empty")?
420        .to_ascii_lowercase();
421    if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
422        anyhow::bail!("the checksum sidecar did not contain a SHA-256 digest");
423    }
424    Ok(hash)
425}
426
427fn fetch_bytes(url: &str) -> Result<Vec<u8>> {
428    let mut body = ureq::get(url)
429        .header("User-Agent", &format!("dev-prune/{}", constants::VERSION))
430        .config()
431        .timeout_global(Some(Duration::from_secs(
432            constants::UPDATE_DOWNLOAD_TIMEOUT_SECS,
433        )))
434        .build()
435        .call()
436        .with_context(|| format!("could not download {url}"))?;
437    let mut buf = Vec::new();
438    body.body_mut()
439        .as_reader()
440        .read_to_end(&mut buf)
441        .with_context(|| format!("could not read {url}"))?;
442    Ok(buf)
443}
444
445/// Move `staged` onto `target`, working around the one platform that will not overwrite
446/// a file it is executing.
447fn replace_binary(staged: &Path, target: &Path) -> Result<()> {
448    // On Windows a running image is locked against replacement but not against rename,
449    // so the live file steps aside and the new one takes its name. The `.old` is swept
450    // by the next run, when nothing holds it open any more.
451    #[cfg(windows)]
452    let aside = {
453        let aside = target.with_extension("exe.old");
454        let _ = fs::remove_file(&aside);
455        target
456            .exists()
457            .then(|| fs::rename(target, &aside).ok().map(|_| aside))
458            .flatten()
459    };
460
461    match fs::rename(staged, target) {
462        Ok(()) => {
463            #[cfg(windows)]
464            if let Some(aside) = aside {
465                let _ = fs::remove_file(&aside);
466            }
467            Ok(())
468        }
469        Err(e) => {
470            let _ = fs::remove_file(staged);
471            #[cfg(windows)]
472            if let Some(aside) = aside
473                && !target.exists()
474            {
475                // Put the working binary back rather than leaving the machine with no
476                // `dev-prune` at all.
477                let _ = fs::rename(&aside, target);
478            }
479            Err(e).with_context(|| format!("could not install {}", target.display()))
480        }
481    }
482}
483
484/// Run one channel's own upgrade command, wired to the terminal so its progress and
485/// prompts reach the user directly.
486fn spawn_channel_upgrade(channel: Channel) -> Result<()> {
487    let install_ps1 = format!("iwr -useb {} | iex", constants::INSTALL_PS1_URL);
488    let install_sh = format!("curl -fsSL {} | sh", constants::INSTALL_SH_URL);
489    let winget_id = constants::WINGET_PACKAGE_ID;
490    let argv: Vec<&str> = match channel {
491        Channel::Cargo => {
492            // binstall pulls the prebuilt release; plain `cargo install` compiles for
493            // minutes. Prefer the fast one when it exists.
494            if crate::adapters::binary_available("cargo-binstall") {
495                vec!["cargo", "binstall", "dev-prune", "--force", "-y"]
496            } else {
497                vec!["cargo", "install", "dev-prune", "--force"]
498            }
499        }
500        Channel::Npm => vec!["npm", "install", "-g", "dev-prune@latest"],
501        Channel::UvTool => vec!["uv", "tool", "upgrade", "dev-prune"],
502        Channel::Pipx => vec!["pipx", "upgrade", "dev-prune"],
503        Channel::Pip => vec!["pip", "install", "--upgrade", "dev-prune"],
504        // The three that own their whole package directory. Each is given its own
505        // command rather than the direct download, because replacing a file inside a
506        // versioned package directory desynchronises the manager from what is on disk —
507        // and the next `winget upgrade` or `brew upgrade` would put the old binary back.
508        Channel::WinGet => vec![
509            "winget",
510            "upgrade",
511            "--id",
512            winget_id,
513            "--accept-package-agreements",
514            "--accept-source-agreements",
515        ],
516        Channel::Scoop => vec!["scoop", "update", "dev-prune"],
517        Channel::Homebrew => vec!["brew", "upgrade", "dev-prune"],
518        Channel::Installer => {
519            if cfg!(windows) {
520                vec!["powershell", "-NoProfile", "-Command", &install_ps1]
521            } else {
522                vec!["sh", "-c", &install_sh]
523            }
524        }
525        Channel::Unknown => {
526            output::print_warning(
527                "Could not tell which channel installed this binary, so nothing was \
528                 changed. Upgrade it yourself with one of:",
529            );
530            print_upgrade_commands();
531            anyhow::bail!("unrecognised install channel");
532        }
533    };
534
535    output::print_info(&format!("Running: {}", argv.join(" ")));
536    let status = crate::spawn::command(crate::adapters::resolve_program(argv[0]))
537        .args(&argv[1..])
538        .status()
539        .with_context(|| format!("could not start `{}`", argv[0]))?;
540    if !status.success() {
541        anyhow::bail!("`{}` exited with {status}", argv.join(" "));
542    }
543    Ok(())
544}
545
546/// The end-of-run hook behind `auto_update`: when the setting is on and the last release
547/// check already knows a newer version exists, replace the binary without being asked.
548///
549/// Warn-never-fail, like everything else that runs as a side effect of `devp run` — a
550/// broken upgrade path must not turn a successful prune into a failed command.
551///
552/// Deliberately *not* `run_install`. That function falls back to running the package
553/// manager that installed this copy, and this is the path that runs unattended: from the
554/// scheduled pass, from a git hook, from `devp run` in the middle of someone else's
555/// work. Spawning `winget upgrade` there can raise an elevation prompt and can pull in
556/// upgrades nobody asked about. Download-and-replace is safe unattended; handing the
557/// machine to a package manager is a decision, and decisions stay with the person.
558pub fn maybe_auto_update(registry: &Registry) {
559    if !registry.settings.auto_update
560        || crate::setup::offline_requested()
561        || crate::setup::no_auto_setup_requested()
562    {
563        return;
564    }
565    let Some(latest) = registry.latest_known_version.as_deref() else {
566        return;
567    };
568    if compare_versions(constants::VERSION, latest) != Some(Ordering::Less) {
569        return;
570    }
571
572    let Ok(exe) = std::env::current_exe() else {
573        return;
574    };
575    let managed = crate::setup::managed_exe_path().ok();
576    let channel = Channel::detect_at(&exe, managed.as_deref());
577
578    // WinGet, Scoop and Homebrew swap their whole package directory on upgrade, so bytes
579    // written there are undone by the next `winget upgrade` — which would still believe
580    // the old version is installed. Those channels own the upgrade, and
581    // `notify_if_outdated` has already printed the line naming the right command.
582    if channel.replaces_its_directory() {
583        return;
584    }
585
586    println!();
587    output::print_info(&format!(
588        "Updating dev-prune v{} -> v{latest} …",
589        constants::VERSION
590    ));
591    match install_directly(latest, &exe, managed.as_deref(), channel) {
592        Ok(()) => {
593            output::print_success(&format!("dev-prune v{latest} installed."));
594            report_channel_bookkeeping(channel);
595        }
596        Err(e) => output::print_warning(&format!(
597            "Automatic update failed ({e:#}). Run `devp update --install` yourself, or \
598             `devp config set auto_update false` to stop trying."
599        )),
600    }
601}
602
603/// Quietly keep the release check current and print a one-line notice when the installed
604/// build is behind. Returns `true` when the registry changed and needs saving.
605///
606/// Called from `devp run` and `devp status`. Never returns an error: a background
607/// convenience must not be able to fail the command the user actually asked for.
608pub fn notify_if_outdated(registry: &mut Registry) -> bool {
609    if !registry.settings.update_check {
610        return false;
611    }
612
613    let interval = registry.settings.update_check_interval_days;
614    let due = registry
615        .last_update_check
616        .is_none_or(|last| Utc::now().signed_duration_since(last).num_days() >= interval);
617
618    if due {
619        // The result is deliberately ignored: `refresh_latest` moves the timestamp even
620        // when the request fails, and retrying on every command while the machine is
621        // offline would put a five-second stall in front of everyday work.
622        let _ = refresh_latest(registry);
623    }
624
625    if let Some(latest) = registry.latest_known_version.as_deref()
626        && compare_versions(constants::VERSION, latest) == Some(Ordering::Less)
627    {
628        output::print_info(&format!(
629            "dev-prune v{latest} is out (you have v{}). `devp update` has the commands; \
630                 `devp config set update_check false` silences this.",
631            constants::VERSION
632        ));
633    }
634
635    due
636}
637
638/// Ask GitHub for the latest release and record the answer on the registry.
639///
640/// The caller is responsible for saving; that keeps this usable from both the
641/// already-loaded-registry path and the standalone command.
642fn refresh_latest(registry: &mut Registry) -> Result<String> {
643    let result = latest_release(registry.settings.update_check_timeout_secs);
644    registry.last_update_check = Some(Utc::now());
645    let latest = result?;
646    registry.latest_known_version = Some(latest.clone());
647    Ok(latest)
648}
649
650/// Say whether the installed build is behind, current, or ahead of the latest release.
651fn report_comparison(latest: &str) {
652    let installed = constants::VERSION;
653    match compare_versions(installed, latest) {
654        Some(Ordering::Less) => {
655            output::print_warning(&format!(
656                "Latest release:    v{latest} — an upgrade is available."
657            ));
658        }
659        Some(Ordering::Equal) => {
660            output::print_success(&format!(
661                "Latest release:    v{latest} — you are up to date."
662            ));
663        }
664        Some(Ordering::Greater) => {
665            // Normal when running a local build between releases.
666            output::print_info(&format!(
667                "Latest release:    v{latest} — your build is newer than the last published one."
668            ));
669        }
670        None => {
671            output::print_info(&format!(
672                "Latest release:    v{latest} (could not compare it to v{installed})."
673            ));
674        }
675    }
676}
677
678/// Fetch the tag name of the most recent published release.
679///
680/// Returns the version without any leading `v`, so it can be compared to
681/// `CARGO_PKG_VERSION` directly.
682fn latest_release(timeout_secs: u64) -> Result<String> {
683    if crate::setup::offline_requested() {
684        anyhow::bail!("{} is set", constants::ENV_OFFLINE);
685    }
686    let body = ureq::get(constants::LATEST_RELEASE_API_URL)
687        .header("User-Agent", &format!("dev-prune/{}", constants::VERSION))
688        .header("Accept", "application/vnd.github+json")
689        .config()
690        .timeout_global(Some(Duration::from_secs(timeout_secs.max(1))))
691        .build()
692        .call()
693        .context("request failed")?
694        .body_mut()
695        .read_to_string()
696        .context("could not read the response")?;
697
698    let json: serde_json::Value =
699        serde_json::from_str(&body).context("the response was not JSON")?;
700    let tag = json
701        .get("tag_name")
702        .and_then(|v| v.as_str())
703        .context("the response carried no tag_name")?;
704
705    Ok(tag.trim_start_matches('v').to_string())
706}
707
708/// Compare two dotted numeric versions, ignoring any pre-release suffix.
709///
710/// Returns `None` when either side is not `major.minor.patch` — better to say "could not
711/// compare" than to claim an upgrade exists because `1.0.0` sorts before `1.0.0-rc.1`
712/// as a string.
713pub(crate) fn compare_versions(a: &str, b: &str) -> Option<Ordering> {
714    let parse = |v: &str| -> Option<[u64; 3]> {
715        let core = v.split(['-', '+']).next()?;
716        let mut parts = core.split('.');
717        let out = [
718            parts.next()?.parse().ok()?,
719            parts.next()?.parse().ok()?,
720            parts.next()?.parse().ok()?,
721        ];
722        // A fourth component means this is not the scheme we release under.
723        if parts.next().is_some() {
724            return None;
725        }
726        Some(out)
727    };
728    Some(parse(a)?.cmp(&parse(b)?))
729}
730
731#[cfg(test)]
732mod tests {
733    use super::*;
734    use chrono::Duration as ChronoDuration;
735
736    #[test]
737    fn orders_by_component_not_lexically() {
738        // "1.10.0" < "1.9.0" as strings, which is the bug this function exists to avoid.
739        assert_eq!(compare_versions("1.9.0", "1.10.0"), Some(Ordering::Less));
740        assert_eq!(compare_versions("1.0.0", "1.0.0"), Some(Ordering::Equal));
741        assert_eq!(
742            compare_versions("2.0.0", "1.99.99"),
743            Some(Ordering::Greater)
744        );
745    }
746
747    #[test]
748    fn pre_release_suffixes_compare_by_their_core() {
749        assert_eq!(
750            compare_versions("1.0.0", "1.0.0-rc.1"),
751            Some(Ordering::Equal)
752        );
753        assert_eq!(
754            compare_versions("1.0.0+build7", "1.0.1"),
755            Some(Ordering::Less)
756        );
757    }
758
759    #[test]
760    fn unparseable_versions_report_no_answer_rather_than_a_wrong_one() {
761        assert_eq!(compare_versions("1.0", "1.0.0"), None);
762        assert_eq!(compare_versions("1.0.0.1", "1.0.0"), None);
763        assert_eq!(compare_versions("nightly", "1.0.0"), None);
764    }
765
766    #[test]
767    fn the_check_is_on_unless_the_user_turns_it_off() {
768        assert!(Registry::default().settings.update_check);
769    }
770
771    #[test]
772    fn a_disabled_check_touches_neither_the_network_nor_the_registry() {
773        let mut registry = Registry::default();
774        registry.settings.update_check = false;
775        assert!(!notify_if_outdated(&mut registry));
776        assert!(registry.last_update_check.is_none());
777    }
778
779    #[test]
780    fn auto_update_is_on_by_default_and_silent_with_nothing_to_install() {
781        let registry = Registry::default();
782        assert!(registry.settings.auto_update);
783        // No release check has run, so `latest_known_version` is unset and this must
784        // return without touching the network or the terminal. The default being *on* is
785        // what makes that early return load-bearing rather than incidental.
786        assert!(registry.latest_known_version.is_none());
787        maybe_auto_update(&registry);
788    }
789
790    #[test]
791    fn a_recent_check_is_not_repeated() {
792        let mut registry = Registry::default();
793        let stamp = Utc::now() - ChronoDuration::days(constants::UPDATE_CHECK_INTERVAL_DAYS - 1);
794        registry.last_update_check = Some(stamp);
795        // No network call, so the stamp survives untouched and nothing needs saving.
796        assert!(!notify_if_outdated(&mut registry));
797        assert_eq!(registry.last_update_check, Some(stamp));
798    }
799
800    #[test]
801    fn the_asset_name_matches_what_the_release_workflow_builds() {
802        // This string is a contract with `.github/workflows/release.yml`. Getting it
803        // wrong is not a compile error and not a test failure anywhere else — it is a
804        // self-update that 404s for every user on the day of a release.
805        let name = constants::release_asset_name("1.4.0");
806        let expected = match (std::env::consts::OS, std::env::consts::ARCH) {
807            ("windows", "x86_64") => Some("dev-prune-v1.4.0-windows-x64.exe"),
808            ("windows", "aarch64") => Some("dev-prune-v1.4.0-windows-arm64.exe"),
809            ("windows", "x86") => Some("dev-prune-v1.4.0-windows-x86.exe"),
810            ("linux", "x86_64") => Some("dev-prune-v1.4.0-linux-x64"),
811            ("linux", "aarch64") => Some("dev-prune-v1.4.0-linux-arm64"),
812            ("macos", "x86_64") => Some("dev-prune-v1.4.0-darwin-x64"),
813            ("macos", "aarch64") => Some("dev-prune-v1.4.0-darwin-arm64"),
814            // A platform the release does not build for must decline the direct route
815            // rather than download some other platform's binary.
816            _ => None,
817        };
818        assert_eq!(name.as_deref(), expected);
819    }
820
821    #[test]
822    fn only_windows_has_a_32_bit_asset() {
823        // The matrix builds `x86` for Windows alone. On a 32-bit Linux there is nothing
824        // to download, and guessing `x64` would install a binary that cannot run.
825        let name = constants::release_asset_name("9.9.9");
826        if std::env::consts::ARCH == "x86" {
827            assert_eq!(name.is_some(), std::env::consts::OS == "windows");
828        }
829    }
830
831    #[test]
832    fn a_sidecar_is_read_as_the_first_field_of_sha256sum_format() {
833        let digest = "a".repeat(64);
834        assert_eq!(
835            parse_sha256_sidecar(&format!("{digest}  dev-prune-v1.4.0-linux-x64\n")).unwrap(),
836            digest
837        );
838        // The Windows step writes it with no trailing newline, and GitHub may serve
839        // either line ending.
840        assert_eq!(
841            parse_sha256_sidecar(&format!("{digest}  asset.exe")).unwrap(),
842            digest
843        );
844        assert_eq!(
845            parse_sha256_sidecar(&format!("{}  asset\r\n", digest.to_uppercase())).unwrap(),
846            digest,
847            "an upper-case digest must compare equal to the one we compute"
848        );
849    }
850
851    #[test]
852    fn anything_that_is_not_a_digest_is_refused_before_it_is_compared() {
853        // A 404 page, an error blob or a truncated read must fail as "not a digest"
854        // rather than as a mismatch — the two send the user to very different places.
855        for bad in [
856            "",
857            "   ",
858            "<!DOCTYPE html>",
859            "not-a-hash  asset",
860            &"a".repeat(63),
861            &"a".repeat(65),
862            &format!("{}g  asset", "a".repeat(63)),
863        ] {
864            assert!(
865                parse_sha256_sidecar(bad).is_err(),
866                "{bad:?} must not be accepted as a digest"
867            );
868        }
869    }
870}