topgrade 17.4.0

Upgrade all the things
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
use color_eyre::eyre::Context;
use color_eyre::eyre::Result;
use color_eyre::eyre::{OptionExt, bail, eyre};
use etcetera::BaseStrategy;
use ini::Ini;
use regex::Regex;
use rust_i18n::t;
use semver::Version;
use std::env::home_dir;
use std::ffi::OsStr;
use std::io::Write;
use std::os::unix::fs::MetadataExt;
use std::path::Component;
use std::path::PathBuf;
use std::sync::LazyLock;
use std::{env::var, path::Path};
use std::{fs, io};
use tracing::{debug, warn};

use crate::XDG_DIRS;
use crate::command::CommandExt;
use crate::config::NixHandler;
use crate::sudo::SudoExecuteOpts;
use crate::utils::require_one;
use crate::{HOME_DIR, output_changed_message};

#[cfg(target_os = "linux")]
use super::linux::Distribution;
use crate::error::{SkipStep, StepFailed};
use crate::execution_context::ExecutionContext;
#[cfg(any(target_os = "linux", target_os = "macos"))]
use crate::executor::Executor;
use crate::step::Step;
use crate::terminal::print_separator;
use crate::utils::{PathExt, require};

#[cfg(target_os = "linux")]
fn brew_linux_sudo_uid() -> Option<u32> {
    let linuxbrew_directory = "/home/linuxbrew/.linuxbrew";
    if let Ok(metadata) = fs::metadata(linuxbrew_directory) {
        let owner_id = metadata.uid();
        let current_id = nix::unistd::Uid::effective();
        // print debug these two values
        debug!("linuxbrew_directory owner_id: {owner_id}, current_id: {current_id}");
        return if owner_id == current_id.as_raw() {
            None // no need for sudo if linuxbrew is owned by the current user
        } else {
            Some(owner_id) // otherwise use sudo to run brew as the owner
        };
    }
    None
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn brew_get_sudo() -> Option<String> {
    #[cfg(target_os = "linux")]
    {
        let sudo_uid = brew_linux_sudo_uid();
        // if brew is owned by another user, execute "sudo -Hu <uid> brew update"
        if let Some(user_id) = sudo_uid {
            let uid = nix::unistd::Uid::from_raw(user_id);
            let user = nix::unistd::User::from_uid(uid)
                .expect("failed to call getpwuid()")
                .expect("this user should exist");

            return Some(user.name);
        }
    }
    None
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
const INTEL_BREW: &str = "/usr/local/bin/brew";

#[cfg(any(target_os = "linux", target_os = "macos"))]
const ARM_BREW: &str = "/opt/homebrew/bin/brew";

#[derive(Clone, Debug)]
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub struct Brew {
    variant: BrewVariant,
    path: PathBuf,
    sudo: Option<String>,
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
impl Brew {
    fn new(variant: BrewVariant) -> Result<Self> {
        Ok(Self {
            variant,
            path: require(variant.binary_name())?,
            sudo: brew_get_sudo(),
        })
    }

    // TODO: this is suboptimal, hopefully simplify with v17 refactor
    //  + `impl Clone for Executor`
    /// Execute a brew command. Uses `arch` to run using the correct
    /// architecture on macOS if needed, and `sudo -Hu` to run as the
    /// correct user on Linux if needed.
    fn execute(&self, ctx: &ExecutionContext) -> Result<Executor> {
        let mut args = vec![];
        match self.variant {
            BrewVariant::MacIntel if cfg!(target_arch = "aarch64") => {
                args.extend(["arch", "-x86_64"]);
            }
            BrewVariant::MacArm if cfg!(target_arch = "x86_64") => {
                args.extend(["arch", "-arm64e"]);
            }
            _ => {}
        }
        args.push(
            self.path
                .to_str()
                .ok_or_eyre("brew path contains non-unicode characters")?,
        );
        let mut it = args.into_iter();

        // SAFETY: guaranteed to contain at least one element, the path
        let program = it.next().unwrap();
        let mut cmd = match &self.sudo {
            None => ctx.execute(program),
            Some(user) => {
                let sudo = ctx.require_sudo()?;
                sudo.execute_opts(ctx, program, SudoExecuteOpts::new().set_home().user(user))?
            }
        };
        cmd.args(it);
        Ok(cmd)
    }

    fn step_title(&self) -> String {
        let both_exists = BrewVariant::both_both_exist();
        let step_title = match self.variant {
            BrewVariant::MacArm if both_exists => "Brew (ARM)",
            BrewVariant::MacIntel if both_exists => "Brew (Intel)",
            _ => "Brew",
        };

        match &self.sudo {
            Some(user) => {
                format!("{} ({})", step_title, t!("sudo as user '{user}'", user = user))
            }
            None => step_title.to_string(),
        }
    }

    #[cfg(target_os = "macos")]
    fn is_macos_custom(&self) -> bool {
        let path = self.path.as_os_str();
        !(path == INTEL_BREW || path == ARM_BREW)
    }
}

#[derive(Copy, Clone, Debug)]
#[allow(dead_code)]
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub enum BrewVariant {
    Path,
    MacIntel,
    MacArm,
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
impl BrewVariant {
    fn binary_name(self) -> &'static str {
        match self {
            BrewVariant::Path => "brew",
            BrewVariant::MacIntel => INTEL_BREW,
            BrewVariant::MacArm => ARM_BREW,
        }
    }

    #[cfg(target_os = "macos")]
    fn is_path(&self) -> bool {
        matches!(self, BrewVariant::Path)
    }

    fn both_both_exist() -> bool {
        Path::new(INTEL_BREW).exists() && Path::new(ARM_BREW).exists()
    }
}

pub fn run_fisher(ctx: &ExecutionContext) -> Result<()> {
    let fish = require("fish")?;

    ctx.execute(&fish)
        .always()
        .args(["-c", "type -t fisher"])
        .output_checked_utf8()
        .map(|_| ())
        .map_err(|_| SkipStep(t!("`fisher` is not defined in `fish`").to_string()))?;

    ctx.execute(&fish)
        .always()
        .args(["-c", "echo \"$__fish_config_dir/fish_plugins\""])
        .output_checked_utf8()
        .and_then(|output| Path::new(&output.stdout.trim()).require().map(|_| ()))
        .map_err(|err| SkipStep(t!("`fish_plugins` path doesn't exist: {err}", err = err).to_string()))?;

    ctx.execute(&fish)
        .always()
        .args(["-c", "fish_update_completions"])
        .output_checked_utf8()
        .map(|_| ())
        .map_err(|_| SkipStep(t!("`fish_update_completions` is not available").to_string()))?;

    print_separator("Fisher");

    let version_str = ctx
        .execute(&fish)
        .always()
        .args(["-c", "fisher --version"])
        .output_checked_utf8()?
        .stdout;
    debug!("Fisher version: {}", version_str);

    if version_str.starts_with("fisher version 3.") {
        // v3 - see https://github.com/topgrade-rs/topgrade/pull/37#issuecomment-1283844506
        ctx.execute(&fish).args(["-c", "fisher"]).status_checked()
    } else {
        // v4
        ctx.execute(&fish).args(["-c", "fisher update"]).status_checked()
    }
}

pub fn run_bashit(ctx: &ExecutionContext) -> Result<()> {
    HOME_DIR.join(".bash_it").require()?;

    print_separator("Bash-it");

    ctx.execute("bash")
        .args(["-lic", &format!("bash-it update {}", ctx.config().bashit_branch())])
        .status_checked()
}

pub fn run_oh_my_bash(ctx: &ExecutionContext) -> Result<()> {
    require("bash")?;
    let oh_my_bash = var("OSH")
        // default to `~/.oh-my-bash`
        .unwrap_or(
            HOME_DIR
                .join(".oh-my-bash")
                .to_str()
                .expect("should be UTF-8 encoded")
                .to_string(),
        )
        .require()?;

    print_separator("oh-my-bash");

    let mut update_script = oh_my_bash;
    update_script.push_str("/tools/upgrade.sh");

    ctx.execute("bash").arg(update_script).status_checked()
}

pub fn run_oh_my_fish(ctx: &ExecutionContext) -> Result<()> {
    let fish = require("fish")?;
    HOME_DIR.join(".local/share/omf/pkg/omf/functions/omf.fish").require()?;

    print_separator("oh-my-fish");

    ctx.execute(fish).args(["-c", "omf update"]).status_checked()
}

pub fn run_pkgin(ctx: &ExecutionContext) -> Result<()> {
    let pkgin = require("pkgin")?;

    print_separator("Pkgin");

    let sudo = ctx.require_sudo()?;

    let mut command = sudo.execute(ctx, &pkgin)?;
    command.arg("update");
    if ctx.config().yes(Step::Pkgin) {
        command.arg("-y");
    }
    command.status_checked()?;

    let mut command = sudo.execute(ctx, &pkgin)?;
    command.arg("upgrade");
    if ctx.config().yes(Step::Pkgin) {
        command.arg("-y");
    }
    command.status_checked()
}

pub fn run_fish_plug(ctx: &ExecutionContext) -> Result<()> {
    let fish = require("fish")?;
    HOME_DIR
        .join(".local/share/fish/plug/kidonng/fish-plug/functions/plug.fish")
        .require()?;

    print_separator("fish-plug");

    ctx.execute(fish).args(["-c", "plug update"]).status_checked()
}

/// Upgrades `fundle` and `fundle` plugins.
///
/// `fundle` is a package manager for the Fish shell.
///
/// See: <https://github.com/danhper/fundle>
pub fn run_fundle(ctx: &ExecutionContext) -> Result<()> {
    let fish = require("fish")?;
    HOME_DIR.join(".config/fish/fundle").require()?;

    print_separator("fundle");

    ctx.execute(fish)
        .args(["-c", "fundle self-update && fundle update"])
        .status_checked()
}

#[cfg(not(any(target_os = "android", target_os = "macos")))]
pub fn upgrade_gnome_extensions(ctx: &ExecutionContext) -> Result<()> {
    let gdbus = require("gdbus")?;
    crate::utils::require_option(
        var("XDG_CURRENT_DESKTOP").ok().filter(|p| p.contains("GNOME")),
        t!("Desktop does not appear to be GNOME").to_string(),
    )?;
    let output = ctx
        .execute("gdbus")
        .always()
        .args([
            "call",
            "--session",
            "--dest",
            "org.freedesktop.DBus",
            "--object-path",
            "/org/freedesktop/DBus",
            "--method",
            "org.freedesktop.DBus.ListActivatableNames",
        ])
        .output_checked_utf8()?;

    debug!("Checking for GNOME extensions: {}", output);
    if !output.stdout.contains("org.gnome.Shell.Extensions") {
        return Err(SkipStep(t!("GNOME shell extensions are unregistered in DBus").to_string()).into());
    }

    print_separator(t!("GNOME Shell extensions"));

    ctx.execute(gdbus)
        .args([
            "call",
            "--session",
            "--dest",
            "org.gnome.Shell.Extensions",
            "--object-path",
            "/org/gnome/Shell/Extensions",
            "--method",
            "org.gnome.Shell.Extensions.CheckForUpdates",
        ])
        .status_checked()
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn run_brew_formula(ctx: &ExecutionContext, variant: BrewVariant) -> Result<()> {
    let brew = Brew::new(variant)?;

    #[cfg(target_os = "macos")]
    {
        if variant.is_path() && !brew.is_macos_custom() {
            return Err(SkipStep(t!("Not a custom brew for macOS").to_string()).into());
        }
    }

    print_separator(brew.step_title());

    brew.execute(ctx)?.arg("update").status_checked()?;
    // TODO: this had:
    //  `.current_dir("/tmp") // brew needs a writable current directory`
    //  but that only applied when sudo -Hu was used. Is it really needed?

    let mut command = brew.execute(ctx)?;
    command.args(["upgrade", "--formula"]);

    if ctx.config().brew_fetch_head() {
        command.arg("--fetch-HEAD");
    }

    command.status_checked()?;

    if ctx.config().cleanup() {
        brew.execute(ctx)?.arg("cleanup").status_checked()?;
    }

    if ctx.config().brew_autoremove() {
        brew.execute(ctx)?.arg("autoremove").status_checked()?;
    }

    Ok(())
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn run_brew_cask(ctx: &ExecutionContext, variant: BrewVariant) -> Result<()> {
    let brew = Brew::new(variant)?;

    #[cfg(target_os = "macos")]
    if variant.is_path() && !brew.is_macos_custom() {
        return Err(SkipStep(t!("Not a custom brew for macOS").to_string()).into());
    }

    #[cfg(target_os = "linux")]
    {
        // Homebrew cask support was added in version 4.5.0
        let version_output = brew.execute(ctx)?.always().arg("--version").output_checked_utf8()?;

        let version_line = version_output
            .stdout
            .lines()
            .next()
            .ok_or_else(|| eyre!(output_changed_message!("brew --version", "no output lines")))?;

        let version_str = version_line.split_whitespace().nth(1).ok_or_else(|| {
            eyre!(output_changed_message!(
                "brew --version",
                "Expected version after 'Homebrew'"
            ))
        })?;

        let version = Version::parse(version_str)
            .wrap_err_with(|| output_changed_message!("brew --version", "Invalid version"))?;

        if version < Version::new(4, 5, 0) {
            return Err(SkipStep(
                t!(
                    "Homebrew cask support on Linux requires Homebrew 4.5.0 or later (found {version})",
                    version = version
                )
                .to_string(),
            )
            .into());
        }
    }

    print_separator(format!("{} - Cask", brew.step_title()));

    let cask_upgrade_exists = brew
        .execute(ctx)?
        .always()
        .args(["--repository", "buo/cask-upgrade"])
        .output_checked_utf8()
        .map(|p| Path::new(p.stdout.trim()).exists())?;

    let mut brew_args = vec![];

    if cask_upgrade_exists {
        brew_args.extend(["cu", "-y"]);
        if ctx.config().brew_cask_greedy() {
            brew_args.push("-a");
        }
    } else {
        brew_args.extend(["upgrade", "--cask"]);
        if ctx.config().brew_cask_greedy() {
            brew_args.push("--greedy");
        }
        if ctx.config().brew_greedy_latest() {
            brew_args.push("--greedy-latest");
        }
        if ctx.config().brew_greedy_auto_updates() {
            brew_args.push("--greedy-auto-updates");
        }
    }

    brew.execute(ctx)?.args(&brew_args).status_checked()?;

    if ctx.config().cleanup() {
        brew.execute(ctx)?.arg("cleanup").status_checked()?;
    }

    Ok(())
}

pub fn run_guix(ctx: &ExecutionContext) -> Result<()> {
    let guix = require("guix")?;

    print_separator("Guix");

    ctx.execute(&guix).arg("pull").status_checked()?;
    ctx.execute(&guix).args(["package", "-u"]).status_checked()?;

    Ok(())
}

struct NixVersion {
    version_string: String,
}

impl NixVersion {
    fn new(ctx: &ExecutionContext, nix: &Path) -> Result<Self> {
        let version_output = ctx.execute(nix).always().arg("--version").output_checked_utf8()?;

        debug!(
            output=%version_output,
            "`nix --version` output"
        );

        let version_string = version_output
            .stdout
            .lines()
            .next()
            .ok_or_else(|| eyre!("`nix --version` output is empty"))?
            .to_string();

        if version_string.is_empty() {
            bail!("`nix --version` output was empty");
        }

        Ok(Self { version_string })
    }

    fn version(&self) -> Result<Version> {
        static NIX_VERSION_REGEX: LazyLock<Regex> =
            LazyLock::new(|| Regex::new(r"^nix \([^)]*\) ([0-9.]+)").expect("Nix version regex always compiles"));

        let captures = NIX_VERSION_REGEX
            .captures(&self.version_string)
            .ok_or_else(|| eyre!(output_changed_message!("nix --version", "regex did not match")))?;
        let raw_version = &captures[1];

        debug!("Raw Nix version: {raw_version}");

        // Nix 2.29.0 outputs "2.29" instead of "2.29.0", so we need to add that if necessary.
        let corrected_raw_version = if raw_version.chars().filter(|&c| c == '.').count() == 1 {
            &format!("{raw_version}.0")
        } else {
            raw_version
        };

        debug!("Corrected raw Nix version: {corrected_raw_version}");

        let version = Version::parse(corrected_raw_version)
            .wrap_err_with(|| output_changed_message!("nix --version", "Invalid version"))?;

        debug!("Nix version: {:?}", version);

        Ok(version)
    }

    fn is_lix(&self) -> bool {
        let is_lix = self.version_string.contains("Lix");
        debug!(?is_lix);
        is_lix
    }

    fn is_determinate_nix(&self) -> bool {
        let is_determinate_nix = self.version_string.contains("Determinate Nix");
        debug!(?is_determinate_nix);
        is_determinate_nix
    }
}

pub fn run_nix(ctx: &ExecutionContext) -> Result<()> {
    let nix = require("nix")?;
    // TODO: Is None possible here? Should we use HOME_DIR instead?
    let profile_path = match home_dir() {
        Some(home) => XDG_DIRS
            .state_dir()
            .map(|d| d.join("nix/profile"))
            .filter(|p| p.exists())
            .unwrap_or(Path::new(&home).join(".nix-profile")),
        None => Path::new("/nix/var/nix/profiles/per-user/default").into(),
    };
    debug!("nix profile: {:?}", profile_path);
    let manifest_json_path = profile_path.join("manifest.json");

    #[cfg(target_os = "macos")]
    {
        if require("darwin-rebuild").is_ok() {
            return Err(
                SkipStep(t!("Nix-darwin on macOS must be upgraded via darwin-rebuild switch").to_string()).into(),
            );
        }
    }

    let nix_version = NixVersion::new(ctx, &nix)?;

    // Nix since 2.21.0 uses `--all --impure` rather than `.*` to upgrade all packages.
    // Lix is based on Nix 2.18, so it doesn't!
    let packages = if nix_version.version()? >= Version::new(2, 21, 0) && !nix_version.is_lix() {
        vec!["--all", "--impure"]
    } else {
        vec![".*"]
    };

    // nix-channel might not be available and isn't always necessary to perform profile updates
    let nix_channel_result = if let Ok(nix_channel) = require("nix-channel") {
        print_separator("Nix Channels");
        ctx.execute(nix_channel).arg("--update").status_checked()
    } else {
        Ok(())
    };

    if Path::new(&manifest_json_path).exists() {
        // nix-channel doesn't have to succeed when upgrading nix profiles, just warn about it
        if let Err(e) = nix_channel_result {
            warn!("`nix-channel --update` failed: {e}");
        }
        print_separator("Nix Profiles");
        ctx.execute(nix)
            .args(nix_args())
            .arg("profile")
            .arg("upgrade")
            .args(&packages)
            .arg("--verbose")
            .status_checked()
    } else {
        // a successful nix-channel run is expected to perform nix-env upgrades
        nix_channel_result?;
        let nix_env = require("nix-env")?;
        print_separator("Nix");

        let mut command = ctx.execute(nix_env);
        command.arg("--upgrade");
        if let Some(args) = ctx.config().nix_env_arguments() {
            command.args(args.split_whitespace());
        };
        command.status_checked()
    }
}

pub fn run_nix_self_upgrade(ctx: &ExecutionContext) -> Result<()> {
    let nix = require("nix")?;

    // Should we attempt to upgrade Nix with `nix upgrade-nix`?
    #[allow(unused_mut)]
    let mut should_self_upgrade = cfg!(target_os = "macos");

    #[cfg(target_os = "linux")]
    {
        // We can't use `nix upgrade-nix` on NixOS.
        if let Ok(Distribution::NixOS) = Distribution::detect() {
            should_self_upgrade = false;
        }
    }

    if !should_self_upgrade {
        return Err(SkipStep(t!("`nix upgrade-nix` can only be used on macOS or non-NixOS Linux").to_string()).into());
    }

    if nix_profile_dir(&nix)?.is_none() {
        return Err(
            SkipStep(t!("`nix upgrade-nix` cannot be run when Nix is installed in a profile").to_string()).into(),
        );
    }

    print_separator(t!("Nix (self-upgrade)"));

    let nix_version = NixVersion::new(ctx, &nix)?;

    if nix_version.is_determinate_nix() {
        let nixd = require("determinate-nixd");
        let nixd = match nixd {
            Err(_) => {
                println!("Found Determinate Nix, but could not find determinate-nixd");
                return Err(StepFailed.into());
            }
            Ok(nixd) => nixd,
        };

        let sudo = ctx.require_sudo()?;
        return sudo
            .execute_opts(ctx, nixd, SudoExecuteOpts::new().login_shell())?
            .arg("upgrade")
            .status_checked();
    }

    let multi_user = fs::metadata(&nix)?.uid() == 0;
    debug!("Multi user nix: {}", multi_user);

    let nix_args = nix_args();
    if multi_user {
        let sudo = ctx.require_sudo()?;
        sudo.execute_opts(ctx, &nix, SudoExecuteOpts::new().login_shell())?
            .args(nix_args)
            .arg("upgrade-nix")
            .status_checked()
    } else {
        ctx.execute(&nix).args(nix_args).arg("upgrade-nix").status_checked()
    }
}

/// If we try to `nix upgrade-nix` but Nix is installed with `nix profile`, we'll get a `does not
/// appear to be part of a Nix profile` error.
///
/// We duplicate some of the `nix` logic here to avoid this.
/// See: <https://github.com/NixOS/nix/blob/f0180487a0e4c0091b46cb1469c44144f5400240/src/nix/upgrade-nix.cc#L102-L139>
///
/// See: <https://github.com/NixOS/nix/issues/5473>
fn nix_profile_dir(nix: &Path) -> Result<Option<PathBuf>> {
    // NOTE: `nix` uses the location of the `nix-env` binary for this but we're using the `nix`
    // binary; should be the same.
    let nix_bin_dir = nix.parent();
    if nix_bin_dir.and_then(|p| p.file_name()) != Some(OsStr::new("bin")) {
        debug!("Nix is not installed in a `bin` directory: {nix_bin_dir:?}");
        return Ok(None);
    }

    let nix_dir = nix_bin_dir
        .and_then(|bin_dir| bin_dir.parent())
        .ok_or_else(|| eyre!("Unable to find Nix install directory from Nix binary {nix:?}"))?;

    debug!("Found Nix in {nix_dir:?}");

    let mut profile_dir = nix_dir.to_path_buf();
    while profile_dir.is_symlink() {
        profile_dir = profile_dir
            .parent()
            .ok_or_else(|| eyre!("Path has no parent: {profile_dir:?}"))?
            .join(
                profile_dir
                    .read_link()
                    .wrap_err_with(|| format!("Failed to read symlink {profile_dir:?}"))?,
            );

        // NOTE: `nix` uses a hand-rolled canonicalize function, Rust just uses `realpath`.
        if profile_dir
            .canonicalize()
            .wrap_err_with(|| format!("Failed to canonicalize {profile_dir:?}"))?
            .components()
            .any(|component| component == Component::Normal(OsStr::new("profiles")))
        {
            break;
        }
    }

    debug!("Found Nix profile {profile_dir:?}");
    let user_env = profile_dir
        .canonicalize()
        .wrap_err_with(|| format!("Failed to canonicalize {profile_dir:?}"))?;

    Ok(
        if user_env
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.ends_with("user-environment"))
        {
            Some(profile_dir)
        } else {
            None
        },
    )
}

/// Returns a directory from an environment variable, if and only if it is a directory which
/// contains a flake.nix
pub(super) fn flake_dir(var: &'static str) -> Option<PathBuf> {
    std::env::var_os(var)
        .map(PathBuf::from)
        .take_if(|x| std::fs::exists(x.join("flake.nix")).is_ok_and(|x| x))
}

pub(super) struct NhSwitchArgs<'a> {
    pub step: &'a str,
    pub installable_type: &'a str,
    pub specific_var: &'a str,
    pub print_separator: bool,
}

pub(super) fn can_nh_switch(args: &NhSwitchArgs<'static>) -> Result<PathBuf> {
    let nix_helper = require("nh");

    if nix_helper.is_err() {
        return Err(SkipStep(
            t!(
                "linux.nix_handler = \"{value}\", but {resulting_tool} is not available",
                value = "nh",
                resulting_tool = "nh"
            )
            .into(),
        )
        .into());
    };

    if flake_dir("NH_FLAKE").is_none() && flake_dir(args.specific_var).is_none() {
        return Err(SkipStep(
            t!(
                "{step}: linux.nix_handler = \"nh\", but neither $NH_FLAKE nor ${specific_var} were set",
                step = args.step,
                specific_var = args.specific_var
            )
            .into(),
        )
        .into());
    }

    nix_helper
}

pub(super) fn nh_switch(ctx: &ExecutionContext, nh: &PathBuf, args: &NhSwitchArgs<'static>) -> Result<()> {
    if args.print_separator {
        print_separator(format!("nh {}", args.installable_type));
    }

    let mut cmd = ctx.execute(nh);
    cmd.arg(args.installable_type);
    cmd.arg("switch");
    cmd.arg("-u");

    if !ctx.config().yes(Step::System) {
        cmd.arg("--ask");
    }
    cmd.status_checked()?;
    Ok(())
}

fn nix_args() -> [&'static str; 2] {
    ["--extra-experimental-features", "nix-command"]
}

pub fn run_yadm(ctx: &ExecutionContext) -> Result<()> {
    let yadm = require("yadm")?;

    print_separator("yadm");

    ctx.execute(yadm).arg("pull").status_checked()
}

pub fn run_asdf(ctx: &ExecutionContext) -> Result<()> {
    let asdf = require("asdf")?;

    print_separator("asdf");

    // asdf (>= 0.15.0) won't support the self-update command
    //
    // https://github.com/topgrade-rs/topgrade/issues/1007
    let version_output = ctx.execute(&asdf).always().arg("version").output_checked_utf8()?;
    // Example output
    //
    // ```
    // $ asdf version
    // v0.15.0-31e8c93
    //
    // ```
    // ```
    // $ asdf version
    // v0.16.7
    // ```
    // ```
    // $ asdf version
    // 0.18.0 (revision unknown)
    // ```
    let version_stdout = version_output.stdout.trim();
    // trim the starting 'v'
    let mut remaining = version_stdout.trim_start_matches('v');
    // remove the hash or revision part if present
    if let Some(idx) = remaining.find(['-', ' ']) {
        remaining = &remaining[..idx];
    }
    let version =
        Version::parse(remaining).wrap_err_with(|| output_changed_message!("asdf version", "invalid version"))?;
    if version < Version::new(0, 15, 0) {
        ctx.execute(&asdf).arg("update").status_checked_with_codes(&[42])?;
    }

    ctx.execute(&asdf).args(["plugin", "update", "--all"]).status_checked()
}

pub fn run_mise(ctx: &ExecutionContext) -> Result<()> {
    let mise = require("mise")?;

    print_separator("mise");

    ctx.execute(&mise).args(["plugins", "update"]).status_checked()?;

    let output = ctx
        .execute(&mise)
        .args(["self-update"])
        .output_checked_with(|_| Ok(()))?;
    let status_code = output
        .status
        .code()
        .ok_or_eyre("Couldn't get status code (terminated by signal)")?;
    let stderr = std::str::from_utf8(&output.stderr).wrap_err("Expected output to be valid UTF-8")?;
    if stderr.contains("cannot update") && status_code == 1 {
        debug!("Mise self-update not available")
    } else {
        // Write the output
        io::stdout().write_all(&output.stdout)?;
        io::stderr().write_all(&output.stderr)?;
        if status_code != 0 {
            return Err(StepFailed.into());
        }
    }

    let mut cmd = ctx.execute(&mise);

    cmd.arg("upgrade");

    if ctx.config().mise_interactive() {
        cmd.arg("--interactive");
    }

    if ctx.config().mise_bump() {
        cmd.arg("--bump");
    }

    if ctx.config().mise_jobs() != 4 {
        cmd.args(["--jobs", &ctx.config().mise_jobs().to_string()]);
    }

    cmd.status_checked()
}

pub fn run_home_manager(ctx: &ExecutionContext) -> Result<()> {
    require_one(["home-manager", "nh"])?;
    let home_manager = require("home-manager");
    let nix_handler = ctx.config().nix_handler();
    let nh_switch_args = NhSwitchArgs {
        step: "home_manager",
        installable_type: "home",
        specific_var: "NH_HOME_FLAKE",
        print_separator: true,
    };
    let can_nh_switch = can_nh_switch(&nh_switch_args);

    match (home_manager, nix_handler, can_nh_switch) {
        // nh is available and we want it
        (_, NixHandler::Autodetect | NixHandler::Nh, Ok(nh)) => nh_switch(ctx, &nh, &nh_switch_args),
        // nh is not available but we need it
        (_, NixHandler::Nh, Err(e)) => Err(e),
        // home-manager is not available but we need it
        (Err(_), NixHandler::Vanilla, _) => Err(SkipStep(
            t!(
                "linux.nix_handler = \"{value}\", but {resulting_tool} is not available",
                value = "vanilla",
                resulting_tool = "home-manager"
            )
            .into(),
        )
        .into()),
        // nh is not available and we don't need it, so we fall back
        (Ok(home_manager), NixHandler::Autodetect, Err(_))
        // We need home-manager
        | (Ok(home_manager), NixHandler::Vanilla, _) => {
            print_separator("home-manager");

            let mut cmd = ctx.execute(home_manager);
            cmd.arg("switch");

            if let Some(extra_args) = ctx.config().home_manager() {
                cmd.args(extra_args);
            }

            cmd.status_checked()
        }
        (Err(_), _, Err(_)) => unreachable!("require_one([\"home-manager\", \"nh\"])?; was called, so either tool must be available"),
    }
}

pub fn run_pearl(ctx: &ExecutionContext) -> Result<()> {
    let pearl = require("pearl")?;
    print_separator("pearl");

    ctx.execute(pearl).arg("update").status_checked()
}

pub fn run_pyenv(ctx: &ExecutionContext) -> Result<()> {
    let pyenv = require("pyenv")?;
    print_separator("pyenv");

    let pyenv_dir = var("PYENV_ROOT").map_or_else(|_| HOME_DIR.join(".pyenv"), PathBuf::from);

    if !pyenv_dir.exists() {
        return Err(SkipStep(t!("Pyenv is installed, but $PYENV_ROOT is not set correctly").to_string()).into());
    }

    if !pyenv_dir.join(".git").exists() {
        return Err(SkipStep(t!("pyenv is not a git repository").to_string()).into());
    }

    if !pyenv_dir.join("plugins").join("pyenv-update").exists() {
        return Err(SkipStep(t!("pyenv-update plugin is not installed").to_string()).into());
    }

    ctx.execute(pyenv).arg("update").status_checked()
}

pub fn run_sdkman(ctx: &ExecutionContext) -> Result<()> {
    let bash = require("bash")?;

    let sdkman_init_path = var("SDKMAN_DIR")
        .map_or_else(|_| HOME_DIR.join(".sdkman"), PathBuf::from)
        .join("bin")
        .join("sdkman-init.sh")
        .require()
        .map(|p| format!("{}", &p.display()))?;

    print_separator("SDKMAN!");

    let sdkman_config_path = var("SDKMAN_DIR")
        .map_or_else(|_| HOME_DIR.join(".sdkman"), PathBuf::from)
        .join("etc")
        .join("config")
        .require()?;

    let sdkman_config = Ini::load_from_file(sdkman_config_path)?;
    let selfupdate_enabled = sdkman_config
        .general_section()
        .get("sdkman_selfupdate_feature")
        .unwrap_or("false");

    if selfupdate_enabled == "true" {
        let cmd_selfupdate = format!("source {} && sdk selfupdate", &sdkman_init_path);
        ctx.execute(&bash)
            .args(["-c", cmd_selfupdate.as_str()])
            .status_checked()?;
    }

    let cmd_update = format!("source {} && sdk update", &sdkman_init_path);
    ctx.execute(&bash).args(["-c", cmd_update.as_str()]).status_checked()?;

    let cmd_upgrade = format!("source {} && sdk upgrade", &sdkman_init_path);
    ctx.execute(&bash).args(["-c", cmd_upgrade.as_str()]).status_checked()?;

    if ctx.config().cleanup() {
        let cmd_flush_archives = format!("source {} && sdk flush archives", &sdkman_init_path);
        ctx.execute(&bash)
            .args(["-c", cmd_flush_archives.as_str()])
            .status_checked()?;

        let cmd_flush_temp = format!("source {} && sdk flush temp", &sdkman_init_path);
        ctx.execute(&bash)
            .args(["-c", cmd_flush_temp.as_str()])
            .status_checked()?;
    }

    Ok(())
}

pub fn run_bun_packages(ctx: &ExecutionContext) -> Result<()> {
    let bun = require("bun")?;

    print_separator(t!("Bun Packages"));

    let mut package_json: PathBuf = var("BUN_INSTALL").map_or_else(|_| HOME_DIR.join(".bun"), PathBuf::from);
    package_json.push("install/global/package.json");

    if !package_json.exists() {
        println!("{}", t!("No global packages installed"));
        return Ok(());
    }

    ctx.execute(bun).args(["-g", "update"]).status_checked()
}

/// Update dotfiles with `rcm(7)`.
///
/// See: <https://github.com/thoughtbot/rcm>
pub fn run_rcm(ctx: &ExecutionContext) -> Result<()> {
    let rcup = require("rcup")?;

    print_separator("rcm");
    ctx.execute(rcup).arg("-v").status_checked()
}

pub fn run_maza(ctx: &ExecutionContext) -> Result<()> {
    let maza = require("maza")?;

    print_separator("maza");
    ctx.execute(maza).arg("update").status_checked()
}

pub fn run_hyprpm(ctx: &ExecutionContext) -> Result<()> {
    let hyprpm = require("hyprpm")?;

    print_separator("hyprpm");

    ctx.execute(hyprpm).arg("update").status_checked()
}

pub fn run_atuin(ctx: &ExecutionContext) -> Result<()> {
    let atuin = require("atuin-update")?;

    print_separator("atuin");

    ctx.execute(atuin).status_checked()
}

pub fn reboot(ctx: &ExecutionContext) -> Result<()> {
    match ctx.sudo() {
        Some(sudo) => sudo.execute(ctx, "reboot")?.status_checked(),
        None => ctx.execute("reboot").status_checked(),
    }
}