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
use crate::{
package::Package,
package_manager::{CaptureFlag, PackageInstalledMethod, PackageManager, PackageManagerTrait},
};
use anyhow::{Context, Result};
use itertools::{iproduct, Itertools};
use run_script::ScriptOptions;
use std::{env::split_paths, iter::Peekable, path::PathBuf};
use strum::IntoEnumIterator;
impl PackageManager {
/// Whether the line contains a package manager.
pub fn detects_line(line: &str) -> bool {
Self::from_line(line).is_some()
}
/// Try to find the proper package manager corresponding to a line.
pub fn from_line(line: &str) -> Option<Self> {
// Iterate over all enum variations
Self::iter().find(|manager| {
// Iterate over all commands
manager
.os_commands()
.into_iter()
// Find the command that's in the file, use an extra space to only match full
// package names
.any(|command| line.contains(&format!("{} ", command)))
})
}
/// Check whether a package is already installed.
pub fn package_is_installed(self, package: &Package) -> Result<bool> {
match self.is_installed(package.name()) {
PackageInstalledMethod::Script(script) => {
// Run the installation script
let mut options = ScriptOptions::new();
options.exit_on_error = true;
options.print_commands = false;
// Only catch the exit status of the script
let (code, _, _) = run_script::run(&script, &vec![], &options)
.context("could not check whether package is installed")?;
Ok(code == 0)
}
PackageInstalledMethod::Path(path) => {
// Check whether the file or directory exists
Ok(path.exists())
}
}
}
/// Check if this package manager is available.
pub fn is_available(self) -> bool {
let path = std::env::var_os("PATH").expect("PATH env is not set");
// Taking all paths, merging them with executable name and checking, that executable exists.
let paths: Vec<PathBuf> = split_paths(&path).collect();
// Create a cartesian product of (Path, executable_name) and checking if any of pairs exists
iproduct!(paths, self.os_commands())
.map(|(path, exec)| path.join(PathBuf::from(exec)).exists())
.any(|x| x)
}
/// Extract the packages from the line.
pub fn catch(self, line: &str) -> Vec<Package> {
// Try all different commands
self.os_commands()
.iter()
.map(|command| {
// Get the part right of the package manager invocation
// The command has another space so lengthened versions of itself don't collide,
// for example 'apt' & 'apt-get'
match line.split(&format!("{} ", command)).nth(1) {
Some(rest_of_line) => {
// The resulting packages strings
let mut package_strings = vec![];
// A list of flags that we caught that we should keep track of
let mut catched_flags = vec![];
// Get which sub command is used
let sub_command = self.sub_commands().clone().into_iter().find(|command| {
rest_of_line.starts_with(&format!("{} ", command))
|| rest_of_line.contains(&format!(" {} ", command))
});
// Remove the sub command from the line
let line_without_subcommand = match sub_command {
Some(command) => rest_of_line.split(command).join(""),
// No installation subcommand means no packages
None => return vec![],
};
// Convert the line into an iterator over all arguments delimited by
// whitespace
let mut args_iter =
line_without_subcommand.split_ascii_whitespace().peekable();
// Loop over the arguments handling flags in a special way
while let Some(arg) = args_iter.next() {
if arg.starts_with('-') {
self.handle_capture_flags(&arg, &mut args_iter, &mut catched_flags);
// If it's a flag containing an extra arguments besides it skip one
if self.known_flags_with_values().contains(&arg) {
// Skip the next item
args_iter.next();
continue;
}
} else {
// We've found a package
package_strings.push(arg.to_string());
}
}
// Now convert it into actual packages
package_strings
.into_iter()
.map(|name| Package::new(self, name, catched_flags.clone()))
.collect()
}
// Package manager command was the last word of the line
None => vec![],
}
})
.flatten()
.collect()
}
/// Get OS specific commands, add .exe & .cmd on Windows.
#[cfg(target_os = "windows")]
fn os_commands(&self) -> Vec<String> {
self.commands()
.into_iter()
.map(|command| {
vec![
command.to_string(),
format!("{}.exe", command),
format!("{}.cmd", command),
]
})
.flatten()
.collect()
}
/// Get OS specific commands.
#[cfg(not(target_os = "windows"))]
fn os_commands(&self) -> Vec<&str> {
self.commands()
}
/// Handle the iterator's flags using the different options as defined in the package managers.
fn handle_capture_flags<'a, I>(
self,
arg: &str,
args_iter: &mut Peekable<I>,
catched_flags: &mut Vec<String>,
) where
I: Iterator<Item = &'a str>,
{
// Find the matching flags from the capture_flags function
let capture = match self
.capture_flags()
.into_iter()
.find(|capture| capture.flag() == arg)
{
Some(capture) => capture,
None => return,
};
match capture {
CaptureFlag::Single(flag) => {
// Just a single flag, add it to the list
catched_flags.push(flag.to_string());
}
CaptureFlag::SetValue(flag, value) => {
// The value is set and must match
if let Some(next_arg) = args_iter.peek() {
if &value == next_arg {
catched_flags.push(format!("{} {}", flag, value));
// We've looked at the next item so we should also skip it
args_iter.next();
}
}
}
CaptureFlag::DynamicValue(flag) => {
// The flag matches and the next value is dynamic so just take that
if let Some(next_arg) = args_iter.next() {
catched_flags.push(format!("{} {}", flag, next_arg))
}
}
}
}
}
impl CaptureFlag {
/// Extract the flag which is always there.
pub fn flag(self) -> &'static str {
match self {
CaptureFlag::Single(flag) => flag,
CaptureFlag::SetValue(flag, _) => flag,
CaptureFlag::DynamicValue(flag) => flag,
}
}
}
#[cfg(test)]
mod tests {
use crate::package_manager::PackageManager;
#[test]
fn test_detect() {
assert!(PackageManager::detects_line("apt install test"));
assert!(!PackageManager::detects_line("something"));
}
#[cfg(target_os = "windows")]
#[test]
fn test_detect_windows() {
assert!(PackageManager::detects_line("scoop.exe -h"));
assert!(PackageManager::detects_line("scoop.cmd -h"));
}
}