govmr 2.2.0

A high-performance, asynchronous Go Version Manager with a slick terminal UI.
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
//! Module manager - Core lifecycle coordinator for fetching, installing, switching, and deleting Go versions.

mod archive;
mod install;

#[cfg(test)]
pub(crate) use archive::check_archive_magic;
pub(crate) use install::InstallProgress;

use crate::{
    completions, config,
    config::Config,
    errors::GovmError,
    logging,
    shim::ShimManager,
    theme::{Theme, ThemeName},
    version::{compare_versions, GoRelease, GoVersion},
};
use futures_util::StreamExt;
use std::{
    env::{
        self,
        consts::{ARCH, OS},
    },
    fs::{self, File},
    path::{Path, PathBuf},
    sync::Mutex,
    time::{Duration, Instant},
};

// ---------------------------------- Types, Variables & Constants ------------------------------ //

/// Prevents a console window from appearing.
#[cfg(windows)]
const CREATE_NO_WINDOW: u32 = 0x0800_0000;

// ------------------------------------------ Types & Impls ------------------------------------- //

/// Primary orchestrator managing installed toolchains, downloads, and version switching.
pub(crate) struct GoManager {
    /// Base configuration directory (`~/.govmr`).
    base_dir: PathBuf,
    /// Root directory storing extracted Go toolchains (`~/.govmr/versions`).
    versions_dir: PathBuf,
    /// Directory storing temporary download archives (`~/.govmr/downloads`).
    downloads_dir: PathBuf,
    /// Handler for creating and managing executable binary shims.
    shim_mgr: ShimManager,
    /// Persisted user preferences (color theme, …), mutable behind a lock so the
    /// theme can be switched from the `Arc<GoManager>` used by the TUI and CLI.
    config: Mutex<Config>,
    /// Reusable asynchronous HTTP client for network operations.
    client: reqwest::Client,
}
impl GoManager {
    // ------------------------------------- Public (crate) API ------------------------------------- //

    /// Initializes a new instance of `GoManager`, creating required directories if missing.
    ///
    /// # Errors
    /// Returns [`GovmError`] if directory creation or initialization fails.
    pub(crate) fn new() -> Result<Self, GovmError> {
        let home = dirs::home_dir().ok_or(GovmError::HomeNotFound)?;
        let base_dir = home.join(".govmr");
        let versions_dir = base_dir.join("versions");
        let downloads_dir = base_dir.join("downloads");

        fs::create_dir_all(&versions_dir)?;
        fs::create_dir_all(&downloads_dir)?;

        let config = Mutex::new(Config::load(&base_dir));

        Ok(Self {
            base_dir,
            versions_dir,
            downloads_dir,
            shim_mgr: ShimManager::new()?,
            config,
            client: reqwest::Client::builder()
                .timeout(Duration::from_mins(5))
                .build()?,
        })
    }

    /// Provides access to the underlying [`ShimManager`].
    pub(crate) fn get_shim_manager(&self) -> &ShimManager {
        &self.shim_mgr
    }

    /// Returns the user's currently selected color theme.
    pub(crate) fn theme_name(&self) -> ThemeName {
        // A poisoned lock only means another thread panicked mid-update; the
        // config value itself is still readable.
        self.config
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .theme
    }

    /// Returns the concrete palette for the currently selected theme.
    pub(crate) fn theme(&self) -> Theme {
        Theme::for_name(self.theme_name())
    }

    /// Persists a new color-theme choice and returns the resulting palette.
    ///
    /// # Errors
    /// Returns [`GovmError::Io`] if the updated configuration cannot be persisted.
    pub(crate) fn set_theme(&self, theme: ThemeName) -> Result<Theme, GovmError> {
        self.config
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .set_theme(theme)?;
        logging::info(&format!(
            "theme: set name={} config=\"{}\"",
            theme.key(),
            self.base_dir.join("config.toml").display()
        ));
        Ok(Theme::for_name(theme))
    }

    /// Lists the versions present on disk as bare version strings, newest first.
    ///
    /// Purely local (a single `readdir`), so it is cheap enough to call from the
    /// session bookend where the log needs the final installed state.
    #[must_use]
    pub(crate) fn installed_versions(&self) -> Vec<String> {
        let mut versions = Vec::new();
        if let Ok(entries) = fs::read_dir(&self.versions_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                // Only count a directory as installed if it has a `bin/` — the
                // same rule the manifest cross-reference uses.
                if path.is_dir()
                    && path.join("bin").exists()
                    && let Some(name) = path.file_name().and_then(|n| n.to_str())
                {
                    versions.push(name.strip_prefix("go").unwrap_or(name).to_string());
                }
            }
        }
        versions.sort_by(|a, b| compare_versions(b, a));
        versions
    }

    /// Retrieves the currently active Go version string from disk, if set.
    pub(crate) fn get_active_version(&self) -> Option<String> {
        let active_file = self.base_dir.join("active_version");
        fs::read_to_string(active_file)
            .ok()
            .map(|v| v.trim().to_string())
    }

    /// Queries `go.dev` for available Go releases and cross-references them against locally installed versions.
    ///
    /// # Errors
    /// Returns [`GovmError::Network`] if the request fails or [`GovmError::Io`] on filesystem read failure.
    pub(crate) async fn fetch_versions(&self) -> Result<Vec<GoVersion>, GovmError> {
        let url = "https://go.dev/dl/?mode=json&include=all";
        // Which files we will accept is part of the request, so normalize the
        // host identity *before* fetching and log it: "why is 1.20.14 missing"
        // is answered by the arch token, and the two lines must agree on names.
        let go_os = match OS {
            "macos" => "darwin",
            other => other,
        };
        let go_arch = match ARCH {
            "x86_64" => "amd64",
            "aarch64" => "arm64",
            other => other,
        };
        logging::debug(&format!(
            "refresh started: url={url} os={go_os} arch={go_arch}"
        ));
        let res = self.client.get(url).send().await.map_err(|e| {
            logging::error(&format!("refresh: failed stage=request error=\"{e}\""));
            GovmError::from(e)
        })?;
        let status = res.status();
        if !status.is_success() {
            logging::error(&format!(
                "refresh: failed stage=response status={status} url={}",
                res.url()
            ));
            return Err(GovmError::HttpStatus {
                status: status.as_u16(),
                url: res.url().to_string(),
            });
        }
        let releases: Vec<GoRelease> = res.json().await.map_err(|e| {
            logging::error(&format!("refresh: failed stage=decode error=\"{e}\""));
            GovmError::from(e)
        })?;

        let active_version = self.get_active_version();
        let mut versions = Vec::new();
        // Releases that ship no archive for this host OS/arch (e.g. a `linux-386`
        // only build). Counted so "missing version" reports can be told apart
        // from "version does not exist".
        let mut skipped = 0usize;

        for release in releases {
            let ver_clean = release.version.trim_start_matches("go").to_string();
            if let Some(file) = release
                .files
                .into_iter()
                .find(|f| f.os == go_os && f.arch == go_arch)
            {
                let install_dir = self.versions_dir.join(format!("go{ver_clean}"));
                let installed = install_dir.join("bin").exists();
                let active = active_version.as_deref() == Some(&ver_clean);

                versions.push(GoVersion {
                    raw_version: ver_clean.clone(),
                    display_name: format!("go{ver_clean}"),
                    filename: file.filename.clone(),
                    url: format!("https://go.dev/dl/{}", file.filename),
                    size: file.size as u64,
                    installed,
                    active,
                    path: if installed { Some(install_dir) } else { None },
                    stable: release.stable,
                });
            } else {
                skipped += 1;
            }
        }

        versions.sort_by(|a, b| compare_versions(&b.raw_version, &a.raw_version));
        logging::info(&format!(
            "refresh ok: count={} os={go_os} arch={go_arch} skipped={skipped}",
            versions.len()
        ));
        Ok(versions)
    }

    /// Sets the specified version as active by generating shims and recording selection on disk.
    ///
    /// # Returns
    /// Returns `true` if the shim directory is correctly configured in system `PATH`.
    ///
    /// # Errors
    /// Returns [`GovmError`] if shim generation or the active-version file
    /// write fails, or [`GovmError::NotInstalled`] if the version has no local path.
    pub(crate) fn switch_version(&self, version: &GoVersion) -> Result<bool, GovmError> {
        // "Version X is not installed" is misleading unless the log says *where*
        // we looked, so a stale manifest entry can be told apart from a
        // genuinely missing toolchain directory.
        let Some(version_path) = version.path.as_ref() else {
            let expected = self.versions_dir.join(format!("go{}", version.raw_version));
            logging::warn(&format!(
                "use rejected: version={} reason=no_path_in_manifest checked=\"{}\" manifest_installed={} bin_present={}",
                version.raw_version,
                expected.display(),
                version.installed,
                expected.join("bin").exists()
            ));
            return Err(GovmError::NotInstalled(version.raw_version.clone()));
        };
        let bin_dir = version_path.join("bin");

        self.shim_mgr.setup_shims_for_version(&bin_dir)?;

        let active_file = self.base_dir.join("active_version");
        fs::write(&active_file, &version.raw_version)?;

        let is_in_path = self.shim_mgr.is_in_path();
        logging::info(&format!(
            "use: activated version={} shim_in_path={} active_file=\"{}\"",
            version.raw_version,
            is_in_path,
            active_file.display()
        ));
        Ok(is_in_path)
    }

    /// Deletes an installed Go version from disk.
    ///
    /// # Errors
    /// Returns [`GovmError::CannotDeleteActive`] if trying to delete the active version,
    /// or [`GovmError::NotInstalled`] if the version is not found locally.
    #[allow(clippy::unused_self)]
    pub(crate) fn delete_version(&self, version: &GoVersion) -> Result<(), GovmError> {
        if !version.installed {
            return Err(GovmError::NotInstalled(version.raw_version.clone()));
        }
        if version.active {
            return Err(GovmError::CannotDeleteActive(version.raw_version.clone()));
        }
        if let Some(path) = &version.path
            && path.exists()
        {
            let freed = dir_size(path);
            fs::remove_dir_all(path)?;
            logging::info(&format!(
                "delete: removed version={} freed_bytes={freed} freed=\"{}\" path=\"{}\"",
                version.raw_version,
                GoVersion::format_size(freed),
                path.display()
            ));
        } else {
            logging::warn(&format!(
                "delete: removed version={} freed_bytes=0 note=no_path_on_disk",
                version.raw_version
            ));
        }
        Ok(())
    }

    /// Applies the permanent PATH fix by running the platform snippet in a
    /// hidden child process and returns a human-readable summary of
    /// exactly what was done, so the UI can reassure the user.
    ///
    /// * **Windows**: runs an idempotent `PowerShell` snippet that appends the
    ///   shim dir to the *User* PATH (no `setx`, so no 1024-char truncation).
    ///   Only takes effect in *new* terminal sessions (Windows limitation).
    /// * **Unix**: appends an `export PATH=...` line to the detected shell
    ///   profile (`~/.zshrc` / `~/.config/fish/config.fish` / `~/.bashrc`),
    ///   guarded by a marker comment so repeats never duplicate it.
    ///
    /// # Errors
    /// Returns [`GovmError`] if the home dir cannot be resolved, the profile
    /// cannot be written, or the child process fails to spawn/run.
    pub(crate) fn fix_path_permanently(&self) -> Result<Vec<String>, GovmError> {
        let shim_dir = self.shim_mgr.get_shim_dir();
        let shim = shim_dir.to_string_lossy().to_string();

        #[cfg(windows)]
        {
            use std::{os::windows::process::CommandExt, process};

            // Idempotent, truncation-safe User-PATH update. Hidden window so
            // the TUI is never clobbered by a console flash.
            let script = format!(
                "$p=[Environment]::GetEnvironmentVariable('PATH','User');\
                 if($p -notlike \"*{shim}*\"){{[Environment]::SetEnvironmentVariable('PATH',\"$p;{shim}\",'User')}}",
            );
            let status = process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-NonInteractive",
                    "-WindowStyle",
                    "Hidden",
                    "-Command",
                    &script,
                ])
                .creation_flags(CREATE_NO_WINDOW) // CREATE_NO_WINDOW: never flash a console
                .status()?;
            if !status.success() {
                return Err(GovmError::Extraction(format!(
                    "PowerShell PATH fix exited with {}",
                    status
                )));
            }

            logging::info("fix-path: applied target=windows_user_path note=new_terminals_only");
            Ok(vec![
                "Done — ran in a hidden PowerShell window:".to_string(),
                format!("    {script}"),
                "Open a NEW terminal for `go` to resolve.".to_string(),
            ])
        }

        #[cfg(unix)]
        {
            use std::io::Write;

            let home = dirs::home_dir().ok_or(GovmError::HomeNotFound)?;
            let profile = match std::env::var("SHELL").unwrap_or_default().as_str() {
                s if s.ends_with("/zsh") => home.join(".zshrc"),
                s if s.ends_with("/fish") => home.join(".config/fish/config.fish"),
                _ => home.join(".bashrc"),
            };
            let marker = "# Added by govmr";

            let existing = fs::read_to_string(&profile).unwrap_or_default();
            // Idempotency guard: never append the same line twice.
            if existing.lines().any(|l| l.trim_start().starts_with(marker)) {
                logging::info(&format!(
                    "fix-path: skipped profile=\"{}\" reason=already_patched",
                    profile.display()
                ));
                return Ok(vec![
                    format!(
                        "Already done — {} already contains the govmr export line.",
                        profile.display()
                    ),
                    "Open a NEW terminal (or source it) for `go` to resolve.".to_string(),
                ]);
            }

            let source_path = format!("export PATH=\"{shim}:$PATH\"");
            let mut file = fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(&profile)?;
            writeln!(file)?;
            writeln!(file, "{marker}")?;
            writeln!(file, "{source_path}")?;

            logging::info(&format!(
                "fix-path: applied profile=\"{}\" line=\"{source_path}\"",
                profile.display()
            ));
            Ok(vec![
                format!("Done — appended to {}:", profile.display()),
                format!("    {source_path}"),
                "Open a NEW terminal (or source it) for `go` to resolve.".to_string(),
            ])
        }
    }

    /// Checks GitHub for a newer release tag. Returns `Some(version)` if an update is available.
    ///
    /// # Errors
    /// Returns [`GovmError`] if the release query or its response parsing fails.
    pub(crate) async fn check_for_update(&self) -> Result<Option<String>, GovmError> {
        logging::debug("update check: started");
        let res = self
            .client
            .get("https://api.github.com/repos/seyallius/govmr/releases/latest")
            .header("User-Agent", "govmr")
            .send()
            .await?;

        let status = res.status();
        if status.as_u16() == 404 {
            logging::debug("update check: complete status=404 note=no_public_releases");
            return Ok(None);
        }

        let json: serde_json::Value = res
            .json()
            .await
            .map_err(|e| GovmError::Extraction(e.to_string()))?;

        let tag = json["tag_name"]
            .as_str()
            .unwrap_or("")
            .trim_start_matches('v');

        logging::debug(&format!(
            "update check: complete status={} tag={}",
            status,
            if tag.is_empty() { "none" } else { tag }
        ));

        let current = config::current_govmr_version();
        if !tag.is_empty() && tag != current {
            Ok(Some(tag.to_string()))
        } else {
            logging::debug(&format!(
                "update check: complete status=latest current={current}"
            ));
            Ok(None)
        }
    }

    /// Downloads the latest release archive, extracts the binary, and replaces the current executable.
    ///
    /// # Errors
    /// Returns [`GovmError`] if any download, archive-extraction, or file-replacement step fails.
    pub(crate) async fn perform_update<F>(
        &self,
        version: &str,
        progress: F,
    ) -> Result<(), GovmError>
    where
        F: Fn(InstallProgress) + Send + 'static,
    {
        let os = match OS {
            "macos" => "apple-darwin",
            "linux" => "unknown-linux-gnu",
            "windows" => "pc-windows-msvc",
            other => other,
        };
        let arch = ARCH;
        let target = format!("{arch}-{os}");
        let ext = if cfg!(windows) { "zip" } else { "tar.gz" };
        let url = format!(
            "https://github.com/seyallius/govmr/releases/download/v{version}/govmr-v{version}-{target}.{ext}"
        );

        let current = config::current_govmr_version();
        logging::info(&format!(
            "update: downloading current={current} target={version} url={url}"
        ));
        let started_at = Instant::now();

        // 1. Download with progress
        let bytes_buf = self.stream_update_archive(&url, &progress).await?;
        logging::debug(&format!(
            "update: archive fetched target={version} size={} ({} bytes) elapsed_time={}s",
            GoVersion::format_size(bytes_buf.len() as u64),
            bytes_buf.len(),
            started_at.elapsed().as_secs()
        ));

        // 2. Save to temp file
        let temp_dir = env::temp_dir().join("govmr_update");
        let _ = fs::create_dir_all(&temp_dir);
        let archive_path = temp_dir.join(format!("govmr.{ext}"));
        fs::write(&archive_path, &bytes_buf)?;

        // 3. Extract
        let bin_name = if cfg!(windows) { "govmr.exe" } else { "govmr" };
        let new_bin_path = temp_dir.join(bin_name);

        logging::info(&format!(
            "update: extracting target={version} archive=\"{}\"",
            archive_path.display()
        ));

        if !Self::extract_update_binary(&archive_path, &new_bin_path, bin_name)? {
            return Err(GovmError::Extraction(format!(
                "binary '{bin_name}' not found in the downloaded archive. Check the release asset contents in ~/.govmr/govmr.log"
            )));
        }

        logging::info(&format!(
            "update: extracted target={version} bin=\"{}\"",
            new_bin_path.display()
        ));

        // 4. Replace using self-replace (handles ETXTBSY and Windows locks natively)
        logging::info(&format!("update: replacing binary target={version}"));

        self_replace::self_replace(&new_bin_path).map_err(|e| {
            logging::error(&format!("update: replace failed error=\"{e}\""));
            GovmError::Extraction(format!("Failed to replace binary: {e}"))
        })?;

        logging::info(&format!(
            "update: complete from={current} to={version} elapsed_time={}s",
            started_at.elapsed().as_secs()
        ));

        // Cleanup temp dir
        let _ = fs::remove_dir_all(&temp_dir);

        Ok(())
    }

    /// Removes the govmr binary and optionally purges the ~/.govmr directory.
    ///
    /// The binary is removed FIRST. If this step fails, the function aborts
    /// immediately without touching completions or `~/.govmr`, preventing a
    /// half-uninstalled state where the binary remains but its support files are gone.
    ///
    /// # Errors
    /// Returns [`GovmError`] if the home directory cannot be found or any
    /// file-removal step fails.
    #[allow(clippy::unused_self)]
    pub(crate) fn uninstall(&self, purge: bool) -> Result<(), GovmError> {
        // 1. Schedule the binary for deletion.
        // `self_replace` handles the cross-platform nightmares for us:
        // - Unix: unlinks the inode (the running process keeps executing from memory).
        // - Windows: spawns a tiny background process that waits for our PID to
        //   exit before deleting the locked `.exe` file.
        self_replace::self_delete().map_err(GovmError::Io)?;
        logging::info("uninstall: binary deletion scheduled via self_replace");

        // 2. Binary is safely handled. Now clean up shell completions.
        completions::remove_completions();

        // 2. Binary is gone (or scheduled to be). Now clean up completions.
        completions::remove_completions();

        // 3. Finally, purge ~/.govmr if requested.
        if purge {
            let home = dirs::home_dir().ok_or(GovmError::HomeNotFound)?;
            let base_dir = home.join(".govmr");
            if base_dir.exists() {
                fs::remove_dir_all(&base_dir)?;
                logging::info(&format!(
                    "uninstall: purged path=\"{}\"",
                    base_dir.display()
                ));
            }
        }

        Ok(())
    }

    // -------------------------------------- Internal Helpers -------------------------------------- //

    /// Streams the update archive into `bytes_buf`, emitting smoothed progress
    /// events and returning the number of bytes fetched.
    async fn stream_update_archive<F>(&self, url: &str, progress: &F) -> Result<Vec<u8>, GovmError>
    where
        F: Fn(InstallProgress),
    {
        let res = self.client.get(url).send().await?;
        let status = res.status();
        if !status.is_success() {
            return Err(GovmError::HttpStatus {
                status: status.as_u16(),
                url: res.url().to_string(),
            });
        }

        let total_size = res.content_length().unwrap_or(0);
        let mut downloaded: u64 = 0;
        let mut stream = res.bytes_stream();

        let mut last_report = Instant::now();
        let mut last_bytes: u64 = 0;
        let mut smoothed_speed: f64 = 0.0;
        let mut bytes_buf = Vec::new();

        while let Some(chunk) = stream.next().await {
            let chunk = chunk?;
            bytes_buf.extend_from_slice(&chunk);
            downloaded += chunk.len() as u64;

            let now = Instant::now();
            let elapsed = now.duration_since(last_report).as_secs_f64();
            if elapsed >= 0.25 || total_size == 0 {
                #[allow(clippy::cast_precision_loss)]
                let instant_speed = (downloaded - last_bytes) as f64 / elapsed.max(1e-3);
                smoothed_speed = if smoothed_speed == 0.0 {
                    instant_speed
                } else {
                    smoothed_speed * 0.6 + instant_speed * 0.4
                };

                progress(InstallProgress::Downloading {
                    downloaded,
                    total: total_size,
                    bytes_per_sec: smoothed_speed,
                });
                last_report = now;
                last_bytes = downloaded;
            }
        }

        progress(InstallProgress::Downloading {
            downloaded,
            total: total_size,
            bytes_per_sec: smoothed_speed,
        });
        progress(InstallProgress::Extracting);

        Ok(bytes_buf)
    }

    /// Extracts the `govmr` binary from a downloaded update archive into
    /// `new_bin_path`, returning `true` when the binary was found and unpacked.
    fn extract_update_binary(
        archive_path: &Path,
        new_bin_path: &Path,
        bin_name: &str,
    ) -> Result<bool, GovmError> {
        let mut found = false;

        if cfg!(windows) {
            let mut archive = zip::ZipArchive::new(File::open(archive_path)?)
                .map_err(|e| GovmError::Extraction(e.to_string()))?;
            for i in 0..archive.len() {
                let mut file = archive
                    .by_index(i)
                    .map_err(|e| GovmError::Extraction(e.to_string()))?;
                logging::debug(&format!("update: inspecting zip entry=\"{}\"", file.name()));
                if file.name().ends_with(bin_name) || file.name() == bin_name {
                    let mut out = File::create(new_bin_path)?;
                    std::io::copy(&mut file, &mut out)?;
                    found = true;
                    break;
                }
            }
        } else {
            let tar_gz = File::open(archive_path)?;
            let tar = flate2::read::GzDecoder::new(tar_gz);
            let mut archive = tar::Archive::new(tar);
            for entry in archive.entries()? {
                let mut entry = entry?;
                let path = entry.path()?;
                logging::debug(&format!(
                    "update: inspecting tar entry=\"{}\"",
                    path.display()
                ));

                let name_matches = path.file_name().is_some_and(|n| n == bin_name);
                let path_matches = path.to_string_lossy().ends_with(&format!("/{bin_name}"))
                    || path.to_string_lossy() == bin_name;

                if (name_matches || path_matches) && !entry.header().entry_type().is_dir() {
                    entry.unpack(new_bin_path)?;
                    found = true;
                    break;
                }
            }
        }

        Ok(found)
    }
}

// -------------------------------------- Internal Helpers -------------------------------------- //

/// Recursively sums the size of a directory tree, for "how much space did this
/// free?" reporting.
///
/// Best-effort by design: unreadable or vanished entries count as zero rather
/// than failing the operation that merely wanted a number for the log. Symlinks
/// are measured, not followed, so a link cannot be double-counted or loop.
fn dir_size(path: &Path) -> u64 {
    let Ok(entries) = fs::read_dir(path) else {
        return 0;
    };
    entries
        .flatten()
        .map(|entry| {
            let child = entry.path();
            match entry.file_type() {
                Ok(ft) if ft.is_dir() => dir_size(&child),
                _ => fs::symlink_metadata(&child).map_or(0, |meta| meta.len()),
            }
        })
        .sum()
}