1use core::cell::RefCell;
2use std::{
3 borrow::Cow,
4 collections::BTreeMap,
5 ffi::OsString,
6 fmt::{self, Display},
7 sync::LazyLock,
8};
9
10use clap::ValueEnum;
11use eyre::{eyre, Result};
12use serde::{Serialize, Deserialize};
13use strum::{EnumIter, IntoEnumIterator};
14
15use crate::package::Package;
16use crate::pls_command::PlsCommand;
17use crate::reinstall::reinstall_all;
18use crate::revendor::change_vendor;
19use crate::run_command::run_command;
20use crate::track;
21use crate::vendor_data::VendorData;
22
23
24#[derive(Debug, Clone, Copy, Default, EnumIter, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
25pub enum Vendor {
26 #[default]
27 Unknown,
28 Upt,
29 Cargo,
30 Go,
31 Npm,
32 Uv,
33 #[cfg(not(target_os = "windows"))]
34 Pkgx,
35 #[cfg(target_os = "linux")]
36 Apt,
37 #[cfg(target_os = "linux")]
38 Yay,
39 #[cfg(target_os = "linux")]
40 Yum,
41 #[cfg(target_os = "linux")]
42 Pacman,
43 #[cfg(target_os = "linux")]
44 Rua,
45 #[cfg(target_os = "linux")]
46 Apk,
47 #[cfg(target_os = "linux")]
48 Emerge,
49 #[cfg(target_os = "linux")]
50 Guix,
51 #[cfg(target_os = "linux")]
52 NixEnv,
53 #[cfg(target_os = "linux")]
54 Slackpkg,
55 #[cfg(target_os = "linux")]
56 Cards,
57 #[cfg(target_os = "linux")]
58 Dnf,
59 #[cfg(target_os = "linux")]
60 Eopkg,
61 #[cfg(target_os = "linux")]
62 Opkg,
63 #[cfg(target_os = "linux")]
64 Urpm,
65 #[cfg(target_os = "linux")]
66 Xbps,
67 #[cfg(target_os = "linux")]
68 Zypper,
69 #[cfg(target_os = "linux")]
70 Flatpak,
71 #[cfg(target_os = "linux")]
72 Snap,
73 #[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly", target_os = "netbsd"))]
74 Pkg,
75 #[cfg(target_os = "haiku")]
76 Pkgman,
77 #[cfg(target_os = "macos")]
78 Brew,
79 #[cfg(target_os = "macos")]
80 Ports,
81 #[cfg(target_os = "windows")]
82 Scoop,
83 #[cfg(target_os = "windows")]
84 Choco,
85 #[cfg(target_os = "windows")]
86 Winget,
87 #[cfg(target_os = "android")]
88 Termux,
89}
90
91impl Vendor {
92 pub fn new() -> Result<Self> {
93 for vendor in Vendor::iter() {
94 if vendor.is_available()? {
95 return Ok(vendor)
96 }
97 }
98 Err(eyre!(
99 "no vendor installed, candidates are: {}",
100 Vendor::iter().map(|vendor| vendor.to_string()).collect::<Vec<String>>().join(", "),
101 ))
102 }
103
104 #[allow(static_mut_refs)]
105 pub fn is_available(&self) -> Result<bool> {
106 unsafe {
107 if let Some(&available) = AVAILABILITY.borrow().get(self) {
108 return Ok(available);
109 }
110 }
111 let vendor_data: VendorData = (*self).try_into()?;
112 let available = which::which(vendor_data.1[0]).is_ok();
113 unsafe {
114 AVAILABILITY.borrow_mut().insert(self.clone(), available);
115 }
116 Ok(available)
117 }
118
119 pub fn execute(
120 self,
121 pls_command: PlsCommand,
122 args: Vec<String>,
123 yes: bool,
124 su: bool,
125 dry_run: bool,
126 pager: Option<String>,
127 supplied_vendor: Option<Vendor>,
128 ) -> Result<i32> {
129 if pls_command == PlsCommand::ReinstallAll {
130 return reinstall_all(supplied_vendor, yes, su, dry_run, pager);
131 }
132
133 if !dry_run {
134 if let PlsCommand::Move { origin, destination } = pls_command {
135 return change_vendor(origin, destination);
136 }
137 }
138
139 let vendor_data: VendorData = self.try_into()?;
140 let packages: Vec<Package> = args.iter()
141 .map(|arg| arg.as_str().into())
142 .map(|mut package: Package| {
143 package.vendor = self;
144 package
145 })
146 .collect();
147
148 let command = pls_command.format(vendor_data, &packages, yes, pager.clone());
149
150 if command.is_empty() {
151 eprintln!("command not supported by the current vendor");
152 return Ok(1)
153 }
154
155 if dry_run {
156 println!("{}", command);
157 return Ok(0);
158 }
159
160 let status = run_command(&command, su)?;
161
162 if !dry_run && status == 0 {
163 match pls_command {
164 PlsCommand::Install => track::save_installed_packages(packages, true)?,
165 PlsCommand::Remove => track::remove_installed_packages(packages)?,
166 _ => (),
167 }
168 }
169
170 Ok(status)
171 }
172
173 pub fn version_sep(&self) -> Cow<'static, str> {
174 match self {
175 Self::Pkgx |
176 Self::Npm => Cow::Borrowed("@"),
177 Self::Flatpak => Cow::Borrowed("//"),
178 _ => Cow::Borrowed("="),
179 }
180 }
181}
182
183impl TryFrom<OsString> for Vendor {
184 type Error = String;
185
186 fn try_from(value: OsString) -> Result<Self, Self::Error> {
187 let value = value.to_string_lossy().to_lowercase();
188 for vendor in Vendor::iter() {
189 if vendor.to_string().to_lowercase() == value {
190 return Ok(vendor);
191 }
192 }
193 Err(format!("invalid vendor name {}", value))
194 }
195}
196
197impl Display for Vendor {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 match self {
200 Self::Unknown => write!(f, "unknown"),
201 Self::Upt => write!(f, "upt"),
202 Self::Cargo => write!(f, "cargo"),
203 Self::Go => write!(f, "go"),
204 Self::Uv => write!(f, "uv"),
205 Self::Npm => write!(f, "npm"),
206 #[cfg(not(target_os = "windows"))]
207 Self::Pkgx => write!(f, "pkgx"),
208 #[cfg(target_os = "linux")]
209 Self::Apt => write!(f, "apt"),
210 #[cfg(target_os = "linux")]
211 Self::Yay => write!(f, "yay"),
212 #[cfg(target_os = "linux")]
213 Self::Yum => write!(f, "yum"),
214 #[cfg(target_os = "linux")]
215 Self::Pacman => write!(f, "pacman"),
216 #[cfg(target_os = "linux")]
217 Self::Rua => write!(f, "rua"),
218 #[cfg(target_os = "linux")]
219 Self::Apk => write!(f, "apk"),
220 #[cfg(target_os = "linux")]
221 Self::Emerge => write!(f, "emerge"),
222 #[cfg(target_os = "linux")]
223 Self::Guix => write!(f, "guix"),
224 #[cfg(target_os = "linux")]
225 Self::NixEnv => write!(f, "nix-env"),
226 #[cfg(target_os = "linux")]
227 Self::Slackpkg => write!(f, "slackpkg"),
228 #[cfg(target_os = "linux")]
229 Self::Cards => write!(f, "cards"),
230 #[cfg(target_os = "linux")]
231 Self::Dnf => write!(f, "dnf"),
232 #[cfg(target_os = "linux")]
233 Self::Eopkg => write!(f, "eopkg"),
234 #[cfg(target_os = "linux")]
235 Self::Opkg => write!(f, "opkg"),
236 #[cfg(target_os = "linux")]
237 Self::Urpm => write!(f, "urpm"),
238 #[cfg(target_os = "linux")]
239 Self::Xbps => write!(f, "xbps"),
240 #[cfg(target_os = "linux")]
241 Self::Zypper => write!(f, "zypper"),
242 #[cfg(target_os = "linux")]
243 Self::Flatpak => write!(f, "flatpak"),
244 #[cfg(target_os = "linux")]
245 Self::Snap => write!(f, "snap"),
246 #[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly", target_os = "netbsd"))]
247 Self::Pkg => write!(f, "pkg"),
248 #[cfg(target_os = "haiku")]
249 Self::Pkgman => write!(f, "pkgman"),
250 #[cfg(target_os = "macos")]
251 Self::Brew => write!(f, "brew"),
252 #[cfg(target_os = "macos")]
253 Self::Ports => write!(f, "ports"),
254 #[cfg(target_os = "windows")]
255 Self::Scoop => write!(f, "scoop"),
256 #[cfg(target_os = "windows")]
257 Self::Choco => write!(f, "choco"),
258 #[cfg(target_os = "windows")]
259 Self::Winget => write!(f, "winget"),
260 #[cfg(target_os = "android")]
261 Self::Termux => write!(f, "termux"),
262 }
263 }
264}
265
266impl TryFrom<&str> for Vendor {
267 type Error = eyre::Error;
268
269 fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
270 let value = value.to_lowercase();
271 for vendor in Vendor::iter() {
272 if vendor.to_string().to_lowercase() == value {
273 return Ok(vendor);
274 }
275 }
276 Err(eyre!("invalid vendor name {}", value))
277 }
278}
279
280impl ValueEnum for Vendor {
281 fn value_variants<'a>() -> &'a [Self] {
282 &VENDORS_SLICE
283 }
284
285 fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
286 Some(clap::builder::PossibleValue::new(self.to_string()))
287 }
288}
289
290static mut AVAILABILITY: LazyLock<RefCell<BTreeMap<Vendor, bool>>> = LazyLock::new(|| RefCell::new(BTreeMap::new()));
291static INNER_VENDORS: LazyLock<Vec<Vendor>> = LazyLock::new(|| Vendor::iter().collect());
292static VENDORS_SLICE: LazyLock<&[Vendor]> = LazyLock::new(|| &INNER_VENDORS);