8447
Co
conveyor / files
conveyor / templates / library / widgets / branch.rs
3.8 KB
1//! A ticket's branch (`refs/conveyor/t-<id>`) of a project's repo as a folder to browse: the files at its tip 2//! (`git archive`), extracted again when the tip moves, and the files it changes against HEAD. 3//! The repo and its checkout are left alone. 4use std::{collections::BTreeSet, path::{Path, PathBuf}, process::{Command, Stdio}, sync::{Arc, Mutex}}; 5 6/// How often the branch's tip is checked, in seconds. 7const EVERY: f64 = 5.0; 8 9#[derive(Default)] 10struct State { rev: String, changed: BTreeSet<PathBuf>, error: Option<String>, busy: bool } 11 12pub struct Snapshot { 13 pub ticket: u32, 14 /// Where the branch's files are. 15 pub tree: PathBuf, 16 state: Arc<Mutex<State>>, 17 seen: String, 18 checked: f64, 19} 20 21impl Snapshot { 22 pub fn new(project: &str, ticket: u32) -> Self { 23 let tree = std::env::temp_dir().join("conveyor-branches").join(format!("{project}-t{ticket}")); 24 Snapshot { ticket, tree, state: Arc::default(), seen: String::new(), checked: f64::MIN } 25 } 26 27 /// Checks the tip of the branch in `repo` every few seconds, extracting it again off the UI 28 /// thread when it moved. True once, when a new tip's files are in `tree`. 29 pub fn poll(&mut self, now: f64, repo: &Path) -> bool { 30 let mut s = self.state.lock().unwrap(); 31 if s.rev != self.seen { self.seen = s.rev.clone(); return true } 32 if s.busy || now - self.checked < EVERY { return false } 33 (self.checked, s.busy) = (now, true); 34 let (state, repo, tree, branch) = (self.state.clone(), repo.to_owned(), self.tree.clone(), format!("refs/conveyor/t-{}", self.ticket)); 35 std::thread::spawn(move || { 36 let had = state.lock().unwrap().rev.clone(); 37 let r = refresh(&repo, &branch, &tree, &had); 38 let mut s = state.lock().unwrap(); 39 match r { 40 Ok(Some((rev, changed))) => (s.rev, s.changed, s.error) = (rev, changed, None), 41 Ok(None) => s.error = None, 42 Err(e) => s.error = Some(e), 43 } 44 s.busy = false; 45 }); 46 false 47 } 48 49 pub fn ready(&self) -> bool { !self.seen.is_empty() } 50 pub fn error(&self) -> Option<String> { self.state.lock().unwrap().error.clone() } 51 /// Whether `path` is a file the branch changes, or a folder holding one. 52 pub fn changed(&self, path: &Path) -> bool { self.state.lock().unwrap().changed.iter().any(|c| c.starts_with(path)) } 53} 54 55/// The branch's tip and changed files when its tip isn't `had`, after extracting it to `tree`. 56fn refresh(repo: &Path, branch: &str, tree: &Path, had: &str) -> Result<Option<(String, BTreeSet<PathBuf>)>, String> { 57 let git = |args: &[&str]| Command::new("git").args(args).current_dir(repo).output().ok().filter(|o| o.status.success()) 58 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()); 59 let rev = git(&["rev-parse", "--verify", "--quiet", &format!("{branch}^{{commit}}")]).ok_or(format!("No branch {branch}"))?; 60 if rev == had { return Ok(None) } 61 let next = tree.with_extension("new"); 62 let _ = std::fs::remove_dir_all(&next); 63 std::fs::create_dir_all(&next).map_err(|e| e.to_string())?; 64 let mut archive = Command::new("git").args(["archive", &rev]).current_dir(repo).stdout(Stdio::piped()).spawn().map_err(|e| format!("git: {e}"))?; 65 let tar = Command::new("tar").arg("-x").arg("-C").arg(&next).stdin(archive.stdout.take().unwrap()).status().map_err(|e| format!("tar: {e}"))?; 66 if !archive.wait().is_ok_and(|s| s.success()) || !tar.success() { return Err(format!("Can't extract {branch}")) } 67 let _ = std::fs::remove_dir_all(tree); 68 std::fs::rename(&next, tree).map_err(|e| e.to_string())?; 69 let changed = git(&["diff", "--name-only", &format!("HEAD...{rev}")]).unwrap_or_default().lines().map(|l| tree.join(l)).collect(); 70 Ok(Some((rev, changed))) 71}