use std::ffi::{OsStr, OsString};
use std::fmt;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
use mrk::sanitize;
use crate::cli::signals::{self, Held};
use crate::version;
pub const REPO: &str = "https://github.com/vmeyet/mrk-cli";
const BINARY: &str = "mrk";
const FORMULA: &str = "vmeyet/tap/mrk";
const PEELED_SUFFIX: &str = "^{}";
const CARGO_INSTALLS: &str = ".crates.toml";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decision {
Install,
UpToDate,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version {
major: u64,
minor: u64,
patch: u64,
}
impl Version {
fn parse(text: &str) -> Option<Self> {
let mut parts = text.split('.').map(number);
let version = Self { major: parts.next()??, minor: parts.next()??, patch: parts.next()?? };
parts.next().is_none().then_some(version)
}
fn running() -> Result<Self> {
Self::parse(env!("CARGO_PKG_VERSION")).context("the running version is not a release number")
}
fn tag(self) -> String {
format!("v{self}")
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
fn number(part: &str) -> Option<u64> {
part.bytes().all(|byte| byte.is_ascii_digit()).then(|| part.parse().ok()).flatten()
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Release {
version: Version,
commit: String,
}
struct Tag<'a> {
version: Version,
id: &'a str,
is_peeled: bool,
}
impl Release {
fn label(&self) -> String {
format!("{} ({})", self.version, version::short(&self.commit))
}
}
fn tag(line: &str) -> Option<Tag<'_>> {
let (id, name) = line.split_once("\trefs/tags/v")?;
let (name, is_peeled) = name.strip_suffix(PEELED_SUFFIX).map_or((name, false), |name| (name, true));
let version = Version::parse(name)?;
is_object_id(id).then_some(Tag { version, id, is_peeled })
}
fn is_object_id(text: &str) -> bool {
matches!(text.len(), 40 | 64) && text.bytes().all(|byte| byte.is_ascii_hexdigit())
}
fn newest_release(listing: &str) -> Option<Release> {
let newest = listing.lines().filter_map(tag).max_by_key(|tag| (tag.version, tag.is_peeled))?;
Some(Release { version: newest.version, commit: newest.id.to_owned() })
}
pub fn decide(installed: Version, latest: Version, force: bool) -> Decision {
if force || latest > installed { Decision::Install } else { Decision::UpToDate }
}
fn stdout_of(mut command: Command) -> Result<String> {
let words: Vec<_> = std::iter::once(command.get_program()).chain(command.get_args()).map(|word| word.to_string_lossy()).collect();
let line = words.join(" ");
let output = command.output().with_context(|| format!("running {line}"))?;
if !output.status.success() {
bail!("{line}: {}", String::from_utf8_lossy(&output.stderr).trim());
}
Ok(String::from_utf8(output.stdout)?.trim().to_owned())
}
fn latest() -> Result<Release> {
let mut git = Command::new("git");
git.args(["ls-remote", "--tags", REPO]).env("GIT_TERMINAL_PROMPT", "0");
newest_release(&stdout_of(git)?).with_context(|| format!("{REPO} has no release tag"))
}
fn is_brew_path(exe: &Path) -> bool {
exe.components().any(|part| part.as_os_str() == "Cellar")
}
fn installed_by_brew() -> bool {
std::env::current_exe().and_then(std::fs::canonicalize).is_ok_and(|exe| is_brew_path(&exe))
}
fn brew_lists(listing: &str, release: Version) -> bool {
let versions = listing.split_whitespace().skip(1).map(|installed| installed.split_once('_').map_or(installed, |(version, _)| version));
versions.filter_map(Version::parse).any(|installed| installed == release)
}
fn run_brew(arguments: &[&str]) -> Result<()> {
let line = arguments.join(" ");
println!("→ brew {line}…");
let status = Command::new("brew").args(arguments).status().with_context(|| format!("running brew {line}"))?;
if !status.success() {
bail!("brew {line} failed");
}
Ok(())
}
fn install_with_brew(release: &Release, force: bool) -> Result<()> {
if std::env::var_os("HOMEBREW_NO_AUTO_UPDATE").is_some_and(|value| !value.is_empty()) {
println!("→ HOMEBREW_NO_AUTO_UPDATE is set: brew reads the tap as it last fetched it, which may miss the release");
} else {
run_brew(&["update"])?;
}
run_brew(&[if force { "reinstall" } else { "upgrade" }, FORMULA])?;
let mut list = Command::new("brew");
list.args(["list", "--versions", FORMULA]);
let listing = stdout_of(list)?;
if !brew_lists(&listing, release.version) {
bail!(
"brew installed {listing}, not {}: the tap's formula has not caught up with the release yet, try again later",
release.version.tag()
);
}
check_install(release, &brew_binary()?)
}
fn brew_binary() -> Result<PathBuf> {
let mut prefix = Command::new("brew");
prefix.args(["--prefix", FORMULA]);
Ok(PathBuf::from(stdout_of(prefix)?).join("bin").join(BINARY))
}
fn install_with_cargo(release: &Release) -> Result<()> {
println!("→ installing mrk {} from {REPO}…", release.label());
let root = install_root().context("finding where to install mrk")?;
check_writable(&root)?;
let held = Held::hold(signals::ending_not_ignored()).context("holding the ending signals during the build")?;
let build = tempfile::Builder::new().prefix("mrk-update-").tempdir().context("creating a build folder")?;
let mut cargo = Command::new("cargo");
cargo
.args(["install", "--git", REPO, "--rev", &release.commit, "--force", "--locked", "--root"])
.arg(&root)
.arg("--target-dir")
.arg(build.path());
let mut cargo = signals::spawn_alone(&mut cargo).context("running cargo install")?;
let status = match signals::wait_ending(&mut cargo, &held).context("waiting for cargo install")? {
Ok(status) => status,
Err(interrupted) => {
let _ = writeln!(io::stdout(), "→ stopped: nothing was installed, the build folder is removed");
return Err(interrupted.into());
}
};
if !status.success() {
bail!("cargo install failed");
}
check_install(release, &root.join("bin").join(BINARY))
}
fn install_root() -> Option<PathBuf> {
let running = std::env::current_exe().and_then(std::fs::canonicalize).ok();
running
.as_deref()
.and_then(root_of)
.or_else(|| cargo_root(std::env::var_os("CARGO_INSTALL_ROOT"), std::env::var_os("CARGO_HOME"), std::env::home_dir()))
}
fn root_of(binary: &Path) -> Option<PathBuf> {
let folder = binary.parent()?;
if folder.file_name()? != "bin" {
return None;
}
let root = folder.parent()?;
root.join(CARGO_INSTALLS).is_file().then(|| root.to_path_buf())
}
fn check_writable(root: &Path) -> Result<()> {
let existing = root.ancestors().find(|folder| folder.is_dir()).unwrap_or(root);
tempfile::tempfile_in(existing)
.map(drop)
.with_context(|| format!("cannot install under {}", sanitize::text(&existing.display().to_string())))
}
fn check_install(release: &Release, installed: &Path) -> Result<()> {
let mut ask = Command::new(installed);
ask.arg("--version");
let label = stdout_of(ask)?;
if !reports(&label, release) {
bail!("{} reports {label}, not {}", sanitize::text(&installed.display().to_string()), release.label());
}
match on_path(&std::env::var_os("PATH").unwrap_or_default()) {
Some(found) if is_same_file(&found, installed) => {}
Some(found) => {
println!(
"! `mrk` runs {}, not the one installed: put {} first in PATH",
sanitize::text(&found.display().to_string()),
parent(installed)
);
}
None => println!("! {} is not in PATH", parent(installed)),
}
Ok(())
}
fn cargo_root(install_root: Option<OsString>, cargo_home: Option<OsString>, home: Option<PathBuf>) -> Option<PathBuf> {
install_root.or(cargo_home).map(PathBuf::from).or_else(|| home.filter(|home| home.is_absolute()).map(|home| home.join(".cargo")))
}
fn on_path(path: &OsStr) -> Option<PathBuf> {
std::env::split_paths(path).map(|folder| folder.join(BINARY)).find(|candidate| candidate.is_file())
}
fn is_same_file(one: &Path, other: &Path) -> bool {
matches!((std::fs::canonicalize(one), std::fs::canonicalize(other)), (Ok(one), Ok(other)) if one == other)
}
fn parent(binary: &Path) -> String {
sanitize::text(&binary.parent().unwrap_or(binary).display().to_string())
}
fn reports(label: &str, release: &Release) -> bool {
label == format!("{BINARY} {}", release.label())
}
fn install(release: &Release, force: bool) -> Result<()> {
if installed_by_brew() { install_with_brew(release, force) } else { install_with_cargo(release) }
}
pub fn run(force: bool) -> Result<()> {
let latest = latest().context("could not check the latest release")?;
match decide(Version::running()?, latest.version, force) {
Decision::UpToDate => println!("✓ already up to date ({})", version::label()),
Decision::Install => {
install(&latest, force)?;
println!("✓ installed mrk {}, run `mrk --version` to see it", latest.version.tag());
}
}
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
const TAG_OBJECT: &str = "1111111111111111111111111111111111111111";
const COMMIT: &str = "2222222222222222222222222222222222222222";
const OLD_COMMIT: &str = "3333333333333333333333333333333333333333";
fn version(text: &str) -> Version {
Version::parse(text).unwrap()
}
fn release(text: &str, commit: &str) -> Release {
Release { version: version(text), commit: commit.to_owned() }
}
#[test]
fn a_binary_in_the_brew_cellar_is_a_brew_install() {
assert!(is_brew_path(Path::new("/opt/homebrew/Cellar/mrk/0.3.0/bin/mrk")));
}
#[test]
fn a_binary_installed_by_cargo_is_not_a_brew_install() {
assert!(!is_brew_path(Path::new("/Users/me/.cargo/bin/mrk")));
}
#[test]
fn brew_has_the_release_when_it_lists_it_whatever_the_formula_revision() {
assert!(brew_lists("mrk 0.7.0", version("0.7.0")));
assert!(brew_lists("mrk 0.6.0 0.7.0_1", version("0.7.0")));
}
#[test]
fn brew_lacks_the_release_when_the_tap_has_not_caught_up() {
assert!(!brew_lists("mrk 0.6.0", version("0.7.0")));
assert!(!brew_lists("", version("0.7.0")));
}
#[test]
fn the_same_release_needs_no_install() {
assert_eq!(decide(version("0.2.0"), version("0.2.0"), false), Decision::UpToDate);
}
#[test]
fn an_older_release_needs_no_install() {
assert_eq!(decide(version("0.3.0"), version("0.2.9"), false), Decision::UpToDate);
}
#[test]
fn a_newer_release_installs() {
assert_eq!(decide(version("0.2.0"), version("0.10.0"), false), Decision::Install);
}
#[test]
fn force_installs_over_the_same_release() {
assert_eq!(decide(version("0.2.0"), version("0.2.0"), true), Decision::Install);
}
#[test]
fn versions_parse_only_plain_release_numbers() {
assert_eq!(version("1.22.3").to_string(), "1.22.3");
for text in ["1.2", "1.2.3.4", "1.2.3-rc.1", "1.2.3+build", "1.+2.3", "v1.2.3", "1.x.3", ""] {
assert_eq!(Version::parse(text), None, "{text}");
}
}
#[test]
fn the_running_version_is_a_release() {
assert_eq!(Version::running().unwrap().to_string(), env!("CARGO_PKG_VERSION"));
}
#[test]
fn a_release_is_tagged_with_a_v() {
assert_eq!(version("0.2.0").tag(), "v0.2.0");
}
#[test]
fn the_newest_release_wins_by_number_not_by_listing_order() {
let listing = format!(
"{OLD_COMMIT}\trefs/tags/v0.10.0\n{COMMIT}\trefs/tags/v0.9.1\n{COMMIT}\trefs/tags/v1.0.0-rc.1\n{COMMIT}\trefs/tags/nightly\n{COMMIT}\trefs/tags/v0.2.0"
);
assert_eq!(newest_release(&listing), Some(release("0.10.0", OLD_COMMIT)));
}
#[test]
fn an_annotated_tag_installs_the_commit_it_points_at() {
let listing = format!("{TAG_OBJECT}\trefs/tags/v0.7.0\n{COMMIT}\trefs/tags/v0.7.0^{{}}\n{OLD_COMMIT}\trefs/tags/v0.6.0");
assert_eq!(newest_release(&listing), Some(release("0.7.0", COMMIT)));
}
#[test]
fn a_tag_without_a_full_object_id_is_ignored() {
let listing = format!("--upload-pack=x\trefs/tags/v9.0.0\nabcd\trefs/tags/v8.0.0\n{COMMIT}\trefs/tags/v0.7.0");
assert_eq!(newest_release(&listing), Some(release("0.7.0", COMMIT)));
}
#[test]
fn a_repo_without_release_tags_has_no_newest_release() {
assert_eq!(newest_release(""), None);
assert_eq!(newest_release(&format!("{COMMIT}\trefs/tags/nightly")), None);
}
#[test]
fn cargo_installs_under_its_install_root_then_its_home_then_dot_cargo() {
let home = Some(PathBuf::from("/Users/nina"));
assert_eq!(cargo_root(Some("/opt/root".into()), Some("/opt/cargo".into()), home.clone()), Some(PathBuf::from("/opt/root")));
assert_eq!(cargo_root(None, Some("/opt/cargo".into()), home.clone()), Some(PathBuf::from("/opt/cargo")));
assert_eq!(cargo_root(None, None, home), Some(PathBuf::from("/Users/nina/.cargo")));
assert_eq!(cargo_root(None, None, None), None);
}
fn installed_under(root: &Path, folder: &str) -> PathBuf {
let binary = root.join(folder).join(BINARY);
std::fs::create_dir_all(binary.parent().unwrap()).unwrap();
std::fs::write(&binary, b"").unwrap();
binary
}
#[test]
fn the_update_installs_where_cargo_installed_the_running_binary() {
let root = tempfile::tempdir().unwrap();
std::fs::write(root.path().join(CARGO_INSTALLS), b"").unwrap();
assert_eq!(root_of(&installed_under(root.path(), "bin")), Some(root.path().to_path_buf()));
assert_eq!(root_of(&installed_under(root.path(), "target/release")), None);
}
#[test]
fn a_bin_folder_cargo_does_not_manage_is_not_an_install_root() {
let home = tempfile::tempdir().unwrap();
assert_eq!(root_of(&installed_under(home.path(), "bin")), None);
}
#[test]
fn cargo_never_installs_under_a_relative_home() {
for home in [PathBuf::new(), PathBuf::from("nina")] {
assert_eq!(cargo_root(None, None, Some(home.clone())), None, "{home:?}");
}
}
#[test]
fn an_install_root_is_writable_when_its_nearest_existing_folder_is() {
let root = tempfile::tempdir().unwrap();
assert!(check_writable(&root.path().join("not/yet")).is_ok());
}
#[test]
fn a_read_only_install_root_is_refused_before_building() {
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir().unwrap();
std::fs::set_permissions(root.path(), std::fs::Permissions::from_mode(0o555)).unwrap();
let checked = check_writable(root.path());
std::fs::set_permissions(root.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(checked.is_err());
}
fn reporting(label: &str) -> (tempfile::TempDir, PathBuf) {
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir().unwrap();
let binary = installed_under(root.path(), "bin");
std::fs::write(&binary, format!("#!/bin/sh\necho '{label}'\n")).unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
(root, binary)
}
#[test]
fn an_install_is_checked_by_running_the_installed_binary() {
let installing = release("0.7.0", COMMIT);
let (_root, right) = reporting("mrk 0.7.0 (2222222)");
let (_other, stale) = reporting("mrk 0.6.0 (3333333)");
assert!(check_install(&installing, &right).is_ok());
assert!(check_install(&installing, &stale).is_err());
}
#[test]
fn the_first_mrk_in_path_is_the_one_a_shell_runs() {
let root = tempfile::tempdir().unwrap();
let folders = ["empty", "first", "second"].map(|name| root.path().join(name));
for folder in &folders {
std::fs::create_dir_all(folder).unwrap();
}
for folder in &folders[1..] {
std::fs::write(folder.join(BINARY), b"").unwrap();
}
let path = std::env::join_paths(&folders).unwrap();
assert_eq!(on_path(&path), Some(folders[1].join(BINARY)));
assert_eq!(on_path(&std::env::join_paths(&folders[..1]).unwrap()), None);
}
#[test]
fn the_installed_binary_must_report_the_release_and_its_commit() {
let installing = release("0.7.0", COMMIT);
assert!(reports("mrk 0.7.0 (2222222)", &installing));
assert!(!reports("mrk 0.7.0 (unknown)", &installing));
assert!(!reports("mrk 0.6.0 (2222222)", &installing));
}
}