diff --git a/README.md b/README.md index d1f4b9290..b6fd94b8c 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ reims-ctl set mac --memory 12G --resolution host # applies at the next start reims-ctl command mac # the QEMU command it runs, as a shell script reims-ctl report mac # logs, settings and the host's details, zipped, for a bug report reims-ctl update # pull the checkout and install again +reims-ctl update --channel development # switch to the development branch first (stable is master) ``` `reims-ctl help` lists every command; every option takes `--name value` or `--name=value`. A running diff --git a/crates/reims-ctl/src/cli.rs b/crates/reims-ctl/src/cli.rs index 812fca48e..c995c3fc7 100644 --- a/crates/reims-ctl/src/cli.rs +++ b/crates/reims-ctl/src/cli.rs @@ -89,7 +89,11 @@ pub enum Cmd { /// Zip a VM's logs, settings and the host's details into Downloads, for a bug report Report { name: String }, /// Update reims-ctl and its QEMU from the checkout it was installed from - Update, + Update { + /// Switch the checkout to this channel first; later updates stay on it + #[arg(long, value_enum)] + channel: Option, + }, /// Check the host and the install Doctor, /// The interactive interface (what reims-ctl runs with no command) @@ -394,7 +398,7 @@ pub fn main(cli: Cli) -> Result { ); } } - Cmd::Update => update::update()?, + Cmd::Update { channel } => update::update(channel)?, Cmd::Doctor => return doctor(host), Cmd::Tui => unreachable!(), Cmd::VulkanProbe => return Ok(gpu::probe_main()), @@ -975,7 +979,12 @@ fn doctor(host: Host) -> Result { Some(i) => line( true, "checkout", - format!("{} at {}", i.repo.display(), i.commit), + format!( + "{} at {}, following {}", + i.repo.display(), + i.commit, + update::following(&i.repo) + ), ), None => line( false, diff --git a/crates/reims-ctl/src/tui.rs b/crates/reims-ctl/src/tui.rs index e28d9146d..72225662b 100644 --- a/crates/reims-ctl/src/tui.rs +++ b/crates/reims-ctl/src/tui.rs @@ -10,6 +10,7 @@ use crate::create::{self, DiskSource, ImportMode, Spec}; use crate::form::{self, Field, Form, opts}; use crate::gpu::GpuInfo; use crate::host::{Host, Os, Profile}; +use crate::update::Channel; use crate::vm::{Registry, Vm, format_mib, parse_size_mib}; use crate::{install, logs, paths, runtime, update}; use anyhow::{Context, Result, bail}; @@ -33,15 +34,15 @@ pub fn run() -> Result<()> { ratatui::restore(); result?; if app.update_requested { - return run_update(); + return run_update(app.update_channel); } Ok(()) } /// Runs the update in the plain terminal, then the new reims-ctl in this process's place. -fn run_update() -> Result<()> { +fn run_update(channel: Option) -> Result<()> { println!("Updating reims-ctl and its QEMU…\n"); - update::update()?; + update::update(channel)?; println!("\nUpdated. Starting the new reims-ctl…"); use std::os::unix::process::CommandExt; let exe = std::env::current_exe()?; @@ -97,7 +98,7 @@ enum Action { None, Delete { vm: String, keep_files: bool }, ForceStop(String), - Update, + Update(Option), Quit, } @@ -124,6 +125,7 @@ struct App { last_registry: Instant, quit: bool, update_requested: bool, + update_channel: Option, pending_select: Option, } @@ -153,6 +155,7 @@ impl App { last_registry: Instant::now(), quit: false, update_requested: false, + update_channel: None, pending_select: None, }; app.reload()?; @@ -510,8 +513,9 @@ impl App { match a { Action::None => {} Action::Quit => self.quit = true, - Action::Update => { + Action::Update(channel) => { self.update_requested = true; + self.update_channel = channel; self.quit = true; } Action::Delete { vm, keep_files } => match delete_vm(&vm, keep_files) { @@ -645,14 +649,27 @@ impl App { } else { String::new() }; + let current = update::current_branch(&i.repo) + .as_deref() + .and_then(Channel::of); + let mut options = vec![("Cancel", Action::None), ("Update", Action::Update(None))]; + for c in Channel::ALL.into_iter().filter(|&c| Some(c) != current) { + let label = match c { + Channel::Stable => "Switch to stable", + Channel::Development => "Switch to development", + }; + options.push((label, Action::Update(Some(c)))); + } self.overlay = Some(Overlay::Confirm { title: "Update reims-ctl?".into(), body: format!( - "This pulls {} and rebuilds reims-ctl, the library and QEMU (a few minutes; the build's output shows here), \ - then restarts reims-ctl.{note}", - paths::tilde(&i.repo) + "This pulls {}, which follows {}, and rebuilds reims-ctl, the library and QEMU (a few minutes; the build's \ + output shows here), then restarts reims-ctl.\n\nA switch checks out that channel's branch first, and \ + later updates stay on it: stable is master, and development gets changes first.{note}", + paths::tilde(&i.repo), + update::following(&i.repo) ), - options: vec![("Cancel", Action::None), ("Update", Action::Update)], + options, choice: 1, }); } diff --git a/crates/reims-ctl/src/update.rs b/crates/reims-ctl/src/update.rs index 28e49406e..3c2adae2a 100644 --- a/crates/reims-ctl/src/update.rs +++ b/crates/reims-ctl/src/update.rs @@ -1,16 +1,75 @@ //! Self-update: the checkout reims-ctl was installed from pulls, and scripts/install-ctl.sh //! builds and installs the new reims-ctl and QEMU. The new QEMU goes beside the old one, so //! running VMs keep theirs; the new reims-ctl replaces this binary, so restart it afterwards. +//! +//! The checkout's branch is the channel an update follows: master is stable, and development +//! gets changes first. Choosing a channel checks its branch out before the script runs, so the +//! script that builds is that branch's own, and later updates stay on it. use crate::install::Install; +use crate::paths; use anyhow::{Context, Result, bail}; +use std::path::Path; use std::process::Command; -pub fn update() -> Result<()> { +/// The branches an update can follow. +#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] +pub enum Channel { + /// The master branch + Stable, + /// The development branch, which gets changes before stable + Development, +} + +impl Channel { + pub const ALL: [Channel; 2] = [Channel::Stable, Channel::Development]; + + pub fn name(self) -> &'static str { + match self { + Channel::Stable => "stable", + Channel::Development => "development", + } + } + + pub fn branch(self) -> &'static str { + match self { + Channel::Stable => "master", + Channel::Development => "development", + } + } + + /// The channel that follows `branch`, if one does. + pub fn of(branch: &str) -> Option { + Channel::ALL.into_iter().find(|c| c.branch() == branch) + } +} + +/// The branch checked out in `repo`; None on a detached HEAD. +pub fn current_branch(repo: &Path) -> Option { + git_output(repo, &["symbolic-ref", "--short", "-q", "HEAD"]) +} + +/// What an update of `repo` follows, for people: "the stable channel (master)", "the branch +/// NAME", or "a detached HEAD". +pub fn following(repo: &Path) -> String { + match current_branch(repo) { + Some(b) => match Channel::of(&b) { + Some(c) => format!("the {} channel ({b})", c.name()), + None => format!("the branch {b}"), + }, + None => "a detached HEAD".into(), + } +} + +/// Updates from the checkout, first switching it to `channel`'s branch where one is given. +pub fn update(channel: Option) -> Result<()> { let i = Install::load().context( "no install record: run scripts/install-ctl.sh in your reims-vgpu checkout once, and \ reims-ctl update can use it from then on", )?; + if let Some(c) = channel { + switch(&i.repo, c)?; + } let script = i.repo.join("scripts/install-ctl.sh"); if !script.is_file() { bail!("{} is missing: was the checkout moved?", script.display()); @@ -26,3 +85,156 @@ pub fn update() -> Result<()> { } Ok(()) } + +/// Checks out `c`'s branch in `repo`, fetched from the remote the current branch tracks (origin +/// where it tracks none). A branch the checkout lacks is made tracking the remote's, and one +/// that tracks nothing is set to track it, so the script's pull moves it on. git tracks only a +/// branch the remote's fetch refspecs cover, which a single-branch clone's do not: the branch is +/// added to them there. +fn switch(repo: &Path, c: Channel) -> Result<()> { + let branch = c.branch(); + if !repo.join(".git").exists() { + bail!("{} is not a git checkout: was it moved?", repo.display()); + } + let current = current_branch(repo); + if current.as_deref() == Some(branch) { + return Ok(()); + } + let remote = current + .and_then(|b| git_output(repo, &["config", &format!("branch.{b}.remote")])) + .filter(|r| r != ".") + .unwrap_or_else(|| "origin".into()); + let upstream = format!("{remote}/{branch}"); + println!( + "Switching {} to the {} channel ({branch})", + paths::tilde(repo), + c.name() + ); + let src = format!("refs/heads/{branch}"); + let covered = git_output( + repo, + &["config", "--get-all", &format!("remote.{remote}.fetch")], + ) + .unwrap_or_default() + .lines() + .filter_map(|r| r.trim_start_matches('+').split_once(':')) + .any(|(from, _)| from == "refs/heads/*" || from == src); + if !covered { + git(repo, &["remote", "set-branches", "--add", &remote, branch])?; + } + git( + repo, + &["fetch", &remote, &format!("+{src}:refs/remotes/{upstream}")], + ) + .with_context(|| format!("fetch {branch} from {remote}"))?; + let have = git_output(repo, &["rev-parse", "--verify", "-q", &src]); + if have.is_none() { + git(repo, &["switch", "--track", "-c", branch, &upstream]) + } else { + git(repo, &["switch", branch]) + } + .with_context(|| { + format!( + "switch {} to {branch}: commit or set aside its local changes, then update again", + paths::tilde(repo) + ) + })?; + if git_output(repo, &["config", &format!("branch.{branch}.remote")]).is_none() { + git(repo, &["branch", "--set-upstream-to", &upstream, branch])?; + } + Ok(()) +} + +fn git(repo: &Path, args: &[&str]) -> Result<()> { + let status = Command::new("git") + .arg("-C") + .arg(repo) + .args(args) + .status() + .context("run git")?; + if !status.success() { + bail!("git {} failed", args.join(" ")); + } + Ok(()) +} + +/// `git args`' output, trimmed; None where it fails or prints nothing. +fn git_output(repo: &Path, args: &[&str]) -> Option { + let o = Command::new("git") + .arg("-C") + .arg(repo) + .args(args) + .output() + .ok()?; + let out = String::from_utf8_lossy(&o.stdout).trim().to_string(); + (o.status.success() && !out.is_empty()).then_some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(dir: &Path, args: &[&str]) { + let ok = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_NOSYSTEM", "1") + .output() + .unwrap() + .status + .success(); + assert!(ok, "git {}", args.join(" ")); + } + + #[test] + fn channels_follow_their_branches() { + assert_eq!(Channel::of("master"), Some(Channel::Stable)); + assert_eq!(Channel::of("development"), Some(Channel::Development)); + assert_eq!(Channel::of("steelbrain/feature"), None); + } + + #[test] + fn switching_fetches_and_tracks_the_channels_branch() { + let d = std::env::temp_dir().join(format!("reims-ctl-channel-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + let (origin, clone) = (d.join("origin"), d.join("clone")); + std::fs::create_dir_all(&origin).unwrap(); + run(&origin, &["init", "-q", "-b", "master"]); + run(&origin, &["config", "user.name", "t"]); + run(&origin, &["config", "user.email", "t@t"]); + run(&origin, &["commit", "-q", "--allow-empty", "-m", "stable"]); + run(&origin, &["switch", "-q", "-c", "development"]); + run( + &origin, + &["commit", "-q", "--allow-empty", "-m", "development"], + ); + run(&origin, &["switch", "-q", "master"]); + // A single-branch clone, whose fetches keep only master. + run( + &d, + &[ + "clone", + "-q", + "--single-branch", + "-b", + "master", + origin.to_str().unwrap(), + "clone", + ], + ); + + switch(&clone, Channel::Development).unwrap(); + assert_eq!(current_branch(&clone).as_deref(), Some("development")); + assert_eq!( + git_output(&clone, &["rev-parse", "--abbrev-ref", "@{u}"]).as_deref(), + Some("origin/development") + ); + assert_eq!(following(&clone), "the development channel (development)"); + + switch(&clone, Channel::Stable).unwrap(); + assert_eq!(following(&clone), "the stable channel (master)"); + let _ = std::fs::remove_dir_all(&d); + } +}