1use std::path::{Path, PathBuf};
23
24const INSTALLER: &str = "https://miradb.dev/install.sh";
28
29const RELEASES: &str = "https://github.com/TrianaLab/mira/releases";
31
32pub fn cli() -> clap::Command {
38 clap::Command::new("update")
39 .about("replace this binary with a release from GitHub")
40 .after_help(
41 "Runs the same installer as\n \
42 curl -fsSL https://miradb.dev/install.sh | bash\n\n\
43 Installs over this binary's own directory, not /usr/local/bin, unless\n\
44 MIRA_INSTALL_DIR says otherwise. Nothing happens if the running version\n\
45 is already the one that would be installed.\n\n\
46 Needs bash and either curl or wget, because it runs the installer rather\n\
47 than carrying an HTTPS client. The container image has none of them;\n\
48 upgrade that by pulling a newer tag.",
49 )
50 .arg(
51 clap::Arg::new("version")
52 .long("version")
53 .short('v')
54 .value_name("VERSION")
55 .value_parser(tag)
56 .help("install this tag instead of the latest (e.g. v0.1.0)"),
57 )
58 .arg(
59 clap::Arg::new("dry-run")
60 .long("dry-run")
61 .action(clap::ArgAction::SetTrue)
62 .help("print the command that would run, and stop"),
63 )
64}
65
66pub fn tag(v: &str) -> Result<String, String> {
75 if v.is_empty()
76 || !v
77 .chars()
78 .all(|c| c.is_ascii_alphanumeric() || "._-".contains(c))
79 {
80 return Err(format!("{v:?} is not a release tag"));
81 }
82 Ok(v.to_owned())
83}
84
85pub fn command(version: Option<&str>) -> String {
91 let tag = match version {
92 Some(v) => format!(" --version {v}"),
93 None => String::new(),
94 };
95 format!(
96 "if command -v curl >/dev/null 2>&1; then curl -fsSL {INSTALLER}; \
97 elif command -v wget >/dev/null 2>&1; then wget -qO- {INSTALLER}; \
98 else echo 'mira update needs curl or wget' >&2; exit 1; fi \
99 | bash -s --{tag}"
100 )
101}
102
103pub fn install_dir(exe: Option<&Path>) -> Option<PathBuf> {
110 let real = std::fs::canonicalize(exe?).ok()?;
111 real.parent().map(Path::to_path_buf)
112}
113
114pub fn run(m: &clap::ArgMatches) -> Result<(), String> {
121 let line = command(m.get_one::<String>("version").map(String::as_str));
122 if m.get_flag("dry-run") {
123 println!("{line}");
124 return Ok(());
125 }
126
127 spawn(&mut installer(&line))
128}
129
130fn installer(line: &str) -> std::process::Command {
136 let mut cmd = std::process::Command::new("bash");
137 cmd.arg("-c").arg(line);
138 if std::env::var_os("MIRA_INSTALL_DIR").is_none()
139 && let Some(dir) = install_dir(std::env::current_exe().ok().as_deref())
140 {
141 cmd.env("MIRA_INSTALL_DIR", dir);
142 }
143 cmd
144}
145
146fn spawn(cmd: &mut std::process::Command) -> Result<(), String> {
152 let status = cmd
153 .status()
154 .map_err(|e| start_failed(&cmd.get_program().to_string_lossy(), &e))?;
155 if !status.success() {
156 return Err(format!("installer exited with {status}"));
157 }
158 Ok(())
159}
160
161fn start_failed(program: &str, e: &std::io::Error) -> String {
171 if e.kind() == std::io::ErrorKind::NotFound {
172 return format!(
173 "`{program}` is not on PATH, so there is nothing here to run the \
174 installer with. In a container, upgrade by pulling a newer image \
175 tag. Otherwise install {program}, or take the tarball for this \
176 platform straight from {RELEASES}."
177 );
178 }
179 format!("could not run the installer: {e}")
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 fn parse(a: &[&str]) -> Result<clap::ArgMatches, String> {
188 cli()
189 .try_get_matches_from(std::iter::once("update").chain(a.iter().copied()))
190 .map_err(|e| e.to_string())
191 }
192
193 #[test]
194 fn no_flags_installs_the_latest_release() {
195 let m = parse(&[]).unwrap();
196 assert_eq!(m.get_one::<String>("version"), None);
197 assert!(!m.get_flag("dry-run"));
198 let line = command(None);
199 assert!(line.ends_with("| bash -s --"), "{line}");
200 assert!(line.contains(INSTALLER), "{line}");
201 }
202
203 #[test]
204 fn a_tag_is_forwarded_to_the_installer() {
205 let m = parse(&["--version", "v0.1.0"]).unwrap();
206 let v = m.get_one::<String>("version").map(String::as_str);
207 assert_eq!(v, Some("v0.1.0"));
208 assert!(!m.get_flag("dry-run"));
209 assert!(command(v).ends_with("--version v0.1.0"));
210 }
211
212 #[test]
213 fn a_tag_that_could_be_a_shell_command_is_refused_rather_than_quoted() {
214 for bad in ["v1; rm -rf /", "$(id)", "`id`", "v1 --no-sudo", ""] {
215 let e = parse(&["--version", bad]).unwrap_err();
218 assert!(e.contains("is not a release tag"), "{bad:?}: {e}");
219 assert!(tag(bad).is_err(), "{bad:?} passed the charset check");
220 }
221 assert!(tag("v0.1.0-rc.1").is_ok(), "a real tag was refused");
222 let e = parse(&["--version"]).unwrap_err();
223 assert!(e.contains("a value is required"), "{e}");
224 }
225
226 #[test]
227 fn an_installer_flag_this_command_does_not_document_is_refused() {
228 let e = parse(&["--no-sudo"]).unwrap_err();
229 assert!(e.contains("--no-sudo"), "{e}");
230 assert!(e.contains("Usage: update"), "the usage is part of it: {e}");
231 }
232
233 #[test]
234 fn the_downloader_is_chosen_by_the_shell_and_not_assumed() {
235 let line = command(None);
236 assert!(line.contains("command -v curl"), "{line}");
237 assert!(line.contains("command -v wget"), "{line}");
238 assert!(line.contains("needs curl or wget"), "{line}");
239 }
240
241 #[test]
242 fn the_install_directory_is_this_binarys_own() {
243 let exe = std::env::current_exe().unwrap();
244 assert_eq!(
245 install_dir(Some(&exe)).unwrap(),
246 std::fs::canonicalize(&exe).unwrap().parent().unwrap()
247 );
248 assert_eq!(install_dir(None), None);
249 assert_eq!(install_dir(Some(Path::new("/no/such/mira"))), None);
250 }
251
252 #[test]
253 fn dry_run_prints_the_command_instead_of_running_it() {
254 run(&parse(&["--dry-run", "--version", "v9.9.9"]).unwrap()).unwrap();
255 assert!(parse(&["--help"]).is_err(), "--help produced matches");
259 assert!(parse(&["--nope"]).is_err());
260 }
261
262 #[test]
265 fn the_child_is_the_installer_pointed_at_this_binarys_directory() {
266 let line = command(None);
267 let cmd = installer(&line);
268 assert_eq!(cmd.get_program(), "bash");
269 let argv: Vec<_> = cmd.get_args().collect();
270 assert_eq!(argv, ["-c", line.as_str()]);
271 let dir = cmd
274 .get_envs()
275 .find(|(k, _)| *k == "MIRA_INSTALL_DIR")
276 .and_then(|(_, v)| v)
277 .expect("an install directory");
278 let exe = std::env::current_exe().unwrap();
279 assert_eq!(Path::new(dir), install_dir(Some(&exe)).unwrap());
280 }
281
282 #[test]
283 fn a_failed_installer_is_a_failed_update() {
284 spawn(&mut std::process::Command::new("true")).unwrap();
285
286 let e = spawn(&mut std::process::Command::new("false")).unwrap_err();
287 assert!(e.starts_with("installer exited with"), "{e}");
288
289 let e = spawn(&mut std::process::Command::new("/no/such/installer")).unwrap_err();
290 assert!(e.starts_with("`/no/such/installer` is not on PATH"), "{e}");
291 }
292
293 #[test]
296 fn no_shell_says_so_and_says_what_to_do_instead() {
297 let e = start_failed("bash", &std::io::ErrorKind::NotFound.into());
298 assert!(e.starts_with("`bash` is not on PATH"), "{e}");
299 assert!(e.contains("pulling a newer image tag"), "{e}");
300 assert!(e.contains(RELEASES), "{e}");
301
302 let e = start_failed("bash", &std::io::ErrorKind::PermissionDenied.into());
305 assert!(e.starts_with("could not run the installer:"), "{e}");
306 }
307
308 #[test]
312 fn the_help_names_what_it_needs_on_the_host() {
313 let help = cli().render_long_help().to_string();
314 assert!(
315 help.contains("Needs bash and either curl or wget"),
316 "{help}"
317 );
318 }
319}