jarvy 0.0.3

Jarvy is a fast, cross-platform CLI that installs and manages developer tools across macOS and Linux.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
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
#![allow(dead_code)] // Public API for tool installation utilities

use std::process::{Command, Output};
use std::sync::OnceLock;

use crate::network::config::NetworkConfig;
use crate::network::propagate::apply_network_config;

#[derive(thiserror::Error, Debug)]
pub enum InstallError {
    #[error("unsupported platform")]
    Unsupported,
    #[error("prerequisite missing: {0}")]
    Prereq(&'static str),
    #[error("invalid permissions: {0}")]
    InvalidPermissions(&'static str),
    #[error("command failed: {cmd} (code: {code:?})\n{stderr}")]
    CommandFailed {
        cmd: String,
        code: Option<i32>,
        stderr: String,
    },
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("parse error: {0}")]
    Parse(&'static str),
}

// OS enum for config keys and runtime resolution
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Os {
    Linux,
    Macos,
    Windows,
    Bsd,
}

// Determine the current OS as our enum
pub fn current_os() -> Os {
    #[cfg(target_os = "linux")]
    {
        Os::Linux
    }
    #[cfg(target_os = "macos")]
    {
        Os::Macos
    }
    #[cfg(target_os = "windows")]
    {
        Os::Windows
    }
    #[cfg(target_os = "freebsd")]
    {
        Os::Bsd
    }
}

// Global default for whether to use sudo on POSIX installs. Can be set from Config in main.
// None means: auto-detect per operation (try without sudo, then with if available).
static USE_SUDO_DEFAULT: OnceLock<Option<bool>> = OnceLock::new();

pub fn set_default_use_sudo(val: Option<bool>) {
    let _ = USE_SUDO_DEFAULT.set(val);
}

pub fn default_use_sudo() -> Option<bool> {
    if let Some(v) = USE_SUDO_DEFAULT.get() {
        *v
    } else {
        // Unset -> auto mode
        None
    }
}

/// Spawn a command, capturing its output, and emit a structured warning +
/// telemetry counter on failure. Replaces the duplicated
/// `match Command::new(...).output() { Err(e) => { eprintln!(...); return; } }`
/// pattern that proliferated in setup/provisioner during the panic-removal
/// sweep.
///
/// Returns `None` on spawn failure so callers can keep the
/// `let Some(out) = run_capture(...) else { return; };` shape that mirrors
/// the prior eprintln+return idiom but routes through tracing.
///
/// `stage` should be a bounded label (e.g. `"hard_dep_check"`,
/// `"macos_setup"`) — used as a low-cardinality telemetry attribute.
pub fn run_capture(cmd: &str, args: &[&str], stage: &str, context: &str) -> Option<Output> {
    match Command::new(cmd).args(args).output() {
        Ok(out) => Some(out),
        Err(e) => {
            tracing::warn!(
                event = "setup.subprocess.failed",
                stage = %stage,
                command = %cmd,
                context = %context,
                error = %e,
            );
            eprintln!("{context}: {e}");
            None
        }
    }
}

#[must_use = "this Result may contain an error that should be handled"]
pub fn run(cmd: &str, args: &[&str]) -> Result<Output, InstallError> {
    // Fast, deterministic tests: allow skipping external command execution.
    // Integration tests can opt-in via JARVY_FAST_TEST; unit tests default to skip unless explicitly overridden.
    if std::env::var_os("JARVY_FAST_TEST").is_some() {
        return Err(InstallError::Prereq(
            "skipped external command in fast test mode",
        ));
    }
    #[cfg(test)]
    {
        if std::env::var_os("JARVY_RUN_EXTERNAL_CMDS_IN_TEST").is_none() {
            return Err(InstallError::Prereq(
                "external commands disabled during unit tests",
            ));
        }
    }

    let out = Command::new(cmd).args(args).output().map_err(|e| {
        use std::io::ErrorKind::*;
        match e.kind() {
            NotFound => InstallError::Prereq("required command not found on PATH"),
            PermissionDenied => {
                InstallError::InvalidPermissions("operation requires elevated privileges")
            }
            _ => InstallError::Io(e),
        }
    })?;

    if !out.status.success() {
        // Try to capture stderr for easier diagnostics.
        return Err(InstallError::CommandFailed {
            cmd: cmd.to_string(),
            code: out.status.code(),
            stderr: String::from_utf8_lossy(&out.stderr).into(),
        });
    }
    Ok(out)
}

/// Run a command with network/proxy configuration applied.
///
/// This variant applies HTTP_PROXY, HTTPS_PROXY, NO_PROXY, and CA bundle
/// environment variables to the spawned process based on the NetworkConfig.
#[must_use = "this Result may contain an error that should be handled"]
pub fn run_with_network(
    cmd: &str,
    args: &[&str],
    network: Option<&NetworkConfig>,
    tool_name: &str,
) -> Result<Output, InstallError> {
    // Fast, deterministic tests: allow skipping external command execution.
    if std::env::var_os("JARVY_FAST_TEST").is_some() {
        return Err(InstallError::Prereq(
            "skipped external command in fast test mode",
        ));
    }
    #[cfg(test)]
    {
        if std::env::var_os("JARVY_RUN_EXTERNAL_CMDS_IN_TEST").is_none() {
            return Err(InstallError::Prereq(
                "external commands disabled during unit tests",
            ));
        }
    }

    let mut command = Command::new(cmd);
    command.args(args);

    // Apply network/proxy configuration if provided
    if let Some(net_config) = network {
        apply_network_config(&mut command, net_config, tool_name);
    }

    let out = command.output().map_err(|e| {
        use std::io::ErrorKind::*;
        match e.kind() {
            NotFound => InstallError::Prereq("required command not found on PATH"),
            PermissionDenied => {
                InstallError::InvalidPermissions("operation requires elevated privileges")
            }
            _ => InstallError::Io(e),
        }
    })?;

    if !out.status.success() {
        return Err(InstallError::CommandFailed {
            cmd: cmd.to_string(),
            code: out.status.code(),
            stderr: String::from_utf8_lossy(&out.stderr).into(),
        });
    }
    Ok(out)
}

/// Run a command, prefixing with sudo if configured and applicable (non-Windows)
#[must_use = "this Result may contain an error that should be handled"]
pub fn run_maybe_sudo(use_sudo: bool, cmd: &str, args: &[&str]) -> Result<Output, InstallError> {
    match current_os() {
        Os::Windows => run(cmd, args),
        Os::Linux | Os::Macos | Os::Bsd => {
            if use_sudo {
                // sudo <cmd> <args...>
                let mut all = Vec::with_capacity(1 + args.len());
                all.push(cmd);
                all.extend_from_slice(args);
                run("sudo", &all)
            } else {
                run(cmd, args)
            }
        }
    }
}

/// Run a command with sudo and network/proxy configuration.
///
/// Combines sudo elevation with proxy settings propagation.
#[must_use = "this Result may contain an error that should be handled"]
pub fn run_maybe_sudo_with_network(
    use_sudo: bool,
    cmd: &str,
    args: &[&str],
    network: Option<&NetworkConfig>,
    tool_name: &str,
) -> Result<Output, InstallError> {
    match current_os() {
        Os::Windows => run_with_network(cmd, args, network, tool_name),
        Os::Linux | Os::Macos | Os::Bsd => {
            if use_sudo {
                // sudo -E preserves environment (including proxy vars)
                // sudo <cmd> <args...>
                let mut all = Vec::with_capacity(2 + args.len());
                all.push("-E"); // Preserve environment
                all.push(cmd);
                all.extend_from_slice(args);
                run_with_network("sudo", &all, network, tool_name)
            } else {
                run_with_network(cmd, args, network, tool_name)
            }
        }
    }
}

pub fn has(cmd: &str) -> bool {
    Command::new(cmd)
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

// Require a single command to exist on PATH, otherwise return a Prereq error with remediation.
pub fn require(cmd: &str, remediation: &'static str) -> Result<(), InstallError> {
    if has(cmd) {
        Ok(())
    } else {
        Err(InstallError::Prereq(remediation))
    }
}

// Require one of multiple candidates (e.g., apt or apt-get)
pub fn require_any<'a>(
    candidates: &[&'a str],
    remediation: &'static str,
) -> Result<&'a str, InstallError> {
    for c in candidates {
        if has(c) {
            return Ok(*c);
        }
    }
    Err(InstallError::Prereq(remediation))
}

/// Check if a command's version satisfies the given requirement.
///
/// Uses proper semantic versioning comparison instead of substring matching.
/// Supports requirements like:
/// - `"latest"` or `"*"`: Always passes
/// - `"3.10"`: Matches 3.10.x
/// - `"3.10.0"`: Exact match
/// - `">= 3.10"`: Minimum version
/// - `">= 3.10, < 4.0"`: Range expression
pub fn cmd_satisfies(cmd: &str, requirement: &str) -> bool {
    if let Ok(out) = Command::new(cmd).arg("--version").output() {
        let version_output = String::from_utf8_lossy(&out.stdout);
        return super::version::version_satisfies(&version_output, requirement);
    }
    false
}

pub fn plan_sudo_attempts(use_sudo: Option<bool>, sudo_available: bool) -> Vec<bool> {
    match use_sudo {
        Some(flag) => vec![flag],
        None => {
            if sudo_available {
                vec![false, true]
            } else {
                vec![false]
            }
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PackageManager {
    Apt,
    Dnf,
    Yum,
    Zypper,
    Pacman,
    Apk,
    Brew,
    BrewCask, // Homebrew casks (GUI apps)
    Winget,
    Choco,
    Pkg, // FreeBSD pkg
}

#[cfg(target_os = "linux")]
pub fn detect_linux_pm() -> Option<PackageManager> {
    use std::{fs, process::Command};
    let has = |c| {
        Command::new(c)
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    };

    // (Optional) use /etc/os-release to bias choices when you need vendor repos
    // ID / ID_LIKE fields are the standard signals.  [oai_citation:0‡Freedesktop](https://www.freedesktop.org/software/systemd/man/os-release.html?utm_source=chatgpt.com) [oai_citation:1‡Debian Manpages](https://manpages.debian.org/trixie/systemd/os-release.5.en.html?utm_source=chatgpt.com)
    let _os_release = fs::read_to_string("/etc/os-release").unwrap_or_default();

    if has("apt-get") || has("apt") {
        return Some(PackageManager::Apt);
    }
    if has("dnf") {
        return Some(PackageManager::Dnf);
    }
    if has("yum") {
        return Some(PackageManager::Yum);
    }
    if has("zypper") {
        return Some(PackageManager::Zypper);
    }
    if has("pacman") {
        return Some(PackageManager::Pacman);
    }
    if has("apk") {
        return Some(PackageManager::Apk);
    }
    None
}

#[cfg(target_os = "freebsd")]
pub fn detect_bsd_pm() -> Option<PackageManager> {
    use std::process::Command;
    let has = |c| {
        Command::new(c)
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    };

    if has("pkg") {
        return Some(PackageManager::Pkg);
    }
    None
}

#[cfg(test)]
mod sudo_plan_tests {
    use super::plan_sudo_attempts;

    #[test]
    fn plan_some_true_only_true() {
        let v = plan_sudo_attempts(Some(true), true);
        assert_eq!(v, vec![true]);
    }

    #[test]
    fn plan_some_false_only_false() {
        let v = plan_sudo_attempts(Some(false), true);
        assert_eq!(v, vec![false]);
    }

    #[test]
    fn plan_none_with_sudo_available() {
        let v = plan_sudo_attempts(None, true);
        assert_eq!(v, vec![false, true]);
    }

    #[test]
    fn plan_none_without_sudo_available() {
        let v = plan_sudo_attempts(None, false);
        assert_eq!(v, vec![false]);
    }
}

#[cfg(test)]
mod batch_install_tests {
    use super::*;

    #[test]
    fn empty_list_returns_empty_result() {
        let result = PkgOps::batch_install(PackageManager::Brew, &[], None);
        assert!(result.is_ok());
        let result = result.unwrap();
        assert!(result.succeeded.is_empty());
        assert!(result.failed.is_empty());
    }

    #[test]
    fn batch_install_result_default() {
        let result = BatchInstallResult {
            succeeded: vec!["foo".to_string()],
            failed: vec![("bar".to_string(), "error".to_string())],
        };
        assert_eq!(result.succeeded.len(), 1);
        assert_eq!(result.failed.len(), 1);
        assert_eq!(result.succeeded[0], "foo");
        assert_eq!(result.failed[0].0, "bar");
    }

    #[test]
    fn package_manager_has_required_traits() {
        // Test that PackageManager can be used as HashMap key
        let mut map = std::collections::HashMap::new();
        map.insert(PackageManager::Brew, vec!["jq", "ripgrep"]);
        map.insert(PackageManager::Apt, vec!["git", "curl"]);
        assert_eq!(map.len(), 2);
        assert!(map.contains_key(&PackageManager::Brew));
        assert!(map.contains_key(&PackageManager::Apt));
    }

    #[test]
    fn package_manager_equality() {
        assert_eq!(PackageManager::Brew, PackageManager::Brew);
        assert_ne!(PackageManager::Brew, PackageManager::Apt);
        assert_eq!(PackageManager::BrewCask, PackageManager::BrewCask);
        assert_ne!(PackageManager::Winget, PackageManager::Choco);
    }
}

#[allow(dead_code)]
pub struct PkgOps {
    name: &'static str,
}

/// Result of a batch installation operation.
#[derive(Debug)]
pub struct BatchInstallResult {
    /// Packages that were successfully installed
    pub succeeded: Vec<String>,
    /// Packages that failed to install (package name, error message)
    pub failed: Vec<(String, String)>,
}

impl PkgOps {
    /// Install multiple packages in a single batch operation.
    ///
    /// This is more efficient than installing packages one-by-one because:
    /// - Single dependency resolution pass
    /// - Single lock acquisition
    /// - Package manager can optimize internally
    ///
    /// Returns a BatchInstallResult indicating which packages succeeded/failed.
    /// On batch failure, individual packages are retried.
    pub fn batch_install(
        pm: PackageManager,
        packages: &[&str],
        use_sudo: Option<bool>,
    ) -> Result<BatchInstallResult, InstallError> {
        if packages.is_empty() {
            return Ok(BatchInstallResult {
                succeeded: vec![],
                failed: vec![],
            });
        }

        // Single package: use regular install
        if packages.len() == 1 {
            match Self::install(pm, packages[0], use_sudo) {
                Ok(()) => {
                    return Ok(BatchInstallResult {
                        succeeded: vec![packages[0].to_string()],
                        failed: vec![],
                    });
                }
                Err(e) => {
                    return Ok(BatchInstallResult {
                        succeeded: vec![],
                        failed: vec![(packages[0].to_string(), format!("{}", e))],
                    });
                }
            }
        }

        // Try batch install first
        let batch_result = Self::try_batch_install(pm, packages, use_sudo);

        match batch_result {
            Ok(()) => {
                // All packages installed successfully
                Ok(BatchInstallResult {
                    succeeded: packages.iter().map(|s| s.to_string()).collect(),
                    failed: vec![],
                })
            }
            Err(_) => {
                // Batch failed, retry individually to find which packages failed
                let mut succeeded = Vec::with_capacity(packages.len());
                let mut failed = Vec::with_capacity(packages.len());

                for pkg in packages {
                    match Self::install(pm, pkg, use_sudo) {
                        Ok(()) => succeeded.push(pkg.to_string()),
                        Err(e) => failed.push((pkg.to_string(), format!("{}", e))),
                    }
                }

                Ok(BatchInstallResult { succeeded, failed })
            }
        }
    }

    /// Attempt to install multiple packages in a single command.
    /// Returns Ok if all packages installed, Err if the command failed.
    fn try_batch_install(
        pm: PackageManager,
        packages: &[&str],
        use_sudo: Option<bool>,
    ) -> Result<(), InstallError> {
        match pm {
            PackageManager::Apt => {
                let apt = require_any(&["apt-get", "apt"], "apt is required to install packages")?;
                let mut args = vec!["install", "-y"];
                args.extend(packages);
                Self::run_with_sudo_strategy(use_sudo, apt, &args)
            }
            PackageManager::Dnf => {
                require("dnf", "dnf is required to install packages")?;
                let mut args = vec!["install", "-y"];
                args.extend(packages);
                Self::run_with_sudo_strategy(use_sudo, "dnf", &args)
            }
            PackageManager::Yum => {
                require("yum", "yum is required to install packages")?;
                let mut args = vec!["install", "-y"];
                args.extend(packages);
                Self::run_with_sudo_strategy(use_sudo, "yum", &args)
            }
            PackageManager::Zypper => {
                require("zypper", "zypper is required to install packages")?;
                let mut args = vec!["--non-interactive", "install", "--no-confirm"];
                args.extend(packages);
                Self::run_with_sudo_strategy(use_sudo, "zypper", &args)
            }
            PackageManager::Pacman => {
                require("pacman", "pacman is required to install packages")?;
                let mut args = vec!["--noconfirm", "-S"];
                args.extend(packages);
                Self::run_with_sudo_strategy(use_sudo, "pacman", &args)
            }
            PackageManager::Apk => {
                require("apk", "apk is required to install packages")?;
                let mut args = vec!["add"];
                args.extend(packages);
                Self::run_with_sudo_strategy(use_sudo, "apk", &args)
            }
            PackageManager::Brew => {
                require("brew", "Homebrew is required to install packages")?;
                let mut args = vec!["install"];
                args.extend(packages);
                run("brew", &args)?;
                Ok(())
            }
            PackageManager::Winget => {
                // winget doesn't support true batch install, but we can chain commands
                // For now, install sequentially since winget is internally sequential anyway
                require("winget", "Winget is required to install packages")?;
                for pkg in packages {
                    run("winget", &["install", "-e", "--id", pkg])?;
                }
                Ok(())
            }
            PackageManager::BrewCask => {
                require("brew", "Homebrew is required to install casks")?;
                let mut args = vec!["install", "--cask"];
                args.extend(packages);
                run("brew", &args)?;
                Ok(())
            }
            PackageManager::Choco => {
                require("choco", "Chocolatey is required to install packages")?;
                let mut args = vec!["install", "-y"];
                args.extend(packages);
                run("choco", &args)?;
                Ok(())
            }
            PackageManager::Pkg => {
                require("pkg", "FreeBSD pkg is required to install packages")?;
                let mut args = vec!["install", "-y"];
                args.extend(packages);
                Self::run_with_sudo_strategy(use_sudo, "pkg", &args)
            }
        }
    }

    /// Helper to run a command with sudo fallback strategy.
    fn run_with_sudo_strategy(
        use_sudo: Option<bool>,
        cmd: &str,
        args: &[&str],
    ) -> Result<(), InstallError> {
        match use_sudo {
            Some(flag) => {
                if flag {
                    require("sudo", "sudo is required to install packages")?;
                }
                run_maybe_sudo(flag, cmd, args)?;
                Ok(())
            }
            None => {
                if let Err(e) = run_maybe_sudo(false, cmd, args) {
                    if has("sudo") {
                        run_maybe_sudo(true, cmd, args)?;
                        Ok(())
                    } else {
                        Err(e)
                    }
                } else {
                    Ok(())
                }
            }
        }
    }

    /// Install packages using Homebrew cask (for GUI apps) in batch.
    pub fn batch_install_cask(packages: &[&str]) -> Result<BatchInstallResult, InstallError> {
        if packages.is_empty() {
            return Ok(BatchInstallResult {
                succeeded: vec![],
                failed: vec![],
            });
        }

        require("brew", "Homebrew is required to install casks")?;

        let mut args = vec!["install", "--cask"];
        args.extend(packages);

        match run("brew", &args) {
            Ok(_) => Ok(BatchInstallResult {
                succeeded: packages.iter().map(|s| s.to_string()).collect(),
                failed: vec![],
            }),
            Err(_) => {
                // Retry individually
                let mut succeeded = Vec::with_capacity(packages.len());
                let mut failed = Vec::with_capacity(packages.len());
                for pkg in packages {
                    match run("brew", &["install", "--cask", pkg]) {
                        Ok(_) => succeeded.push(pkg.to_string()),
                        Err(e) => failed.push((pkg.to_string(), format!("{}", e))),
                    }
                }
                Ok(BatchInstallResult { succeeded, failed })
            }
        }
    }

    /// Install packages using Chocolatey in batch.
    pub fn batch_install_choco(packages: &[&str]) -> Result<BatchInstallResult, InstallError> {
        if packages.is_empty() {
            return Ok(BatchInstallResult {
                succeeded: vec![],
                failed: vec![],
            });
        }

        require("choco", "Chocolatey is required to install packages")?;

        let mut args = vec!["install", "-y"];
        args.extend(packages);

        match run("choco", &args) {
            Ok(_) => Ok(BatchInstallResult {
                succeeded: packages.iter().map(|s| s.to_string()).collect(),
                failed: vec![],
            }),
            Err(_) => {
                // Retry individually
                let mut succeeded = Vec::with_capacity(packages.len());
                let mut failed = Vec::with_capacity(packages.len());
                for pkg in packages {
                    match run("choco", &["install", "-y", pkg]) {
                        Ok(_) => succeeded.push(pkg.to_string()),
                        Err(e) => failed.push((pkg.to_string(), format!("{}", e))),
                    }
                }
                Ok(BatchInstallResult { succeeded, failed })
            }
        }
    }

    pub fn update(pm: PackageManager, use_sudo: Option<bool>) -> Result<(), InstallError> {
        match pm {
            PackageManager::Apt => {
                // Ensure prerequisites exist before attempting the update
                let apt = require_any(&["apt-get", "apt"], "apt is required to update packages")?;
                // Decide sudo strategy
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to update packages")?;
                        }
                        run_maybe_sudo(flag, apt, &["update"])?;
                    }
                    None => {
                        // Try without sudo first
                        if let Err(e) = run_maybe_sudo(false, apt, &["update"]) {
                            // Retry with sudo if available
                            if has("sudo") {
                                run_maybe_sudo(true, apt, &["update"])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            PackageManager::Dnf => { /* dnf auto-refreshes; optional */ }
            PackageManager::Yum => { /* optional */ }
            PackageManager::Zypper => {
                require("zypper", "zypper is required to update packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to update packages")?;
                        }
                        run_maybe_sudo(flag, "zypper", &["--non-interactive", "refresh"])?;
                    }
                    None => {
                        if let Err(e) =
                            run_maybe_sudo(false, "zypper", &["--non-interactive", "refresh"])
                        {
                            if has("sudo") {
                                run_maybe_sudo(true, "zypper", &["--non-interactive", "refresh"])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            PackageManager::Pacman => {
                require("pacman", "pacman is required to update packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to update packages")?;
                        }
                        run_maybe_sudo(flag, "pacman", &["-Sy"])?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(false, "pacman", &["-Sy"]) {
                            if has("sudo") {
                                run_maybe_sudo(true, "pacman", &["-Sy"])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            PackageManager::Apk => { /* `apk add` refreshes on demand */ }
            PackageManager::Pkg => {
                require("pkg", "FreeBSD pkg is required to update packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to update packages")?;
                        }
                        run_maybe_sudo(flag, "pkg", &["update"])?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(false, "pkg", &["update"]) {
                            if has("sudo") {
                                run_maybe_sudo(true, "pkg", &["update"])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    pub fn install(
        pm: PackageManager,
        pkg: &str,
        use_sudo: Option<bool>,
    ) -> Result<(), InstallError> {
        match pm {
            PackageManager::Apt => {
                let apt = require_any(&["apt-get", "apt"], "apt is required to install packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to install packages")?;
                        }
                        run_maybe_sudo(flag, apt, &["install", "-y", pkg])?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(false, apt, &["install", "-y", pkg]) {
                            if has("sudo") {
                                run_maybe_sudo(true, apt, &["install", "-y", pkg])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            PackageManager::Dnf => {
                require("dnf", "dnf is required to install packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to install packages")?;
                        }
                        run_maybe_sudo(flag, "dnf", &["install", "-y", pkg])?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(false, "dnf", &["install", "-y", pkg]) {
                            if has("sudo") {
                                run_maybe_sudo(true, "dnf", &["install", "-y", pkg])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            PackageManager::Yum => {
                require("yum", "yum is required to install packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to install packages")?;
                        }
                        run_maybe_sudo(flag, "yum", &["install", "-y", pkg])?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(false, "yum", &["install", "-y", pkg]) {
                            if has("sudo") {
                                run_maybe_sudo(true, "yum", &["install", "-y", pkg])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            PackageManager::Zypper => {
                require("zypper", "zypper is required to install packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to install packages")?;
                        }
                        run_maybe_sudo(
                            flag,
                            "zypper",
                            &["--non-interactive", "install", "--no-confirm", pkg],
                        )?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(
                            false,
                            "zypper",
                            &["--non-interactive", "install", "--no-confirm", pkg],
                        ) {
                            if has("sudo") {
                                run_maybe_sudo(
                                    true,
                                    "zypper",
                                    &["--non-interactive", "install", "--no-confirm", pkg],
                                )?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            PackageManager::Pacman => {
                require("pacman", "pacman is required to install packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to install packages")?;
                        }
                        run_maybe_sudo(flag, "pacman", &["--noconfirm", "-S", pkg])?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(false, "pacman", &["--noconfirm", "-S", pkg])
                        {
                            if has("sudo") {
                                run_maybe_sudo(true, "pacman", &["--noconfirm", "-S", pkg])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            PackageManager::Apk => {
                require("apk", "apk is required to install packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to install packages")?;
                        }
                        run_maybe_sudo(flag, "apk", &["add", pkg])?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(false, "apk", &["add", pkg]) {
                            if has("sudo") {
                                run_maybe_sudo(true, "apk", &["add", pkg])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
            // These package managers generally do not require sudo by design here
            PackageManager::Brew => {
                require("brew", "Homebrew is required to install packages")?;
                run("brew", &["install", pkg])?;
            }
            PackageManager::BrewCask => {
                require("brew", "Homebrew is required to install casks")?;
                run("brew", &["install", "--cask", pkg])?;
            }
            PackageManager::Winget => {
                require("winget", "Winget is required to install packages")?;
                run("winget", &["install", "-e", "--id", pkg])?;
            }
            PackageManager::Choco => {
                require("choco", "Chocolatey is required to install packages")?;
                run("choco", &["install", "-y", pkg])?;
            }
            PackageManager::Pkg => {
                require("pkg", "FreeBSD pkg is required to install packages")?;
                match use_sudo {
                    Some(flag) => {
                        if flag {
                            require("sudo", "sudo is required to install packages")?;
                        }
                        run_maybe_sudo(flag, "pkg", &["install", "-y", pkg])?;
                    }
                    None => {
                        if let Err(e) = run_maybe_sudo(false, "pkg", &["install", "-y", pkg]) {
                            if has("sudo") {
                                run_maybe_sudo(true, "pkg", &["install", "-y", pkg])?;
                            } else {
                                return Err(e);
                            }
                        }
                    }
                }
            }
        };
        Ok(())
    }
}