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