1use super::nix::{PYTHON_IMPORTS, command_package};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Fix {
9 Packages,
11 PythonOnly,
13 None,
15}
16
17pub const GET_PIXI: &str = "byob has no package manager here. Tell the user that installing pixi (https://pixi.sh, e.g. \
19`curl -fsSL https://pixi.sh/install.sh | sh`, `brew install pixi` or `winget install prefix-dev.pixi`) and restarting byob \
20lets install_packages add programs and Python libraries for this workspace.";
21
22pub fn hint(stdout: &str, stderr: &str, command: Option<&str>, fix: Fix, system: Option<&str>) -> Option<String> {
25 let last_resort = |what: &str| {
26 system.map_or_else(String::new, |s| {
27 format!(" As a last resort, install_system_packages can install {what} system-wide with {s} (the user must approve).")
28 })
29 };
30 let module = missing_module(stderr).or_else(|| missing_module(stdout));
31 let cmd = missing_command(stderr);
32 if fix == Fix::None || (fix == Fix::PythonOnly && module.is_none()) {
33 let (what, pkg) = match (&module, &cmd) {
34 (Some(m), _) => (format!("the Python library `{m}` is"), python_package(m)),
35 (None, Some(c)) => (format!("`{c}` is"), command_package(c).unwrap_or(c).to_owned()),
36 (None, None) => return None,
37 };
38 return Some(format!("Hint: {what} not installed, and {GET_PIXI}{}", last_resort(&pkg)));
39 }
40 if let Some(module) = module {
41 let pkg = python_package(&module);
42 return Some(match fix {
43 Fix::Packages => {
44 format!("Hint: the Python library `{module}` is not installed. Call install_packages with {{\"packages\": [\"{pkg}\"]}}, then run this again.")
45 }
46 _ => format!(
47 "Hint: the Python library `{module}` is not installed. Call install_python_packages with {{\"packages\": [\"{pkg}\"]}}, then run this again."
48 ),
49 });
50 }
51 if fix != Fix::Packages {
52 return None;
53 }
54 if let Some(cmd) = cmd {
55 let pkg = command_package(&cmd).unwrap_or(&cmd);
56 return Some(format!("Hint: `{cmd}` is not installed. Call install_packages with {{\"packages\": [\"{pkg}\"]}}, then run the command again."));
57 }
58 let c = command?;
59 let installs = [
60 "pip install",
61 "pip3 install",
62 "python -m pip",
63 "python3 -m pip",
64 "apt ",
65 "apt-get",
66 "sudo ",
67 "brew install",
68 "dnf ",
69 "yum ",
70 "pacman ",
71 "nix-env",
72 "nix profile install",
73 ];
74 installs.iter().any(|w| c.contains(w)).then(|| {
75 "Hint: installing software that way doesn't work here. Call install_packages with the programs or Python libraries you need (e.g. {\"packages\": [\"jq\", \"matplotlib\"]}); they stay installed for this workspace.".to_owned()
76 })
77}
78
79pub fn missing_command(stderr: &str) -> Option<String> {
81 stderr.lines().find_map(|line| {
82 let rest = line.trim_end().strip_suffix(": command not found").or_else(|| line.trim_end().strip_suffix(": not found"))?;
83 let name = rest.rsplit(": ").next()?.trim();
84 let ok = !name.is_empty() && name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || "._+-".contains(c));
85 ok.then(|| name.to_owned())
86 })
87}
88
89pub fn missing_module(text: &str) -> Option<String> {
91 let (_, rest) = text.split_once("No module named '")?;
92 let name = rest.split('\'').next()?;
93 let ok = !name.is_empty() && name.len() <= 100 && name.chars().all(|c| c.is_ascii_alphanumeric() || "._".contains(c));
94 ok.then(|| {
95 if PYTHON_IMPORTS.iter().any(|(import, _)| *import == name) { name.to_owned() } else { name.split('.').next().unwrap_or(name).to_owned() }
97 })
98}
99
100fn python_package(module: &str) -> String {
102 PYTHON_IMPORTS.iter().find(|(import, _)| *import == module).map_or_else(|| module.to_owned(), |(_, pkg)| (*pkg).to_owned())
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 #[test]
110 fn missing_commands_from_each_shell() {
111 assert_eq!(missing_command("sh: 1: jq: not found").as_deref(), Some("jq"));
112 assert_eq!(missing_command("sh: jq: command not found\n").as_deref(), Some("jq"));
113 assert_eq!(missing_command("bash: line 1: rg: command not found").as_deref(), Some("rg"));
114 assert_eq!(missing_command("zsh: command not found: jq"), None);
115 assert_eq!(missing_command("cat: x.txt: No such file or directory"), None);
116 assert_eq!(missing_command("sh: 1: $(evil): not found"), None);
117 }
118
119 #[test]
120 fn missing_modules() {
121 assert_eq!(missing_module("ModuleNotFoundError: No module named 'matplotlib.pyplot'").as_deref(), Some("matplotlib"));
122 assert_eq!(missing_module("No module named 'PIL'").as_deref(), Some("PIL"));
123 assert_eq!(missing_module("No module named 'google.protobuf'").as_deref(), Some("google.protobuf"));
124 assert_eq!(missing_module("all fine"), None);
125 }
126
127 #[test]
128 fn hints_name_the_tool_and_package() {
129 let h = hint("", "sh: 1: convert: not found", Some("convert a.png b.jpg"), Fix::Packages, None).unwrap();
130 assert!(h.contains("install_packages") && h.contains("[\"imagemagick\"]"), "{h}");
131 let h = hint("", "ModuleNotFoundError: No module named 'sklearn'", None, Fix::Packages, None).unwrap();
132 assert!(h.contains("[\"scikit-learn\"]"), "{h}");
133 let h = hint("", "ModuleNotFoundError: No module named 'PIL'", None, Fix::PythonOnly, None).unwrap();
134 assert!(h.contains("install_python_packages") && h.contains("[\"pillow\"]"), "{h}");
135 assert!(hint("", "error: externally-managed-environment", Some("pip install pandas"), Fix::Packages, None).unwrap().contains("install_packages"));
136 assert!(hint("", "some other failure", Some("ls"), Fix::Packages, None).is_none());
137 assert!(hint("", "some other failure", Some("ls"), Fix::None, Some("Homebrew")).is_none());
138 }
139
140 #[test]
141 fn without_an_installer_the_hint_says_how_to_get_pixi() {
142 let h = hint("", "sh: 1: jq: not found", None, Fix::PythonOnly, None).unwrap();
143 assert!(h.contains("`jq` is not installed") && h.contains("https://pixi.sh") && !h.contains("install_system_packages"), "{h}");
144 let h = hint("", "sh: 1: convert: not found", None, Fix::None, Some("Homebrew")).unwrap();
145 assert!(h.contains("pixi") && h.contains("install_system_packages can install imagemagick system-wide with Homebrew"), "{h}");
146 let h = hint("", "No module named 'PIL'", None, Fix::None, None).unwrap();
147 assert!(h.contains("`PIL`") && h.contains("pixi"), "{h}");
148 }
149}