1use std::ffi::OsString;
15use std::path::{Path, PathBuf};
16use std::time::Duration;
17
18use serde_json::Value;
19
20use super::{Layer, Project, Runner, STOPPED, keep_var};
21use crate::Job;
22
23const LOAD_TIMEOUT: Duration = Duration::from_secs(900);
24const MAX_JSON: u64 = 4 << 20;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Kind {
29 Pixi,
30 Mise,
31}
32
33#[derive(Debug, Clone)]
35pub struct JsonEnvTool {
36 kind: Kind,
37 program: PathBuf,
38 state: Option<PathBuf>,
40}
41
42impl JsonEnvTool {
43 pub fn new(kind: Kind, program: PathBuf, data_dir: Option<&Path>) -> Self {
45 let name = match kind {
46 Kind::Pixi => "pixi",
47 Kind::Mise => "mise",
48 };
49 Self { kind, program, state: data_dir.map(|d| d.join(name)) }
50 }
51
52 pub fn program(&self) -> &Path {
53 &self.program
54 }
55
56 fn vars(&self, ws: &Path) -> Vec<(String, OsString)> {
58 let Some(s) = &self.state else { return Vec::new() };
59 let mut v: Vec<(String, OsString)> = match self.kind {
60 Kind::Pixi => vec![("PIXI_CACHE_DIR".into(), s.join("cache").into()), ("RATTLER_CACHE_DIR".into(), s.join("cache").into())],
61 Kind::Mise => vec![("MISE_DATA_DIR".into(), s.join("data").into()), ("MISE_CACHE_DIR".into(), s.join("cache").into())],
62 };
63 if self.kind == Kind::Mise {
64 v.push(("MISE_TRUSTED_CONFIG_PATHS".into(), ws.into()));
65 v.push(("MISE_YES".into(), "1".into()));
66 }
67 v
68 }
69
70 fn run_tool(&self, args: &[&str], ws: &Path, run: &dyn Runner, capture: bool) -> Result<Option<String>, String> {
73 let mut write = vec![ws.to_path_buf()];
74 write.extend(self.state.clone());
75 let t = ToolRun { program: &self.program, name: self.label_cmd(), cwd: ws, write, read: Vec::new(), env: self.vars(ws) };
76 run_tool(&t, args, run, capture)
77 }
78
79 fn label_cmd(&self) -> &'static str {
80 match self.kind {
81 Kind::Pixi => "pixi",
82 Kind::Mise => "mise",
83 }
84 }
85}
86
87pub(crate) struct ToolRun<'a> {
89 pub program: &'a Path,
90 pub name: &'a str,
92 pub cwd: &'a Path,
93 pub write: Vec<PathBuf>,
95 pub read: Vec<PathBuf>,
97 pub env: Vec<(String, OsString)>,
98}
99
100pub(crate) fn run_tool(t: &ToolRun<'_>, args: &[&str], run: &dyn Runner, capture: bool) -> Result<Option<String>, String> {
103 let tmp = byob_sandbox::TempDir::new("byob-env-")?;
104 let out_file = tmp.path().join("env.json");
105 let mut job = if cfg!(windows) {
106 let mut j = Job::new(t.program.as_os_str().to_owned(), args.iter().map(OsString::from).collect(), LOAD_TIMEOUT);
108 j.max_output = usize::try_from(MAX_JSON).unwrap_or(usize::MAX).saturating_mul(2);
109 j
110 } else {
111 let mut argv: Vec<OsString> = vec!["-c".into(), if capture { r#"exec "$@" > "$BYOB_OUT""# } else { r#"exec "$@""# }.into(), "sh".into()];
113 argv.push(t.program.as_os_str().to_owned());
114 argv.extend(args.iter().map(OsString::from));
115 Job::new("sh".into(), argv, LOAD_TIMEOUT)
116 };
117 job.network = true;
118 job.big_memory = true;
119 for w in &t.write {
120 std::fs::create_dir_all(w).map_err(|e| format!("can't create {}: {e}", w.display()))?;
121 job.layer.write.push(w.clone());
122 }
123 job.layer.read.extend(t.read.iter().cloned());
124 job.env.clone_from(&t.env);
125 job.env.push(("BYOB_OUT".into(), out_file.clone().into_os_string()));
126 let out = run.run(job, t.cwd, tmp.path())?;
127 if out.cancelled {
128 return Err(STOPPED.into());
129 }
130 if !out.success() {
131 let err = out.stderr.text();
132 return Err(format!("`{} {}` failed: {}", t.name, args.join(" "), err.trim()));
133 }
134 if !capture {
135 return Ok(None);
136 }
137 if cfg!(windows) {
138 if out.stdout.dropped > 0 || out.stdout.bytes().len() as u64 > MAX_JSON {
139 return Err("the environment is too large".into());
140 }
141 return Ok(Some(out.stdout.text()));
142 }
143 let size = std::fs::metadata(&out_file).map(|m| m.len()).unwrap_or(0);
144 if size > MAX_JSON {
145 return Err(format!("the environment is too large ({size} bytes)"));
146 }
147 std::fs::read_to_string(&out_file).map(Some).map_err(|e| format!("no environment from {}: {e}", t.name))
148}
149
150impl Project for JsonEnvTool {
151 fn id(&self) -> &str {
152 self.label_cmd()
153 }
154
155 fn label(&self) -> &str {
156 match self.kind {
157 Kind::Pixi => "pixi environment",
158 Kind::Mise => "mise tools",
159 }
160 }
161
162 fn file(&self, ws: &Path) -> Option<String> {
163 project_file(self.kind, ws).map(str::to_owned)
164 }
165
166 fn inputs(&self) -> Vec<String> {
167 let files: &[&str] = match self.kind {
168 Kind::Pixi => &["pixi.toml", "pixi.lock", "pyproject.toml"],
169 Kind::Mise => &["mise.toml", ".mise.toml", ".tool-versions", "mise.lock"],
170 };
171 files.iter().map(|f| (*f).to_owned()).collect()
172 }
173
174 fn load(&self, ws: &Path, _dir: &Path, run: &dyn Runner) -> Result<Layer, String> {
175 let text = match self.kind {
176 Kind::Pixi => self.run_tool(&["shell-hook", "--json"], ws, run, true)?,
177 Kind::Mise => {
178 self.run_tool(&["install"], ws, run, false)?;
179 self.run_tool(&["env", "--json"], ws, run, true)?
180 }
181 };
182 let host: Vec<PathBuf> = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
183 let mut layer = parse_env(self.kind, text.as_deref().unwrap_or_default(), &host)?;
184 layer.read.extend(self.state.clone());
186 Ok(layer)
187 }
188}
189
190pub fn project_file(kind: Kind, ws: &Path) -> Option<&'static str> {
192 match kind {
193 Kind::Pixi => {
194 if ws.join("pixi.toml").is_file() {
195 return Some("pixi.toml");
196 }
197 let py = std::fs::read_to_string(ws.join("pyproject.toml")).ok()?;
198 py.lines().any(|l| l.trim_start().starts_with("[tool.pixi")).then_some("pyproject.toml")
199 }
200 Kind::Mise => ["mise.toml", ".mise.toml", ".tool-versions"].into_iter().find(|f| ws.join(f).is_file()),
201 }
202}
203
204pub fn parse_env(kind: Kind, text: &str, host: &[PathBuf]) -> Result<Layer, String> {
207 let v: Value = serde_json::from_str(text).map_err(|e| format!("bad environment JSON: {e}"))?;
208 let vars = match kind {
209 Kind::Pixi => v.get("environment_variables"),
210 Kind::Mise => Some(&v),
211 }
212 .and_then(Value::as_object)
213 .ok_or("the environment JSON has no variables")?;
214 let mut l = Layer::default();
215 for (k, val) in vars {
216 let Some(val) = val.as_str() else { continue };
217 if k == "PATH" {
218 for p in std::env::split_paths(val) {
219 if p.is_absolute() && !host.contains(&p) && !l.path.contains(&p) {
220 l.path.push(p);
221 }
222 }
223 } else if !keep_var(k) && !k.is_empty() && !k.contains(['=', '\0']) && !val.contains('\0') {
224 l.vars.push((k.clone(), val.to_owned()));
225 }
226 }
227 Ok(l)
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 #[cfg(unix)]
235 #[test]
236 fn pixi_and_mise_json() {
237 let host = vec![PathBuf::from("/usr/bin"), PathBuf::from("/bin")];
238 let pixi = r#"{"environment_variables":{"CONDA_PREFIX":"/w/.pixi/envs/default","PIXI_PROJECT_NAME":"t","PATH":"/w/.pixi/envs/default/bin:/usr/bin:/bin","HOME":"/x"}}"#;
239 let l = parse_env(Kind::Pixi, pixi, &host).unwrap();
240 assert_eq!(l.path, vec![PathBuf::from("/w/.pixi/envs/default/bin")]);
241 assert_eq!(l.var("CONDA_PREFIX"), Some("/w/.pixi/envs/default"));
242 assert_eq!(l.var("HOME"), None);
243 let mise = r#"{"GREETING":"hi","PATH":"/d/installs/node/22/bin:/usr/bin","N":1}"#;
244 let l = parse_env(Kind::Mise, mise, &host).unwrap();
245 assert_eq!(l.path, vec![PathBuf::from("/d/installs/node/22/bin")]);
246 assert_eq!(l.vars, vec![("GREETING".to_owned(), "hi".to_owned())]);
247 assert!(parse_env(Kind::Pixi, "{}", &host).is_err() && parse_env(Kind::Mise, "[1]", &host).is_err() && parse_env(Kind::Mise, "x", &host).is_err());
248 }
249
250 #[test]
251 fn project_files() {
252 let d = tempfile::tempdir().unwrap();
253 assert_eq!(project_file(Kind::Pixi, d.path()), None);
254 assert_eq!(project_file(Kind::Mise, d.path()), None);
255 std::fs::write(d.path().join("pyproject.toml"), "[project]\nname = \"x\"\n").unwrap();
256 assert_eq!(project_file(Kind::Pixi, d.path()), None);
257 std::fs::write(d.path().join("pyproject.toml"), "[project]\nname = \"x\"\n\n[tool.pixi.workspace]\nchannels = []\n").unwrap();
258 assert_eq!(project_file(Kind::Pixi, d.path()), Some("pyproject.toml"));
259 std::fs::write(d.path().join("pixi.toml"), "").unwrap();
260 assert_eq!(project_file(Kind::Pixi, d.path()), Some("pixi.toml"));
261 std::fs::write(d.path().join(".tool-versions"), "nodejs 22\n").unwrap();
262 assert_eq!(project_file(Kind::Mise, d.path()), Some(".tool-versions"));
263 }
264}