8447
Co
conveyor / files
conveyor / templates / library / widgets / git_commit.rs
9.5 KB
1//! Committing a project's changes from a widget: its `git status`, a message, which files go in, 2//! and the dropdown that edits them. Git runs off the UI thread. 3use super::{api::*, look::Look, ui}; 4use rune::{Align, El, Side, TextEdit, Tx, col, el, row, text}; 5use std::{collections::BTreeSet, path::{Path, PathBuf}, process::Command, sync::{Arc, Mutex}}; 6 7/// What a git run leaves: the new `git status -z`, and a commit's outcome. 8type Done = (String, Option<Result<String, String>>); 9 10pub struct Commit { 11 pub open: bool, 12 pub message: TextEdit, 13 /// Changed files: the status code and the path (a rename's old path after it). 14 files: Vec<(String, Vec<String>)>, 15 /// Paths the user unticked. 16 left_out: BTreeSet<String>, 17 /// The last commit's outcome, shown under the button. 18 note: Option<Result<String, String>>, 19 job: Option<Arc<Mutex<Option<Done>>>>, 20 /// A commit is running: Commit waits for it. 21 busy: bool, 22 /// When status last ran, and where the message is kept with what it last got. 23 at: f64, 24 file: PathBuf, 25 written: String, 26} 27 28impl Commit { 29 pub fn load(dir: &Path) -> Self { 30 let file = dir.join("commit_message"); 31 let written = std::fs::read_to_string(&file).unwrap_or_default(); 32 Commit { open: false, message: TextEdit::new(written.clone()), files: vec![], left_out: BTreeSet::new(), note: None, job: None, busy: false, at: f64::MIN, file, written } 33 } 34 35 /// Every 2 s, a fresh status of `root`; a finished run's result; the message saved as it's typed. 36 pub fn update(&mut self, cx: &Cx, root: &Path) { 37 let done = self.job.as_ref().and_then(|j| j.lock().unwrap().take()); 38 if let Some((status, note)) = done { 39 self.files = parse(&status); 40 if let Some(Ok(_)) = note { self.message = TextEdit::new("") } 41 if note.is_some() { (self.note, self.busy) = (note, false) } 42 self.job = None; 43 cx.act(|_| {}); 44 } 45 if self.job.is_none() && cx.now - self.at > 2.0 && root.join(".git").exists() { self.at = cx.now; self.refresh(root) } 46 if self.message.text != self.written { 47 self.written = self.message.text.clone(); 48 let _ = std::fs::write(&self.file, &self.written); 49 } 50 } 51 52 /// Commits the ticked files with the message. Staging skips paths gone from the tree that git 53 /// no longer tracks (a staged delete, a rename's old name): `add` refuses them, `commit` takes them. 54 pub fn run(&mut self, root: &Path) { 55 let paths: Vec<(&str, &String)> = self.picked().flat_map(|(code, p)| p.iter().map(move |p| (code.as_str(), p))).collect(); 56 let add: Vec<String> = paths.iter().filter(|(code, p)| root.join(p).exists() || code.ends_with('D')).map(|(_, p)| p.to_string()).collect(); 57 let all: Vec<String> = paths.iter().map(|(_, p)| p.to_string()).collect(); 58 let message = self.message.text.trim().to_owned(); 59 if self.busy || all.is_empty() || message.is_empty() { return } 60 self.busy = true; 61 let (slot, root) = (Arc::new(Mutex::new(None)), root.to_owned()); 62 self.job = Some(slot.clone()); 63 std::thread::spawn(move || { 64 let note = (|| { 65 let args = |head: &[&str], paths: &[String]| head.iter().map(|s| s.to_string()).chain(["--".into()]).chain(paths.iter().cloned()).collect::<Vec<_>>(); 66 if !add.is_empty() { git(&root, &args(&["add", "-A"], &add))?; } 67 git(&root, &args(&["commit", "-m", &message], &all))?; 68 git(&root, &["log", "-1", "--format=Committed %h %s"]) 69 })(); 70 *slot.lock().unwrap() = Some((status(&root), Some(note))); 71 }); 72 } 73 74 /// A fresh status, off the UI thread. 75 fn refresh(&mut self, root: &Path) { 76 let (slot, root) = (Arc::new(Mutex::new(None)), root.to_owned()); 77 self.job = Some(slot.clone()); 78 std::thread::spawn(move || *slot.lock().unwrap() = Some((status(&root), None))); 79 } 80 81 fn picked(&self) -> impl Iterator<Item = &(String, Vec<String>)> { 82 self.files.iter().filter(|(_, p)| !self.left_out.contains(&p[0])) 83 } 84 85 /// Opens or closes the dropdown, with a fresh status and no old outcome. 86 pub fn toggle_open(&mut self) { 87 (self.open, self.note, self.at) = (!self.open, None, f64::MIN); 88 } 89 90 fn toggle(&mut self, path: &str) { 91 if !self.left_out.remove(path) { self.left_out.insert(path.to_owned()); } 92 } 93 94 /// All in, or all out when all are in. 95 fn toggle_all(&mut self) { 96 let all = self.picked().count() == self.files.len(); 97 self.left_out = if all { self.files.iter().map(|(_, p)| p[0].clone()).collect() } else { BTreeSet::new() }; 98 } 99} 100 101/// The header button: "Commit" with the changed file count; `press` opens `menu` (with `toggle`). 102/// Nothing outside a git repo. 103pub fn button(t: &Look, cx: &Cx, c: &Commit, root: &Path, press: impl Fn(&mut HostState, &mut Tx) + 'static) -> El { 104 if !root.join(".git").exists() { return el() } 105 let label = if c.files.is_empty() { "Commit".to_owned() } else { format!("Commit ({})", c.files.len()) }; 106 let b = ui::button(t, &ui::anchor(cx, "commit"), &label, true, press).help("Commit your changes"); 107 el().key("commit").child(if c.open { b.fill(t.hover) } else { b }) 108} 109 110/// Under the button: the message, the changed files with a tick each, and Commit, which `commit` does. 111pub fn menu<W: View>(t: &Look, cx: &Cx, c: &Commit, pick: fn(&mut W) -> &mut Commit, commit: impl Fn(&mut HostState, &mut Tx) + 'static) -> El { 112 if !c.open { return el() } 113 let id = cx.id.to_owned(); 114 let n = c.picked().count(); 115 let mut files = col().key("commit-files").w_full().max_h(240.0).scroll(rune::ScrollSpec { stick_bottom: false }).gap(2.0); 116 for (code, paths) in &c.files { 117 let path = paths[0].clone(); 118 let (on_, p) = (!c.left_out.contains(&path), path.clone()); 119 let ink = match code.as_str() { "??" => t.accent, _ if code.contains('D') => t.danger, _ => t.warn }; 120 files = files.child(row().key(format!("commit-file-{}", path.replace('/', "|"))).w_full().min_h(24.0).px(6.0).gap(8.0).center_y().radius(5.0) 121 .role("button").label(path.as_str()).help(paths.join(" ← ").as_str()).hover(t.hover) 122 .on_press_tx(on(cx.id, move |w: &mut W, _| pick(w).toggle(&p))) 123 .child(tick(t, on_)) 124 .child(text(if code == "??" { "U" } else { code.trim() }).font(t.mono).color(ink).w(18.0)) 125 .child(text(path).font(t.label).color(if on_ { t.text } else { t.text_secondary }).truncate().grow(1.0).min_w(0.0))); 126 } 127 if c.files.is_empty() { files = files.child(text("Nothing to commit").font(t.label).color(t.text_secondary).px(6.0)) } 128 let all = row().key("commit-all").w_full().min_h(24.0).px(6.0).gap(8.0).center_y().radius(5.0).role("button").label("All files").hover(t.hover) 129 .on_press_tx(on(cx.id, move |w: &mut W, _| pick(w).toggle_all())) 130 .child(tick(t, n > 0 && n == c.files.len())) 131 .child(text(format!("{n} of {} files", c.files.len())).font(t.label).color(t.text_secondary)); 132 let ready = n > 0 && !c.message.text.trim().is_empty() && !c.busy; 133 let label = if n == 1 { "Commit 1 file".to_owned() } else { format!("Commit {n} files") }; 134 let mut card = ui::popover(t, col().key("commit-menu").w(380.0).padding(10.0).gap(8.0)) 135 .anchored_fit(ui::anchor(cx, "commit"), Side::Bottom, Align::End, 4.0) 136 .modal(true, move |h: &mut HostState| if let Some(w) = get::<W>(h, &id) { pick(w).open = false }) 137 .child(ui::field(t, &c.message, t.body, "Commit message").key("commit-message").min_h(64.0).on_edit(edit(cx.id, move |w: &mut W| &mut pick(w).message))) 138 .child(if c.files.is_empty() { el() } else { all }) 139 .child(el().w_full().h(1.0).fill(t.separator)) 140 .child(files); 141 if let Some(note) = &c.note { 142 let (s, ink) = match note { Ok(s) => (s, t.text_secondary), Err(e) => (e, t.danger) }; 143 card = card.child(text(s.as_str()).key("commit-note").font(t.label).color(ink).w_full().wrap()); 144 } 145 card.child(row().w_full().child(el().grow(1.0)).child(ui::primary(t, "commit-run", &label, ready, commit))) 146} 147 148/// A checkbox: the accent with a check when on, a hairline box when off. 149fn tick(t: &Look, on: bool) -> El { 150 let b = row().w(16.0).h(16.0).center().radius(4.0); 151 if on { b.fill(t.accent).child(text("✓").font(t.label).color(t.on_accent)) } else { b.border(1.0, t.text_secondary) } 152} 153 154/// `git status -z` entries: "XY path", a rename's or copy's old path as the next entry. 155fn parse(status: &str) -> Vec<(String, Vec<String>)> { 156 let mut it = status.split('\0').filter(|e| !e.is_empty()); 157 let mut files = vec![]; 158 while let Some(e) = it.next() { 159 if e.len() < 4 { continue } 160 let (code, mut paths) = (e[..2].to_owned(), vec![e[3..].to_owned()]); 161 if code.contains(['R', 'C']) && let Some(old) = it.next() { paths.push(old.to_owned()) } 162 files.push((code, paths)); 163 } 164 files 165} 166 167/// `git status -z` of `root`, every untracked file listed. 168fn status(root: &Path) -> String { 169 git(root, &["status", "--porcelain=v1", "-z", "-uall"]).unwrap_or_default() 170} 171 172/// `git args` in `root`: its output, or what it said went wrong. 173fn git(root: &Path, args: &[impl AsRef<std::ffi::OsStr>]) -> Result<String, String> { 174 let o = Command::new("git").args(args).current_dir(root).output().map_err(|e| e.to_string())?; 175 let out = |b: &[u8]| String::from_utf8_lossy(b).trim_end_matches('\n').to_owned(); 176 if o.status.success() { Ok(out(&o.stdout)) } else { Err(Some(out(&o.stderr)).filter(|e| !e.is_empty()).unwrap_or_else(|| out(&o.stdout))) } 177}