1use crate::PackageManager;
2use anyhow::Error;
3use std::process::{Command, Stdio};
4
5pub struct Homebrew {}
6
7impl Homebrew {
8 pub fn new() -> Self {
9 Self {}
10 }
11
12 pub fn create_install_command(&self, name: &str) -> Command {
13 let mut command = Command::new("sh");
14 command
15 .arg("-c")
16 .arg(format!("brew install {}", name))
17 .stdin(Stdio::inherit())
18 .stdout(Stdio::inherit())
19 .stderr(Stdio::inherit());
20 command
21 }
22}
23
24impl Default for Homebrew {
25 fn default() -> Self {
26 Self::new()
27 }
28}
29
30impl PackageManager for Homebrew {
31 fn install(&self, name: &str) -> Result<(), Error> {
32 self.setup()?;
33 let mut child = self.create_install_command(name).spawn()?;
34 child.wait()?;
35 Ok(())
36 }
37
38 fn uninstall(&self, name: &str) -> Result<(), Error> {
39 let mut child = Command::new("sh")
40 .arg("-c")
41 .arg(format!("brew uninstall {}", name))
42 .stdin(Stdio::inherit())
43 .stdout(Stdio::inherit())
44 .stderr(Stdio::inherit())
45 .spawn()?;
46 child.wait()?;
47 Ok(())
48 }
49
50 fn setup(&self) -> Result<(), Error> {
51 std::env::set_var(
52 "PATH",
53 format!(
54 "{}:{}",
55 std::env::var("PATH").unwrap(),
56 "/home/linuxbrew/.linuxbrew/bin"
57 ),
58 );
59 let mut child = Command::new("sh")
60 .arg("-c")
61 .arg(r#"type brew > /dev/null || /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)""#)
62 .stdin(Stdio::inherit())
63 .stdout(Stdio::inherit())
64 .stderr(Stdio::inherit())
65 .spawn()?;
66 child.wait()?;
67 Ok(())
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn test_create_child_command_with_version() {
77 let homebrew = Homebrew::new();
78 let command = homebrew.create_install_command("neovim@0.9.5");
79 assert_eq!(command.get_args().len(), 2);
80 assert_eq!(
81 command.get_args().last().unwrap().to_string_lossy(),
82 "brew install neovim@0.9.5"
83 );
84 }
85
86 #[test]
87 fn test_create_child_command_without_version() {
88 let homebrew = Homebrew::new();
89 let command = homebrew.create_install_command("neovim");
90 assert_eq!(command.get_args().len(), 2);
91 assert_eq!(
92 command.get_args().last().unwrap().to_string_lossy(),
93 "brew install neovim"
94 );
95 }
96
97 #[test]
98 fn test_create_child_command_with_head() {
99 let homebrew = Homebrew::new();
100 let command = homebrew.create_install_command("neovim --HEAD");
101 assert_eq!(command.get_args().len(), 2);
102 assert_eq!(
103 command.get_args().last().unwrap().to_string_lossy(),
104 "brew install neovim --HEAD"
105 );
106 }
107}