1use anyhow::{Context, Result, anyhow, bail};
2use regex::Regex;
3use std::{
4 env, fs,
5 path::{Path, PathBuf},
6};
7
8use crate::{
9 Ctx, Status, ToolKind, ToolReport, UpdateMethod, Version, http_get_text, info, link_dir_bins,
10 run_capture, which_or_none,
11};
12
13const MOJO_RELEASES_URL: &str = "https://mojolang.org/releases/";
14const PIXI_ADD_ARGS: &[&str] = &["add", "mojo"];
15const PIXI_UPDATE_ARGS: &[&str] = &["update", "mojo"];
16const UV_INSTALL_ARGS: &[&str] = &["pip", "install", "--system", "--upgrade", "mojo"];
17const PIP_INSTALL_ARGS: &[&str] = &["install", "--upgrade", "mojo"];
18
19pub fn mojo_latest(ctx: &Ctx) -> Result<Version> {
20 let page = http_get_text(ctx, MOJO_RELEASES_URL)?;
21 let re = Regex::new(r"Latest release:\s*([^<\s]+)")?;
22 let raw = re
23 .captures(&page)
24 .and_then(|captures| captures.get(1).map(|value| value.as_str()))
25 .ok_or_else(|| anyhow!("could not find latest Mojo release"))?;
26 Version::parse_loose(raw)
27 .ok_or_else(|| anyhow!("could not parse Mojo version from releases page: {raw}"))
28}
29
30pub fn check_mojo(ctx: &Ctx) -> Result<ToolReport> {
31 let installed = which_or_none("mojo")
32 .and_then(|_| run_capture("mojo", &["--version"]).ok())
33 .and_then(|out| Version::parse_loose(&out));
34
35 let mut notes =
36 vec!["Uses the official mojolang.org stable release page; updates via pixi or uv.".into()];
37 let latest = match mojo_latest(ctx) {
38 Ok(version) => Some(version),
39 Err(err) => {
40 notes.push(format!("Latest check failed: {err}"));
41 None
42 }
43 };
44 let status = Status::from_versions(installed.as_ref(), latest.as_ref());
45
46 Ok(ToolReport {
47 tool: ToolKind::Mojo,
48 installed,
49 latest,
50 status,
51 method: UpdateMethod::BuiltIn,
52 notes,
53 })
54}
55
56pub fn update_mojo(ctx: &Ctx) -> Result<()> {
57 if ctx.offline {
58 bail!("offline mode enabled; Mojo update requires network access");
59 }
60 let report = check_mojo(ctx)?;
61 let latest = report
62 .latest
63 .clone()
64 .ok_or_else(|| anyhow!("latest unknown"))?;
65
66 if matches!(report.status, Status::UpToDate) && !ctx.force {
67 info(ctx, format!("mojo is up-to-date ({})", latest.to_string()));
68 return Ok(());
69 }
70
71 let (program, args): (&str, &[&str]) =
72 if which_or_none("pixi").is_some() && pixi_project_dir().is_some() {
73 if report.installed.is_some() {
74 ("pixi", PIXI_UPDATE_ARGS)
75 } else {
76 ("pixi", PIXI_ADD_ARGS)
77 }
78 } else if which_or_none("uv").is_some() {
79 ("uv", UV_INSTALL_ARGS)
80 } else if which_or_none("pip3").is_some() {
81 ("pip3", PIP_INSTALL_ARGS)
82 } else if which_or_none("pip").is_some() {
83 ("pip", PIP_INSTALL_ARGS)
84 } else {
85 bail!("Mojo update requires pixi, uv, or pip; see https://mojolang.org/install/");
86 };
87
88 info(
89 ctx,
90 format!("Updating mojo via {} {}", program, args.join(" ")),
91 );
92 if ctx.dry_run {
93 info(
94 ctx,
95 format!("[dry-run] would run: {} {}", program, args.join(" ")),
96 );
97 return Ok(());
98 }
99
100 run_capture(program, args)
101 .with_context(|| format!("failed to run {program} update command"))?;
102 if matches!(program, "uv" | "pip" | "pip3") {
103 link_mojo_binary(ctx)?;
104 }
105 info(ctx, "mojo updated");
106 Ok(())
107}
108
109fn pixi_project_dir() -> Option<PathBuf> {
110 env::current_dir()
111 .ok()
112 .and_then(|cwd| find_pixi_project(&cwd))
113}
114
115fn find_pixi_project(start: &Path) -> Option<PathBuf> {
116 let mut dir = Some(start);
117 while let Some(path) = dir {
118 if path.join("pixi.toml").is_file() || is_pixi_pyproject(&path.join("pyproject.toml")) {
119 return Some(path.to_path_buf());
120 }
121 dir = path.parent();
122 }
123 None
124}
125
126fn is_pixi_pyproject(path: &Path) -> bool {
127 fs::read_to_string(path)
128 .ok()
129 .and_then(|text| toml::from_str::<toml::Value>(&text).ok())
130 .is_some_and(|value| {
131 value
132 .get("tool")
133 .and_then(|tool| tool.get("pixi"))
134 .is_some()
135 })
136}
137
138fn link_mojo_binary(ctx: &Ctx) -> Result<()> {
139 let Some(python) = which_or_none("python3").or_else(|| which_or_none("python")) else {
140 return Ok(());
141 };
142 let Ok(python) = fs::canonicalize(python) else {
143 return Ok(());
144 };
145 let Some(bin_dir) = python.parent() else {
146 return Ok(());
147 };
148 link_dir_bins(bin_dir, &ctx.bindir, &["mojo"])
149}
150
151#[cfg(test)]
152mod tests {
153 use super::find_pixi_project;
154 use std::fs;
155 use tempfile::tempdir;
156
157 #[test]
158 fn finds_pixi_manifests_in_parent_directories() {
159 let dir = tempdir().unwrap();
160 let nested = dir.path().join("nested");
161 fs::create_dir_all(&nested).unwrap();
162 assert!(find_pixi_project(&nested).is_none());
163
164 fs::write(dir.path().join("pixi.toml"), "[workspace]\n").unwrap();
165 assert_eq!(find_pixi_project(&nested).as_deref(), Some(dir.path()));
166
167 fs::remove_file(dir.path().join("pixi.toml")).unwrap();
168 fs::write(
169 dir.path().join("pyproject.toml"),
170 "[tool.pixi.workspace]\nchannels = [\"conda-forge\"]\n",
171 )
172 .unwrap();
173 assert_eq!(find_pixi_project(&nested).as_deref(), Some(dir.path()));
174 }
175}