1use std::path::{Path, PathBuf};
8
9use byob_tools::CommandEnv;
10
11use super::project::{Kind, ToolRun, parse_env, run_tool};
12use super::{EnvProvider, Layer, Runner};
13
14#[derive(Debug, Clone)]
16pub struct CommandProvider {
17 decl: CommandEnv,
18}
19
20impl CommandProvider {
21 pub fn new(decl: CommandEnv) -> Self {
22 Self { decl }
23 }
24}
25
26impl EnvProvider for CommandProvider {
27 fn id(&self) -> &str {
28 &self.decl.id
29 }
30
31 fn label(&self) -> &str {
32 &self.decl.label
33 }
34
35 fn file(&self, ws: &Path) -> Option<String> {
36 self.decl.detect.iter().find(|f| ws.join(f).is_file()).cloned()
37 }
38
39 fn inputs(&self) -> Vec<String> {
40 let mut out = self.decl.detect.clone();
41 out.extend(self.decl.inputs.iter().filter(|i| !self.decl.detect.contains(i)).cloned());
42 out
43 }
44
45 fn load(&self, ws: &Path, _dir: &Path, run: &dyn Runner) -> Result<Layer, String> {
46 let args: Vec<String> = self
48 .decl
49 .args
50 .iter()
51 .map(|a| {
52 let inside = self.decl.dir.join(a);
53 if !a.starts_with('-') && byob_plugins_path_ok(a) && inside.is_file() { inside.display().to_string() } else { a.clone() }
54 })
55 .collect();
56 let program = program(&self.decl.program, &self.decl.dir).ok_or_else(|| format!("{} isn't installed (not on PATH)", self.decl.program.display()))?;
57 let name = self.decl.program.display().to_string();
58 let t = ToolRun { program: &program, name: &name, cwd: ws, write: vec![ws.to_path_buf()], read: vec![self.decl.dir.clone()], env: Vec::new() };
59 let refs: Vec<&str> = args.iter().map(String::as_str).collect();
60 let text = run_tool(&t, &refs, run, true)?.unwrap_or_default();
61 let host: Vec<PathBuf> = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
62 let kind = if serde_json::from_str::<serde_json::Value>(&text).ok().is_some_and(|v| v.get("environment_variables").is_some()) {
63 Kind::Pixi
64 } else {
65 Kind::Mise
66 };
67 parse_env(kind, &text, &host).map_err(|e| format!("{e} (from `{name}`)"))
68 }
69}
70
71fn byob_plugins_path_ok(p: &str) -> bool {
73 let p = Path::new(p);
74 !p.is_absolute() && p.components().all(|c| matches!(c, std::path::Component::Normal(_) | std::path::Component::CurDir))
75}
76
77fn program(p: &Path, dir: &Path) -> Option<PathBuf> {
79 if p.is_absolute() {
80 return p.is_file().then(|| p.to_path_buf());
81 }
82 let inside = dir.join(p);
83 if p.components().count() > 1 || inside.is_file() {
84 return inside.is_file().then_some(inside);
85 }
86 byob_sandbox::which(p.as_os_str())
87}
88
89#[cfg(test)]
90mod tests {
91 use super::*;
92
93 #[test]
94 fn detects_by_its_files_and_keys_the_cache_by_them() {
95 let ws = tempfile::tempdir().unwrap();
96 let p = CommandProvider::new(CommandEnv {
97 id: "demo-conda".into(),
98 label: "conda environment".into(),
99 detect: vec!["environment.yml".into()],
100 inputs: vec!["conda.lock".into(), "environment.yml".into()],
101 program: "python3".into(),
102 ..CommandEnv::default()
103 });
104 assert_eq!(p.file(ws.path()), None);
105 std::fs::write(ws.path().join("environment.yml"), "name: x\n").unwrap();
106 assert_eq!(p.file(ws.path()).as_deref(), Some("environment.yml"));
107 assert_eq!(p.inputs(), ["environment.yml", "conda.lock"]);
108 assert!(byob_plugins_path_ok("env.py") && !byob_plugins_path_ok("../x") && !byob_plugins_path_ok("/x"));
109 }
110}