//! A session's work, moved between machines with it (DESIGN.md, decision 21). //! //! A session handed from a workstation to the hub's runner takes its //! checkout's work along as a branch, `session/`; handed back, it brings //! the runner's work back the same way. Nothing here touches the checkout it //! reads from, except `bring_back` when the checkout is still exactly as it //! was left: //! //! * `snapshot` makes the working tree — changes, new files, deletions; not //! what `.gitignore` leaves out — a commit on top of HEAD through an index of //! its own, so the checkout's index, HEAD and files stay as they are. When the //! branch has work already (a session that went and came back before), that //! is a second parent, so the push is never a force. //! * `bring_back` puts the branch's tip in the working tree as uncommitted //! changes on the same HEAD — as the work was when it left — but only when //! the checkout has not changed since; otherwise it says so and leaves it. use std::path::{Path, PathBuf}; use std::process::Command; use anyhow::{bail, Context, Result}; /// git in `dir`, with `index` as its index when given. fn git(dir: &Path, index: Option<&Path>, args: &[&str]) -> Result { let mut c = Command::new("git"); c.arg("-C").arg(dir).args(args); if let Some(i) = index { c.env("GIT_INDEX_FILE", i); } let out = c.output().with_context(|| format!("running git {}", args.join(" ")))?; if !out.status.success() { bail!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim()); } Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) } /// The checkout's top directory. pub fn top(dir: &Path) -> Result { Ok(PathBuf::from(git(dir, None, &["rev-parse", "--show-toplevel"])?)) } /// The working tree as a tree object, written through a throwaway index. fn tree_of(top: &Path) -> Result { let index = std::env::temp_dir().join(format!("midas-index-{}-{}", std::process::id(), crate::mirror::random_hex(4)?)); let r = (|| { git(top, Some(&index), &["read-tree", "HEAD"])?; git(top, Some(&index), &["add", "-A"])?; git(top, Some(&index), &["write-tree"]) })(); let _ = std::fs::remove_file(&index); r } /// The branch's tip at `origin`, fetched; `None` when it has none yet. pub fn fetch(top: &Path, branch: &str) -> Option { git(top, None, &["fetch", "-q", "origin", &format!("+refs/heads/{branch}:refs/remotes/origin/{branch}")]).ok()?; git(top, None, &["rev-parse", &format!("refs/remotes/origin/{branch}")]).ok() } /// What `snapshot` made. #[derive(Debug, PartialEq)] pub struct Snapshot { pub sha: String, /// Something was not committed: the snapshot is a commit of its own. pub uncommitted: bool, } /// The checkout's working tree as a commit on HEAD (and on `branch`'s tip, if /// it has work HEAD has not), pushed to `origin` as `branch`. The checkout is /// left as it was. pub fn snapshot(dir: &Path, branch: &str, message: &str) -> Result { let top = top(dir)?; let head = git(&top, None, &["rev-parse", "HEAD"])?; let tree = tree_of(&top)?; let mut parents = vec![head.clone()]; if let Some(tip) = fetch(&top, branch) { let had = git(&top, None, &["merge-base", "--is-ancestor", &tip, &head]).is_ok(); if !had { parents.push(tip); } } let uncommitted = tree != git(&top, None, &["rev-parse", "HEAD^{tree}"])?; let sha = if uncommitted || parents.len() > 1 { let mut args = vec!["commit-tree", tree.as_str(), "-m", message]; for p in &parents { args.extend(["-p", p.as_str()]); } git(&top, None, &args)? } else { head }; git(&top, None, &["push", "-q", "origin", &format!("{sha}:refs/heads/{branch}")])?; Ok(Snapshot { sha, uncommitted }) } /// What `bring_back` did with the checkout. #[derive(Debug, PartialEq)] pub enum Back { /// Its working tree is the branch's tip now, on the HEAD it had. Restored, /// It has that already. Already, /// It changed since the work left (or its HEAD moved): left alone. Diverged, } /// Bring `branch`'s work (fetched from `origin`) into the checkout, which /// sent it as `left` (its snapshot): only when the checkout is still as it /// was then, so nothing made here meanwhile is written over. pub fn bring_back(dir: &Path, branch: &str, left: &str) -> Result<(Back, String)> { let top = top(dir)?; let tip = fetch(&top, branch).with_context(|| format!("origin has no {branch}"))?; let now = tree_of(&top)?; if now == git(&top, None, &["rev-parse", &format!("{tip}^{{tree}}")])? { return Ok((Back::Already, tip)); } // Left as a commit of its own (first parent the HEAD it was on), or as HEAD itself. let head = git(&top, None, &["rev-parse", "HEAD"])?; let base = if left == head { head.clone() } else { git(&top, None, &["rev-parse", &format!("{left}^1")]).unwrap_or_default() }; let same = base == head && now == git(&top, None, &["rev-parse", &format!("{left}^{{tree}}")])?; if !same { return Ok((Back::Diverged, tip)); } git(&top, None, &["restore", &format!("--source={tip}"), "--worktree", "--", "."])?; Ok((Back::Restored, tip)) } #[cfg(test)] mod tests { use super::*; fn sh(dir: &Path, args: &[&str]) -> String { let out = Command::new("git").arg("-C").arg(dir).args(["-c", "user.name=t", "-c", "user.email=t@t"]).args(args).output().unwrap(); assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr)); String::from_utf8_lossy(&out.stdout).trim().to_string() } #[test] fn work_goes_as_a_branch_and_comes_back_into_a_checkout_left_as_it_was() { let root = std::env::temp_dir().join(format!("midas-handoff-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); let (origin, here, there) = (root.join("origin.git"), root.join("here"), root.join("there")); std::fs::create_dir_all(&root).unwrap(); sh(&root, &["init", "-q", "--bare", origin.to_str().unwrap()]); sh(&root, &["clone", "-q", origin.to_str().unwrap(), here.to_str().unwrap()]); std::fs::write(here.join("a"), "a\n").unwrap(); std::fs::write(here.join("b"), "b\n").unwrap(); sh(&here, &["add", "."]); sh(&here, &["commit", "-qm", "base"]); sh(&here, &["push", "-q", "origin", "HEAD"]); let head = sh(&here, &["rev-parse", "HEAD"]); // Uncommitted work here: a change and a new file. It goes; the checkout stays as it is. std::fs::write(here.join("a"), "a2\n").unwrap(); std::fs::write(here.join("new"), "n\n").unwrap(); sh(&here, &["config", "user.name", "t"]); sh(&here, &["config", "user.email", "t@t"]); let left = snapshot(&here, "session/s1", "wip: from here").unwrap(); assert!(left.uncommitted); assert_eq!(sh(&here, &["rev-parse", "HEAD"]), head, "HEAD unmoved"); assert_eq!(sh(&here, &["status", "--short"]), "M a\n?? new", "the checkout as it was"); // The runner goes on with it there: a change, a deletion, a new file, committed. sh(&root, &["clone", "-q", "-b", "session/s1", origin.to_str().unwrap(), there.to_str().unwrap()]); assert_eq!(std::fs::read_to_string(there.join("new")).unwrap(), "n\n", "the new file went along"); std::fs::write(there.join("a"), "a3\n").unwrap(); std::fs::remove_file(there.join("b")).unwrap(); std::fs::write(there.join("c"), "c\n").unwrap(); sh(&there, &["add", "-A"]); sh(&there, &["commit", "-qm", "on the runner"]); sh(&there, &["push", "-q", "origin", "HEAD:session/s1"]); // Back: the checkout has the runner's work as uncommitted changes, on its own HEAD. assert_eq!(bring_back(&here, "session/s1", &left.sha).unwrap().0, Back::Restored); assert_eq!(sh(&here, &["rev-parse", "HEAD"]), head); assert_eq!(std::fs::read_to_string(here.join("a")).unwrap(), "a3\n"); assert!(!here.join("b").exists() && here.join("c").exists()); assert_eq!(bring_back(&here, "session/s1", &left.sha).unwrap().0, Back::Already, "twice is once"); // Going again from here: the branch's work is a parent, so it is no force push. std::fs::write(here.join("a"), "a4\n").unwrap(); let again = snapshot(&here, "session/s1", "wip: again").unwrap(); let parents = sh(&here, &["rev-list", "--parents", "-n", "1", &again.sha]); assert_eq!(parents.split(' ').count(), 3, "HEAD and the branch's tip: {parents}"); // A checkout changed meanwhile is left alone. std::fs::write(there.join("a"), "a5\n").unwrap(); sh(&there, &["fetch", "-q", "origin"]); sh(&there, &["reset", "-q", "--hard", "origin/session/s1"]); std::fs::write(there.join("a"), "a5\n").unwrap(); sh(&there, &["commit", "-qam", "more"]); sh(&there, &["push", "-q", "origin", "HEAD:session/s1"]); std::fs::write(here.join("a"), "mine\n").unwrap(); assert_eq!(bring_back(&here, "session/s1", &again.sha).unwrap().0, Back::Diverged); assert_eq!(std::fs::read_to_string(here.join("a")).unwrap(), "mine\n", "untouched"); let _ = std::fs::remove_dir_all(&root); } }