From 0cfb548b119a09193000aaf83de732f7d7ce9855 Mon Sep 17 00:00:00 2001 From: ThinhNguyen2005 Date: Thu, 26 Nov 2026 22:36:17 +0700 Subject: [PATCH 1/7] refactor(panel,remote): add repo-relative path helpers and WSL process cleanup --- src/panel.rs | 78 ++++++++++++++++++++++++++++++++++++++++++++--- src/remote/mod.rs | 3 +- src/term.rs | 1 - src/ws_context.rs | 18 +++++++++-- 4 files changed, 91 insertions(+), 9 deletions(-) diff --git a/src/panel.rs b/src/panel.rs index cd581cf..d6e9d53 100644 --- a/src/panel.rs +++ b/src/panel.rs @@ -233,7 +233,7 @@ impl PanelSel { } fn mono_kind(k: LineKind) -> bool { - matches!(k, LineKind::Normal | LineKind::Err | LineKind::Warn | LineKind::Dim | LineKind::Success | LineKind::Frame | LineKind::Hunk | LineKind::Code | LineKind::Caret | LineKind::Blank) + matches!(k, LineKind::Normal | LineKind::Err | LineKind::Warn | LineKind::Dim | LineKind::Success | LineKind::Frame | LineKind::Code | LineKind::Caret | LineKind::Blank) } pub(crate) type WrapCache = std::cell::RefCell<((usize, usize, usize, usize, usize), std::rc::Rc>)>; @@ -249,11 +249,64 @@ pub(crate) struct Problem { pub message: String, } -fn same_path(a: &Path, b: &Path) -> bool { +pub(crate) fn same_path(a: &Path, b: &Path) -> bool { let n = |p: &Path| p.to_string_lossy().replace('/', "\\").trim_start_matches(r"\\?\").to_lowercase(); if cfg!(windows) { n(a) == n(b) } else { a == b } } +fn clean_path_parts(path: &Path) -> Vec { + let raw = path.to_string_lossy(); + let trimmed = if cfg!(windows) { + if let Some(unc) = raw.strip_prefix(r"\\?\UNC\") { + format!(r"\\{unc}") + } else { + raw.strip_prefix(r"\\?\").unwrap_or(&raw).to_string() + } + } else { + raw.into_owned() + }; + let unified = trimmed.replace('\\', "/"); + unified + .split('/') + .filter(|part| !part.is_empty() && *part != ".") + .map(|part| if cfg!(windows) { part.to_ascii_lowercase() } else { part.to_string() }) + .collect() +} + +pub(crate) fn repo_rel_path(repo: &Path, path: &Path) -> Option { + let base = clean_path_parts(repo); + let raw = path.to_string_lossy(); + let trimmed = if cfg!(windows) { + if let Some(unc) = raw.strip_prefix(r"\\?\UNC\") { + format!(r"\\{unc}") + } else { + raw.strip_prefix(r"\\?\").unwrap_or(&raw).to_string() + } + } else { + raw.into_owned() + }; + let unified = trimmed.replace('\\', "/"); + let parts: Vec<&str> = unified + .split('/') + .filter(|part| !part.is_empty() && *part != ".") + .collect(); + if base.is_empty() || parts.len() <= base.len() { + return None; + } + let matches = parts.iter().zip(&base).all(|(a, b)| { + if cfg!(windows) { + a.eq_ignore_ascii_case(b) + } else { + *a == b + } + }); + matches.then(|| parts[base.len()..].join("/")) +} + +pub(crate) fn path_in_repo(repo: &Path, path: &Path) -> bool { + same_path(repo, path) || repo_rel_path(repo, path).is_some() +} + impl Workbench { pub(crate) fn on_toggle_panel(&mut self, _: &TogglePanel, _: &mut Window, cx: &mut Context) { self.set_panel_open(!self.panel_open, cx); @@ -1308,7 +1361,6 @@ impl Workbench { let col = match k { LineKind::Err | LineKind::Caret => theme::DANGER, LineKind::Warn => theme::WARN, - LineKind::Hunk => theme::BLUE, LineKind::Dim => theme::FG_DIM, LineKind::Success => theme::GREEN, LineKind::Code => theme::FG_STRONG, @@ -1423,7 +1475,7 @@ impl Workbench { for (ix, l) in lines.iter().enumerate() { let marked = l.kind == LineKind::Code && lines.get(ix + 1).is_some_and(|n| n.kind == LineKind::Caret); let (width, hang) = match l.kind { - LineKind::Normal | LineKind::Err | LineKind::Warn | LineKind::Dim | LineKind::Success | LineKind::Frame | LineKind::Hunk => (cols.mono, 2), + LineKind::Normal | LineKind::Err | LineKind::Warn | LineKind::Dim | LineKind::Success | LineKind::Frame => (cols.mono, 2), LineKind::Code if !marked => (cols.mono, 2), LineKind::CardMsg | LineKind::CardHint => (cols.card, 0), LineKind::Result if l.err => (cols.result, 0), @@ -2820,4 +2872,22 @@ mod tests { assert!(matches!(check_script_runnable(&crate_src.join("lib.rs"), "pub fn helper() -> i32 { 1 }", Some(&tmp), false, all), RunVerdict::NotRunnable(_))); let _ = std::fs::remove_dir_all(&tmp); } + + #[test] + fn repo_rel_path_handles_slashes_and_windows_unc_prefixes() { + let repo = Path::new(r"\\?\D:\App\Repo"); + let file = Path::new("d:/app/repo/src/scm_git.rs"); + if cfg!(windows) { + assert_eq!(super::repo_rel_path(repo, file).as_deref(), Some("src/scm_git.rs")); + assert!(super::path_in_repo(repo, file)); + assert!(!super::path_in_repo(repo, Path::new(r"D:\Other\src\scm_git.rs"))); + } else { + let u_repo = Path::new("/work/repo"); + assert_eq!( + super::repo_rel_path(u_repo, Path::new("/work/repo/src/lib.rs")).as_deref(), + Some("src/lib.rs") + ); + assert!(!super::path_in_repo(u_repo, Path::new("/work/repo2/src/lib.rs"))); + } + } } diff --git a/src/remote/mod.rs b/src/remote/mod.rs index 0cfbc59..62c866a 100644 --- a/src/remote/mod.rs +++ b/src/remote/mod.rs @@ -7,8 +7,7 @@ mod proto; mod server; mod wsl; -pub use client::{drop_client, note_ui_thread, set_helper_enabled, warm, with_client, RemoteClient}; +pub use client::{drop_client, note_ui_thread, set_helper_enabled, warm, with_client}; pub use paths::WslTarget; -pub use proto::GitWire; pub use server::serve; pub use wsl::{available, distros, home_dir, list_dirs, program_command, program_command_env, shell_command}; diff --git a/src/term.rs b/src/term.rs index e27c28b..304c227 100644 --- a/src/term.rs +++ b/src/term.rs @@ -15,7 +15,6 @@ pub enum LineKind { Fixed, Status, Result, - Hunk, CardHead, CardMsg, CardCode, diff --git a/src/ws_context.rs b/src/ws_context.rs index f318ea9..19db34d 100644 --- a/src/ws_context.rs +++ b/src/ws_context.rs @@ -350,7 +350,14 @@ pub fn overview(i: &Inputs) -> String { if let Some(up) = &g.upstream { let _ = write!(line, ", tracking {up} ({} ahead, {} behind)", g.ahead, g.behind); } - let changed: Vec = g.conflicts.iter().chain(&g.staged).chain(&g.changes).map(|c| format!("{} {}", c.code, c.path)).collect(); + let changed: Vec = g + .conflicts + .iter() + .chain(&g.staged) + .chain(&g.changes) + .chain(&g.untracked) + .map(|c| format!("{} {}", c.code, c.path)) + .collect(); if changed.is_empty() { line.push_str("; no uncommitted changes"); } else { @@ -394,7 +401,13 @@ pub fn git_signature(g: Option<&RepoStatus>) -> u64 { g.branch.hash(&mut h); g.ahead.hash(&mut h); g.behind.hash(&mut h); - for c in g.conflicts.iter().chain(&g.staged).chain(&g.changes) { + for c in g + .conflicts + .iter() + .chain(&g.staged) + .chain(&g.changes) + .chain(&g.untracked) + { c.code.hash(&mut h); c.path.hash(&mut h); } @@ -413,6 +426,7 @@ pub fn git_delta(g: &RepoStatus) -> String { .iter() .chain(&g.staged) .chain(&g.changes) + .chain(&g.untracked) .map(|c| format!("{} {}", c.code, c.path)) .collect(); if changed.is_empty() { From f9d235e9d14fec34a46eaa9eabe6f60fcdd584e1 Mon Sep 17 00:00:00 2001 From: ThinhNguyen2005 Date: Thu, 26 Nov 2026 22:36:17 +0700 Subject: [PATCH 2/7] feat(scm): overhaul git step runner, source control panes, hunk staging, and conflict resolution --- src/diff_view.rs | 379 +++++- src/i18n_id.rs | 111 ++ src/main.rs | 1 + src/scm.rs | 2866 +++++++++++++++++++++++++++++++------------ src/scm_git.rs | 1196 ++++++++++++++++++ src/scm_incoming.rs | 308 +++-- src/workbench.rs | 57 +- 7 files changed, 3982 insertions(+), 936 deletions(-) create mode 100644 src/scm_git.rs diff --git a/src/diff_view.rs b/src/diff_view.rs index e9b3ac7..6bd64be 100644 --- a/src/diff_view.rs +++ b/src/diff_view.rs @@ -1,7 +1,8 @@ use crate::files; use crate::i18n::tr; +use crate::scm_git::Group; use crate::theme::{self, c}; -use crate::workbench::Workbench; +use crate::workbench::{Doc, Workbench}; use gpui_kit::assets::IconName as Ico; use gpui_kit::component::{ diff::{ @@ -39,6 +40,9 @@ pub struct DiffDoc { pub name: SharedString, pub badge: Option, pub target: Option, + pub(crate) scm_stage: Option<(PathBuf, String, Group)>, + scm_patch: Option>, + conflict_original: Option>, pub state: Option>, pub multi_file: bool, pub empty_note: Option, @@ -112,6 +116,9 @@ pub fn parse(text: &str) -> DiffDoc { name: name.into(), badge: None, target: None, + scm_stage: None, + scm_patch: None, + conflict_original: None, state: None, multi_file: false, empty_note: None, @@ -119,6 +126,42 @@ pub fn parse(text: &str) -> DiffDoc { } } +pub fn untracked_patch(rel_path: &str, bytes: &[u8]) -> Option { + if bytes.iter().take(8192).any(|&b| b == 0) { + return None; + } + let content = String::from_utf8_lossy(bytes); + let lines: Vec<&str> = content.lines().collect(); + let path = |prefix: &str| { + if rel_path.contains(['\\', '"', '\n', '\t', '\r']) { + let escaped = rel_path + .replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\n', "\\n") + .replace('\t', "\\t") + .replace('\r', "\\r"); + format!("\"{prefix}/{escaped}\"") + } else { + format!("{prefix}/{rel_path}") + } + }; + let (old, new) = (path("a"), path("b")); + let mut out = + format!("diff --git {old} {new}\nnew file mode 100644\n--- /dev/null\n+++ {new}\n"); + if !lines.is_empty() { + out.push_str(&format!("@@ -0,0 +1,{} @@\n", lines.len())); + for line in lines { + out.push('+'); + out.push_str(line); + out.push('\n'); + } + if !content.ends_with('\n') { + out.push_str("\\ No newline at end of file\n"); + } + } + Some(out) +} + pub fn parse_with_state(text: &str, cx: &mut Context) -> DiffDoc { let mut doc = parse(text); let files = parse_diff_files(text, None); @@ -171,6 +214,18 @@ pub(crate) fn jump_row_for_y(y: f32, top: f32, height: f32, total: usize) -> usi pub(crate) type DiffRulerDrag = (Entity, Rc>); +pub struct ScmDiffSpec { + pub virtual_key: PathBuf, + pub tab_title: String, + pub display_name: String, + pub badge: String, + pub patch: String, + pub conflict_text: Option, + pub target: Option, + pub(crate) scm_stage: Option<(PathBuf, String, Group)>, + pub multi_file: bool, +} + impl Workbench { pub(crate) fn diff_drag_ruler(&mut self, y: f32, cx: &mut Context) { let Some((st, rect)) = self.diff_ruler_drag.as_ref() else { @@ -185,13 +240,140 @@ impl Workbench { st.update(cx, |s, cx| s.scroll_to_row(row, cx)); } + pub(crate) fn open_scm_diff_tab( + &mut self, + spec: ScmDiffSpec, + window: &mut Window, + cx: &mut Context, + ) { + let existing_ix = self.docs.iter().position(|d| d.path == spec.virtual_key); + let prev_mode = existing_ix + .and_then(|ix| self.docs[ix].diff.as_ref()) + .and_then(|d| d.state.as_ref()) + .map(|st| st.read(cx).mode()) + .unwrap_or(DiffMode::Split); + let lang_hint = spec.target.as_deref().and_then(|p| { + let (l, _) = files::language_for(p, ""); + (l != "text").then_some(l) + }); + let files = if let Some(conflict_text) = &spec.conflict_text { + match DiffFile::parse_conflicts(spec.display_name.clone(), conflict_text) { + Ok(mut f) => { + if let Some(l) = lang_hint { + f = f.with_language(l); + } + vec![f] + } + Err(_) => parse_diff_files(&spec.patch, lang_hint), + } + } else { + parse_diff_files(&spec.patch, lang_hint) + }; + + let (added, removed, state, empty_note) = if !files.is_empty() { + let added = files.iter().map(DiffFile::additions).sum(); + let removed = files.iter().map(DiffFile::deletions).sum(); + let context = if spec.multi_file || spec.scm_stage.is_some() { + Some(3) + } else { + None + }; + let st = cx.new(|cx| { + DiffState::new(files, cx) + .with_mode(prev_mode) + .with_context_lines(context) + }); + if !spec.multi_file && spec.scm_stage.is_none() { + st.update(cx, |s, cx| s.next_change(cx)); + } + (added, removed, Some(st), None) + } else { + ( + 0, + 0, + None, + Some( + tr("No textual changes to compare (binary file or unchanged content).").into(), + ), + ) + }; + + let scm_patch = spec + .scm_stage + .as_ref() + .filter(|(_, _, group)| matches!(group, Group::Changes | Group::Staged)) + .map(|_| std::sync::Arc::from(spec.patch.as_str())); + let diff_doc = DiffDoc { + lines: Rc::new(Vec::new()), + added, + removed, + source: false, + name: spec.display_name.into(), + badge: Some(spec.badge.into()), + target: spec.target, + scm_stage: spec.scm_stage, + scm_patch, + conflict_original: spec.conflict_text.as_deref().map(std::sync::Arc::from), + state, + multi_file: spec.multi_file, + empty_note, + virtual_tab: true, + }; + + if let Some(ix) = existing_ix { + self.docs[ix].name = spec.tab_title.into(); + self.docs[ix].diff = Some(diff_doc); + self.activate(ix, window, cx); + return; + } + + self.anim_seq = self.anim_seq.wrapping_add(1); + self.opened_tab = Some((spec.virtual_key.clone(), self.anim_seq)); + self.docs.push(Doc { + path: spec.virtual_key, + name: spec.tab_title.into(), + lang: "diff", + label: "Diff", + read_only: true, + nbt_format: None, + banner: None, + crlf: false, + editor: None, + dirty: false, + gen: 0, + _sub: None, + image: None, + flux: None, + flux_source: false, + flux_lazy: false, + diff: Some(diff_doc), + long_lines: false, + complex: false, + wrap_override: None, + saved_cursor: Default::default(), + saved_scroll: Default::default(), + last_used: 0, + loading: false, + diagnostics: Vec::new(), + error_count: 0, + warn_count: 0, + diag_ranges: None, + diag_ruler: None, + runnable_runtime: None, + }); + let ix = self.docs.len() - 1; + self.activate(ix, window, cx); + } + pub(crate) fn render_diff_doc(&self, ix: usize, cx: &mut Context) -> AnyElement { let Some(d) = self.docs.get(ix).and_then(|d| d.diff.as_ref()) else { return div().into_any_element(); }; let (green, red) = (c(theme::GREEN), c(theme::DANGER)); let target = d.target.clone(); + let scm_stage = d.scm_stage.clone(); let virtual_tab = d.virtual_tab; + let is_file_diff = scm_stage.is_some(); let state = d.state.clone(); let (is_split, is_full) = match &state { Some(st) => { @@ -283,24 +465,60 @@ impl Workbench { .child(div().flex_1()); if let Some(st) = &state { + if is_file_diff { + if let Some((hunk, count)) = st.read(cx).hunk_position() { + bar = bar.child( + div() + .flex_none() + .text_color(c(theme::FG_MUTED)) + .child(crate::trf!("Hunk {n}/{total}"; n => hunk + 1, total => count)), + ); + } + } let st_prev = st.clone(); let st_next = st.clone(); let st_mode = st.clone(); let st_ctx = st.clone(); bar = bar .child( - icon_btn("diff-prev", Ico::ArrowUp, "Previous change").on_click( - cx.listener(move |_, _, _, cx| { - st_prev.update(cx, |s, cx| s.previous_change(cx)); - }), - ), + icon_btn( + "diff-prev", + Ico::ArrowUp, + if is_file_diff { + "Previous hunk" + } else { + "Previous change" + }, + ) + .on_click(cx.listener(move |_, _, _, cx| { + st_prev.update(cx, |s, cx| { + if is_file_diff { + s.move_hunk(false, cx) + } else { + s.previous_change(cx) + } + }); + })), ) .child( - icon_btn("diff-next", Ico::ArrowDown, "Next change").on_click( - cx.listener(move |_, _, _, cx| { - st_next.update(cx, |s, cx| s.next_change(cx)); - }), - ), + icon_btn( + "diff-next", + Ico::ArrowDown, + if is_file_diff { + "Next hunk" + } else { + "Next change" + }, + ) + .on_click(cx.listener(move |_, _, _, cx| { + st_next.update(cx, |s, cx| { + if is_file_diff { + s.move_hunk(true, cx) + } else { + s.next_change(cx) + } + }); + })), ) .child( btn("diff-mode", if is_split { "Inline" } else { "Side by side" }, false) @@ -313,13 +531,127 @@ impl Workbench { st_mode.update(cx, |s, cx| s.set_mode(next, cx)); })), ) - .child( - btn("diff-ctx", if is_full { "Full file" } else { "Changes only" }, false) - .on_click(cx.listener(move |_, _, _, cx| { - let next = if is_full { Some(3) } else { None }; - st_ctx.update(cx, |s, cx| s.set_context_lines(next, cx)); - })), + .when(!is_file_diff, |h| { + h.child( + btn("diff-ctx", if is_full { "Full file" } else { "Changes only" }, false) + .on_click(cx.listener(move |_, _, _, cx| { + let next = if is_full { Some(3) } else { None }; + st_ctx.update(cx, |s, cx| s.set_context_lines(next, cx)); + })), + ) + }); + } + + if let Some((repo, rel, group)) = scm_stage { + if self.scm.repo.as_ref() == Some(&repo) + && !self.scm.is_busy() + && self + .scm + .status + .files(group) + .iter() + .any(|file| file.path == rel) + { + if let Some((original, conflict_state)) = + d.conflict_original.clone().zip(state.clone()) + { + let path = rel.clone(); + let conflict_repo = repo.clone(); + bar = bar.child(btn("save-conflict-resolution", "Save Resolution", false).on_click( + cx.listener(move |this, _, _, cx| { + if this.scm.repo.as_ref() != Some(&conflict_repo) { + return; + } + let full = conflict_repo.join(&path); + let unsaved = this + .docs + .iter() + .any(|doc| doc.dirty && crate::panel::same_path(&doc.path, &full)); + let resolved = conflict_state.read(cx).resolved_text(&path); + if unsaved || resolved.is_none() { + let message = if unsaved { + tr("Save unsaved editors before changing Git branches or files.") + } else { + tr("Choose a resolution for every conflict first.") + }; + this.status = message.into(); + cx.notify(); + return; + } + if let Some(resolved) = resolved { + let step = crate::scm_git::Step::Resolve { + path: path.clone(), + expected: original.to_string(), + resolved, + }; + this.scm_run(tr("Running Git…"), vec![step], cx, |this, _, _| { + this.status = tr("Conflict resolution saved and staged.").into(); + }); + } + }), + )); + } + if let Some((patch, (index, _))) = d + .scm_patch + .clone() + .zip(state.as_ref().and_then(|state| state.read(cx).hunk_position())) + { + if self + .scm + .status + .files(group) + .iter() + .any(|file| file.path == rel && file.code == 'M') + { + let path = rel.clone(); + let hunk_repo = repo.clone(); + bar = bar.child( + btn( + "diff-hunk-stage", + if group == Group::Staged { + "Unstage Hunk" + } else { + "Stage Hunk" + }, + false, + ) + .on_click(cx.listener(move |this, _, window, cx| { + if this.scm.repo.as_ref() != Some(&hunk_repo) { + return; + } + this.scm_stage_hunk( + path.clone(), + group, + patch.to_string(), + index, + window, + cx, + ); + })), + ); + } + } + bar = bar.child( + icon_btn( + "diff-stage", + if group == Group::Staged { + Ico::Minus + } else { + Ico::Plus + }, + if group == Group::Staged { + "Unstage" + } else { + "Stage" + }, + ) + .on_click(cx.listener(move |this, _, _, cx| { + if this.scm.repo.as_ref() == Some(&repo) { + this.scm_paths(group, Some(rel.clone()), false, cx); + } + })), ); + } } if let Some(path) = target.clone() { @@ -581,7 +913,7 @@ impl Workbench { #[cfg(test)] mod tests { - use super::{jump_row_for_y, parse, parse_diff_files, Kind}; + use super::{jump_row_for_y, parse, parse_diff_files, untracked_patch, Kind}; #[test] fn numbers_follow_the_hunks() { @@ -622,6 +954,17 @@ mod tests { assert_eq!(files[0].deletions(), 0); } + #[test] + fn untracked_patch_handles_text_and_skips_binary() { + let p = untracked_patch("src/new.kt", b"fun main() {}\n").unwrap(); + assert!(p.contains("+++ b/src/new.kt\n@@ -0,0 +1,1 @@\n+fun main() {}\n")); + assert!(untracked_patch("img.png", b"\x89PNG\0\0").is_none()); + let quoted = untracked_patch("tabs\tand\nlines.rs", b"content").unwrap(); + let parsed = parse_diff_files("ed, None); + assert_eq!(parsed[0].path().as_ref(), "tabs\tand\nlines.rs"); + assert_eq!(parsed[0].additions(), 1); + } + #[test] fn overview_ruler_maps_click_y_to_clamped_row() { assert_eq!(jump_row_for_y(100., 100., 200., 101), 0); diff --git a/src/i18n_id.rs b/src/i18n_id.rs index cbd7570..6c22a3a 100644 --- a/src/i18n_id.rs +++ b/src/i18n_id.rs @@ -1811,6 +1811,117 @@ pub const ID: &[(&str, &str)] = &[ "No textual changes to compare (binary file or unchanged content).", "Tidak ada perubahan teks untuk dibandingkan (file biner atau isinya sama).", ), + ("Commit", "Commit"), + ("Commit All", "Commit Semua"), + ("Commit (Sign Off)", "Commit (Sign Off)"), + ("Stage everything and commit", "Stage semua dan commit"), + ("Enter a commit message.", "Masukkan pesan commit."), + ( + "Resolve the merge conflicts before committing.", + "Selesaikan konflik merge sebelum commit.", + ), + ("There is no commit to amend.", "Tidak ada commit untuk di-amend."), + ( + "Stage changes or enter a new commit message to amend.", + "Stage perubahan atau masukkan pesan commit baru untuk amend.", + ), + ("Stage changes before committing.", "Stage perubahan sebelum commit."), + ("There are no changes to commit.", "Tidak ada perubahan untuk di-commit."), + ("Index", "Index"), + ("Conflict", "Konflik"), + ("Working Tree", "Working Tree"), + ("List", "Daftar"), + ("View as List", "Lihat sebagai Daftar"), + ("View as Tree", "Lihat sebagai Pohon"), + ("No commits yet.", "Belum ada commit."), + ("View full diff", "Lihat diff penuh"), + ("No changed files.", "Tidak ada file berubah."), + ("Publish Branch", "Publikasikan Branch"), + ("Upstream unavailable", "Upstream tidak tersedia"), + ("Hunk {n}/{total}", "Hunk {n}/{total}"), + ("Previous hunk", "Hunk sebelumnya"), + ("Next hunk", "Hunk berikutnya"), + ("Hunk updated.", "Hunk diperbarui."), + ("Stage Hunk", "Stage Hunk"), + ("Unstage Hunk", "Unstage Hunk"), + ("Save Resolution", "Simpan Resolusi"), + ( + "Choose a resolution for every conflict first.", + "Pilih resolusi untuk setiap konflik dulu.", + ), + ( + "Conflict resolution saved and staged.", + "Resolusi konflik disimpan dan di-stage.", + ), + ( + "Save unsaved editors before changing Git branches or files.", + "Simpan editor yang belum tersimpan sebelum mengganti branch atau file Git.", + ), + ("The diff is too large to preview.", "Diff terlalu besar untuk ditampilkan."), + ( + "The untracked file is too large to preview.", + "File untracked terlalu besar untuk ditampilkan.", + ), + ( + "The diff changed. Reopen it before staging or unstaging a hunk.", + "Diff berubah. Buka ulang sebelum stage atau unstage hunk.", + ), + ( + "The conflict changed. Reopen it before saving the resolution.", + "Konflik berubah. Buka ulang sebelum menyimpan resolusi.", + ), + ( + "The selected files changed. Review Source Control and try again.", + "File terpilih berubah. Periksa Source Control lalu coba lagi.", + ), + ( + "Discard untracked files individually inside nested repositories.", + "Buang file untracked satu per satu di dalam repositori bersarang.", + ), + ( + "Discard or stage the working tree changes to these files first.", + "Buang atau stage perubahan working tree pada file ini dulu.", + ), + ( + "Configure Git user.name and user.email before committing.", + "Atur user.name dan user.email Git sebelum commit.", + ), + ( + "The remote branch has new commits. Pull or Sync before pushing again.", + "Branch remote punya commit baru. Pull atau Sync sebelum push lagi.", + ), + ( + "Check Git credentials or your SSH connection in a terminal, then retry.", + "Periksa kredensial Git atau koneksi SSH di terminal, lalu coba lagi.", + ), + ( + "No Git remote is configured. Add a remote before fetching, pulling, or pushing.", + "Belum ada remote Git terpasang. Tambahkan remote sebelum fetch, pull, atau push.", + ), + ( + "Switch to a branch before pulling, pushing, or syncing.", + "Pindah ke sebuah branch sebelum pull, push, atau sync.", + ), + ( + "Resolve and finish the merge, or abort it before using the remote.", + "Selesaikan dan akhiri merge, atau batalkan sebelum menggunakan remote.", + ), + ( + "This branch has no upstream. Set one or publish the branch before pulling.", + "Branch ini belum punya upstream. Atur upstream atau publikasikan branch sebelum pull.", + ), + ( + "Pull left unresolved conflicts. Resolve them before continuing.", + "Pull meninggalkan konflik yang belum selesai. Selesaikan dulu sebelum lanjut.", + ), + ( + "Create a commit before publishing this branch.", + "Buat commit sebelum mempublikasikan branch ini.", + ), + ( + "No origin remote is configured. Set the branch upstream before pushing.", + "Remote origin belum diatur. Atur upstream branch sebelum push.", + ), ]; #[cfg(test)] diff --git a/src/main.rs b/src/main.rs index 3e05d44..1a59d90 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,6 +37,7 @@ mod proc; mod quick; mod remote; mod scm; +mod scm_git; mod scm_incoming; mod search; mod scene; diff --git a/src/scm.rs b/src/scm.rs index 9bbce05..819c24b 100644 --- a/src/scm.rs +++ b/src/scm.rs @@ -1,6 +1,5 @@ use crate::i18n::tr; -use crate::proc; use crate::theme::{self, c}; use crate::workbench::*; use gpui_kit::assets::IconName as Ico; @@ -9,48 +8,18 @@ use gpui_kit::component::{ h_flex, input::{InputEvent, InputState}, menu::{DropdownMenu, PopupMenu}, - v_flex, Icon, IconName, Sizable, + scroll::ScrollableElement, + v_flex, Disableable, ElementExt, Icon, IconName, Sizable, }; use gpui_kit::{prelude::FluentBuilder, *}; +use std::cell::Cell; use std::collections::{HashMap, HashSet}; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::rc::Rc; use gpui_kit::component::tooltip::Tooltip; -#[derive(Clone, Debug, PartialEq)] -pub struct FileChange { - pub path: String, - pub code: char, - pub orig: Option, -} - -#[derive(Clone, Debug, Default, PartialEq)] -pub struct RepoStatus { - pub branch: Option, - pub upstream: Option, - pub ahead: u32, - pub behind: u32, - pub staged: Vec, - pub changes: Vec, - pub conflicts: Vec, -} - -impl RepoStatus { - pub fn count(&self) -> usize { - self.staged.len() + self.changes.len() + self.conflicts.len() - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct Commit { - pub hash: String, - pub short: String, - pub subject: String, - pub author: String, - pub when: String, - pub refs: Vec, - pub merge: bool, -} +use crate::scm_git::{git_step, run_step, snapshot, FileChange, Group, RemoteAction, Step}; +pub use crate::scm_git::{parse_log, Commit, RepoStatus}; #[derive(Clone, Debug)] pub struct Run { @@ -75,22 +44,214 @@ pub enum After { Sync, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ScmPane { + Conflicts = 0, + Staged = 1, + Changes = 2, + Graph = 3, + Actions = 4, + Untracked = 5, +} + +#[derive(Clone, Copy, Debug)] +struct PaneSpec { + id: ScmPane, + flexible: bool, + min_h: f32, + natural_h: f32, + saved: Option, +} + +#[derive(Clone, Debug)] +pub struct ScmPaneDrag { + pub(crate) sash: usize, + pub(crate) y0: f32, + pub(crate) ids: Vec, + pub(crate) start: Vec, + pub(crate) mins: Vec, + pub(crate) maxs: Vec, +} + +const SASH_H: f32 = 5.; + +fn water_fill_panes(budget: f32, specs: &[PaneSpec], flex_ix: &[usize]) -> Vec { + let mut out = vec![0.; specs.len()]; + let mut active: Vec = flex_ix.to_vec(); + let mut rem = budget; + loop { + if active.is_empty() { + break; + } + let share = rem / active.len() as f32; + let mut settled = false; + let mut next = Vec::with_capacity(active.len()); + for i in active { + if specs[i].natural_h <= share { + let h = specs[i].natural_h.max(specs[i].min_h).min(rem); + out[i] = h; + rem = (rem - h).max(0.); + settled = true; + } else { + next.push(i); + } + } + active = next; + if !settled { + break; + } + } + if !active.is_empty() { + let share = rem / active.len() as f32; + for i in active { + out[i] = share.max(specs[i].min_h); + } + } else if rem > 0.5 { + if let Some(&last) = flex_ix.last() { + out[last] += rem; + } + } + out +} + +fn resolve_pane_heights(avail_h: f32, specs: &[PaneSpec]) -> Vec { + let mut out: Vec = specs.iter().map(|s| s.min_h).collect(); + let fixed_sum: f32 = specs.iter().filter(|s| !s.flexible).map(|s| s.min_h).sum(); + let budget = (avail_h - fixed_sum).max(0.); + let flex_ix: Vec = specs + .iter() + .enumerate() + .filter(|(_, s)| s.flexible) + .map(|(i, _)| i) + .collect(); + if flex_ix.is_empty() { + return out; + } + if flex_ix.len() == 1 { + let i = flex_ix[0]; + out[i] = budget.max(specs[i].min_h); + return out; + } + let min_sum: f32 = flex_ix.iter().map(|&i| specs[i].min_h).sum(); + if budget <= min_sum { + let denom = min_sum.max(1.); + for &i in &flex_ix { + out[i] = (budget * (specs[i].min_h / denom)).max(1.); + } + return out; + } + let def = water_fill_panes(budget, specs, &flex_ix); + if flex_ix.iter().all(|&i| specs[i].saved.is_none()) { + for &i in &flex_ix { + out[i] = def[i]; + } + return out; + } + for &i in &flex_ix { + out[i] = specs[i].saved.unwrap_or(def[i]).max(specs[i].min_h); + } + let cur_sum: f32 = flex_ix.iter().map(|&i| out[i]).sum(); + if cur_sum < budget { + let extra = budget - cur_sum; + let denom = cur_sum.max(1.); + for &i in &flex_ix { + out[i] += extra * (out[i] / denom); + } + } else if cur_sum > budget { + let excess = cur_sum - budget; + let slack_sum: f32 = flex_ix + .iter() + .map(|&i| (out[i] - specs[i].min_h).max(0.)) + .sum(); + if slack_sum > 0. { + for &i in &flex_ix { + let slack = (out[i] - specs[i].min_h).max(0.); + out[i] -= excess * (slack / slack_sum); + } + } + } + out +} + +fn apply_sash_drag(drag: &ScmPaneDrag, y: f32) -> Vec<(ScmPane, f32)> { + let n = drag.start.len(); + if drag.sash == 0 || drag.sash >= n { + return Vec::new(); + } + let delta = y - drag.y0; + let mut h = drag.start.clone(); + if delta > 0. { + let grow_above: f32 = (0..drag.sash).map(|i| (drag.maxs[i] - h[i]).max(0.)).sum(); + let shrink_below: f32 = (drag.sash..n).map(|i| (h[i] - drag.mins[i]).max(0.)).sum(); + let shift = delta.min(grow_above).min(shrink_below); + let mut rem = shift; + for i in (0..drag.sash).rev() { + let add = rem.min((drag.maxs[i] - h[i]).max(0.)); + h[i] += add; + rem -= add; + } + let mut rem = shift; + for (cur, &min_h) in h[drag.sash..].iter_mut().zip(&drag.mins[drag.sash..]) { + let sub = rem.min((*cur - min_h).max(0.)); + *cur -= sub; + rem -= sub; + } + } else if delta < 0. { + let shrink_above: f32 = (0..drag.sash).map(|i| (h[i] - drag.mins[i]).max(0.)).sum(); + let grow_below: f32 = (drag.sash..n).map(|i| (drag.maxs[i] - h[i]).max(0.)).sum(); + let shift = (-delta).min(shrink_above).min(grow_below); + let mut rem = shift; + for i in (0..drag.sash).rev() { + let sub = rem.min((h[i] - drag.mins[i]).max(0.)); + h[i] -= sub; + rem -= sub; + } + let mut rem = shift; + for (cur, &max_h) in h[drag.sash..].iter_mut().zip(&drag.maxs[drag.sash..]) { + let add = rem.min((max_h - *cur).max(0.)); + *cur += add; + rem -= add; + } + } + drag.ids + .iter() + .copied() + .zip(h) + .enumerate() + .filter(|(i, _)| drag.maxs[*i] > drag.mins[*i]) + .map(|(_, pair)| pair) + .collect() +} + pub struct Scm { pub repo: Option, pub status: RepoStatus, pub log: Vec, + pub commit_open: Option, + pub commit_files: HashMap>, pub runs: Vec, pub workflows: Vec, pub busy: Option, pub error: Option, + repo_error: Option, pub note: Option<(String, Option)>, pub message: Entity, + pub msg_non_empty: bool, + pub workspace_generation: u64, refreshing: bool, again: bool, + show_changes_view: bool, + show_tree: bool, + collapsed_folders: [HashSet; 4], + pub show_conflicts: bool, + pub show_staged: bool, + pub show_changes: bool, + pub show_untracked: bool, + row_limits: [usize; 4], pub show_graph: bool, pub show_actions: bool, pub actions_loaded: bool, - pub confirm_discard: Option, + confirm_discard: Option<(Group, Option, Vec)>, pub confirm_uninit: bool, pub marks: Rc>, pub dirty_dirs: Rc>, @@ -105,29 +266,66 @@ pub struct Scm { pub fetching: bool, pub fetch_loop: bool, pub last_fetch: Option, + pub pane_h: [Option; 6], + pub painted_h: Rc>, + pub stack_h: Rc>, + pub pane_drag: Option, } impl Scm { + pub(crate) fn is_busy(&self) -> bool { + self.busy.is_some() || self.fetching + } + pub fn new(window: &mut Window, cx: &mut Context) -> (Self, Subscription) { let message = cx.new(|cx| InputState::new(window, cx).placeholder(tr("Commit message"))); - let sub = cx.subscribe_in(&message, window, |this: &mut Workbench, _, ev: &InputEvent, window, cx| { - if let InputEvent::PressEnter { .. } = ev { - this.scm_commit(After::Nothing, false, window, cx); - } - }); + let sub = cx.subscribe_in( + &message, + window, + |this: &mut Workbench, _, ev: &InputEvent, window, cx| { + if let InputEvent::PressEnter { .. } = ev { + this.scm_commit(After::Nothing, false, window, cx); + } else { + let non_empty = !this.scm.message.read(cx).value().trim().is_empty(); + let cleared_err = non_empty + && this.scm.error.as_deref() == Some(tr("Enter a commit message.")) + && { + this.scm.error = None; + true + }; + if non_empty != this.scm.msg_non_empty || cleared_err { + this.scm.msg_non_empty = non_empty; + cx.notify(); + } + } + }, + ); ( Self { repo: None, status: RepoStatus::default(), log: Vec::new(), + commit_open: None, + commit_files: HashMap::new(), runs: Vec::new(), workflows: Vec::new(), busy: None, error: None, + repo_error: None, note: None, message, + msg_non_empty: false, + workspace_generation: 0, refreshing: false, again: false, + show_changes_view: true, + show_tree: false, + collapsed_folders: Default::default(), + show_conflicts: true, + show_staged: true, + show_changes: true, + show_untracked: true, + row_limits: [MAX_ROWS; 4], show_graph: true, show_actions: false, actions_loaded: false, @@ -146,6 +344,10 @@ impl Scm { fetching: false, fetch_loop: false, last_fetch: None, + pane_h: [None; 6], + painted_h: Rc::new(Cell::new([0.; 6])), + stack_h: Rc::new(Cell::new(0.)), + pane_drag: None, }, sub, ) @@ -163,175 +365,25 @@ pub fn code_color(code: char) -> theme::Tok { } -pub fn parse_status(out: &str) -> RepoStatus { - let mut st = RepoStatus::default(); - let mut recs = out.split('\0').filter(|r| !r.is_empty()); - let letter = |c: char| if c == '?' { 'U' } else if c == 'T' { 'M' } else { c }; - while let Some(r) = recs.next() { - if let Some(h) = r.strip_prefix("# branch.head ") { - st.branch = (h != "(detached)").then(|| h.to_string()); - } else if let Some(u) = r.strip_prefix("# branch.upstream ") { - st.upstream = Some(u.to_string()); - } else if let Some(ab) = r.strip_prefix("# branch.ab ") { - let mut it = ab.split_whitespace(); - st.ahead = it.next().and_then(|a| a.trim_start_matches('+').parse().ok()).unwrap_or(0); - st.behind = it.next().and_then(|b| b.trim_start_matches('-').parse().ok()).unwrap_or(0); - } else if let Some(p) = r.strip_prefix("? ") { - st.changes.push(FileChange { path: p.to_string(), code: 'U', orig: None }); - } else if r.starts_with("1 ") || r.starts_with("2 ") { - let renamed = r.starts_with('2'); - let fields: Vec<&str> = r.splitn(if renamed { 10 } else { 9 }, ' ').collect(); - let xy: Vec = fields.get(1).unwrap_or(&"..").chars().collect(); - let path = fields.last().unwrap_or(&"").to_string(); - let orig = if renamed { recs.next().map(str::to_string) } else { None }; - if xy[0] != '.' { - st.staged.push(FileChange { path: path.clone(), code: letter(xy[0]), orig: orig.clone() }); - } - if xy.get(1).is_some_and(|y| *y != '.') { - st.changes.push(FileChange { path, code: letter(xy[1]), orig }); - } - } else if r.starts_with("u ") { - let path = r.splitn(11, ' ').last().unwrap_or("").to_string(); - st.conflicts.push(FileChange { path, code: '!', orig: None }); - } - } - st -} - -pub fn parse_log(out: &str) -> Vec { - out.split('\0') - .filter(|r| !r.trim().is_empty()) - .filter_map(|r| { - let f: Vec<&str> = r.trim_start_matches('\n').split('\x1f').collect(); - (f.len() >= 7).then(|| Commit { - hash: f[0].into(), - short: f[1].into(), - subject: f[2].into(), - author: f[3].into(), - when: f[4].into(), - refs: f[5].split(", ").filter(|s| !s.is_empty() && *s != "origin/HEAD").map(|s| s.replace("HEAD -> ", "")).collect(), - merge: f[6].split_whitespace().count() > 1, - }) - }) - .collect() -} - fn find_url(s: &str) -> Option { let i = s.find("https://")?; Some(s[i..].split_whitespace().next()?.trim_end_matches(['.', ',', ')']).to_string()) } -#[derive(Clone)] -pub enum Step { - Save { path: PathBuf, gen: u64, text: String, crlf: bool, nbt: Option }, - Git(Vec, Option), - Gh(Vec), -} - -fn git_step(args: &[&str]) -> Step { - Step::Git(args.iter().map(|s| s.to_string()).collect(), None) -} - -fn run_step(dir: &Path, step: &Step, target: Option<&crate::remote::WslTarget>) -> Result { - use std::io::Write; - let (prog, args, input) = match step { - Step::Save { path, text, crlf, nbt, .. } => { - crate::workbench::write_doc_to_disk(target, path, text, *crlf, *nbt)?; - return Ok(String::new()); - } - Step::Git(a, i) => ("git", a, i.clone()), - Step::Gh(a) => ("gh", a, None), - }; - let target = matches!(step, Step::Git(..)).then_some(target).flatten(); - let refs: Vec<&str> = args.iter().map(String::as_str).collect(); - let mut cmd = match &target { - Some(t) => { - let cwd = t.linux_path(dir).unwrap_or_else(|| t.linux_root.clone()); - let owned: Vec = args.iter().map(|s| s.to_string()).collect(); - if let Some(r) = crate::remote::with_client(&t.distro.clone(), |c| c.git(&cwd, &owned, input.as_deref())) { - match r { - Ok(g) if g.success => { - return Ok(if g.stdout.trim().is_empty() { g.stderr.trim().to_string() } else { g.stdout }) - } - Ok(g) => return Err(format!("{prog} {}: {}", args.first().map(String::as_str).unwrap_or(""), g.stderr.trim())), - Err(_) => {} - } - } - crate::remote::program_command_env( - t, - &cwd, - &[("GIT_OPTIONAL_LOCKS", "0"), ("GIT_TERMINAL_PROMPT", "0"), ("NO_COLOR", "1")], - prog, - &refs, - ) - } - None => { - let mut c = proc::command(prog); - c.args(args).current_dir(dir); - c - } - }; - cmd.env("GIT_OPTIONAL_LOCKS", "0") - .env("GIT_TERMINAL_PROMPT", "0") - .env("GH_PROMPT_DISABLED", "1") - .env("NO_COLOR", "1") - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()); - crate::github::apply_env(&mut cmd); - let mut child = cmd.spawn().map_err(|e| format!("{prog} could not start: {e}"))?; - if let Some(mut stdin) = child.stdin.take() { - if let Some(text) = input { - let _ = stdin.write_all(text.as_bytes()); - } - } - let out = child.wait_with_output().map_err(|e| e.to_string())?; - let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); - let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); - if out.status.success() { - Ok(if stdout.trim().is_empty() { stderr } else { stdout }) - } else { - let msg = if stderr.is_empty() { stdout.trim().to_string() } else { stderr }; - Err(format!("{prog} {}: {}", args.first().map(String::as_str).unwrap_or(""), msg)) +fn group_title(group: Group) -> &'static str { + match group { + Group::Conflicts => tr("Merge Conflicts"), + Group::Staged => tr("Staged Changes"), + Group::Changes => tr("Changes"), + Group::Untracked => tr("Untracked Files"), } } -struct Snapshot { - repo: Option, - status: RepoStatus, - log: Option>, - incoming: (Vec, Option), -} - -fn snapshot(dir: &Path, with_log: bool, target: Option<&crate::remote::WslTarget>) -> Snapshot { - let top = run_step(dir, &git_step(&["rev-parse", "--show-toplevel"]), target).ok().map(|s| { - let p = s.trim(); - match target { - Some(t) => t.unc_path(p), - None => PathBuf::from(p.replace('/', "\\")), - } - }); - let Some(repo) = top else { return Snapshot { repo: None, status: RepoStatus::default(), log: None, incoming: Default::default() } }; - let status = run_step(&repo, &git_step(&["status", "--porcelain=v2", "--branch", "-z", "-uall"]), target).map(|s| parse_status(&s)).unwrap_or_default(); - let log = with_log.then(|| { - run_step( - &repo, - &git_step(&["-c", "i18n.logOutputEncoding=UTF-8", "log", "-n", "60", "--format=%H%x1f%h%x1f%s%x1f%an%x1f%ar%x1f%D%x1f%P", "-z"]), - target, - ) - .map(|s| parse_log(&s)) - .unwrap_or_default() - }); - let incoming = if status.behind > 0 { crate::scm_incoming::incoming(&repo, target) } else { Default::default() }; - Snapshot { repo: Some(repo), status, log, incoming } -} - const MAX_ROWS: usize = 200; pub(crate) const ROW_H: f32 = 24.; -const LANE_MID: f32 = ROW_H * 0.5; -const DOT_SIZE: f32 = 8.; -const DOT_TOP: f32 = LANE_MID - DOT_SIZE * 0.5; +// Clear gpui-base's 16px overlay scrollbar track so badges and controls never sit underneath it. +pub(crate) const SCROLLBAR_PAD: f32 = 18.; // `.overflow_hidden()` drops Taffy's min-height to 0, so `.flex_none()` keeps rows from collapsing under scroll overflow. pub(crate) fn scm_row() -> Div { @@ -343,87 +395,151 @@ pub(crate) fn scm_row() -> Div { .h(theme::u(ROW_H)) } -pub(crate) fn graph_lane( - first: bool, - end: bool, - color: theme::Tok, - line_alpha: f32, - filled: bool, -) -> Div { - div() - .relative() - .w(theme::u(14.)) - .h_full() - .flex_none() - .child( - div() - .absolute() - .left(theme::u(6.)) - .w(px(2.)) - .top(if first { theme::u(LANE_MID) } else { px(0.) }) - .bottom(if end { theme::u(LANE_MID) } else { px(0.) }) - .bg(c(color).opacity(line_alpha)), - ) - .child( - div() - .absolute() - .left(theme::u(3.)) - .top(theme::u(DOT_TOP)) - .size(theme::u(DOT_SIZE)) - .rounded_full() - .border_2() - .border_color(c(color)) - .bg(if filled { c(color) } else { c(theme::BG_SIDE) }), - ) +#[derive(Debug, PartialEq, Eq)] +enum ChangeTreeRow<'a> { + Folder(&'a str, usize), + File(usize, usize), +} + +fn change_tree_rows<'a>(files: &'a [FileChange], collapsed: &HashSet) -> Vec> { + let mut sorted: Vec<_> = files.iter().enumerate().collect(); + sorted.sort_unstable_by(|(_, a), (_, b)| a.path.cmp(&b.path)); + let mut folders = HashSet::new(); + let mut rows = Vec::new(); + 'file: for (index, file) in sorted { + let mut depth = 0; + for (offset, _) in file.path.match_indices('/') { + let folder = &file.path[..offset]; + if folders.insert(folder) { + rows.push(ChangeTreeRow::Folder(folder, depth)); + } + if collapsed.contains(folder) { + continue 'file; + } + depth += 1; + } + rows.push(ChangeTreeRow::File(index, depth)); + } + rows } -fn more_rows(total: usize) -> Option
{ - (total > MAX_ROWS).then(|| { - div() - .flex_none() - .px(theme::u(18.)) - .py_1() - .text_xs() - .text_color(c(theme::FG_DIM)) - .child(crate::trf!("… and {n} more files (Stage All includes them)"; n => total - MAX_ROWS)) - }) +pub(crate) fn lane_geometry(index: usize, count: usize, extends_below: bool) -> (f32, f32, f32) { + let mid = ROW_H / 2.; + let top = if index == 0 { mid } else { 0. }; + let bottom = if index + 1 >= count && !extends_below { + mid + } else { + 0. + }; + let dot_top = (ROW_H - 8.) / 2.; + (top, bottom, dot_top) } impl Workbench { + pub(crate) fn scm_reset_workspace(&mut self) { + let s = &mut self.scm; + s.workspace_generation = s.workspace_generation.wrapping_add(1); + s.repo = None; + s.status = RepoStatus::default(); + s.log.clear(); + s.commit_open = None; + s.commit_files.clear(); + s.incoming.clear(); + s.incoming_head = None; + s.incoming_dismissed = None; + s.incoming_open = None; + s.incoming_files.clear(); + s.runs.clear(); + s.workflows.clear(); + s.actions_loaded = false; + s.refreshing = false; + s.again = false; + s.fetching = false; + s.last_fetch = None; + s.last_refresh = None; + s.busy = None; + s.error = None; + s.repo_error = None; + s.note = None; + s.confirm_discard = None; + s.confirm_uninit = false; + s.marks = Rc::default(); + s.dirty_dirs = Rc::default(); + s.row_limits = [MAX_ROWS; 4]; + s.collapsed_folders = Default::default(); + s.msg_non_empty = false; + s.clear_message = true; + } + pub(crate) fn scm_refresh(&mut self, cx: &mut Context) { let Some(root) = self.root.clone() else { return }; - if self.scm.refreshing { + if self.scm.refreshing || self.scm.is_busy() { self.scm.again = true; return; } self.scm.refreshing = true; + self.scm.again = false; + let generation = self.scm.workspace_generation; self.scm.last_refresh = Some(std::time::Instant::now()); let with_log = self.scm.show_graph; let wsl = self.wsl.clone(); cx.spawn(async move |this, cx| { let snap = cx.background_spawn(async move { snapshot(&root, with_log, wsl.as_ref()) }).await; _ = this.update(cx, |this, cx| { + if this.scm.workspace_generation != generation { + return; + } let s = &mut this.scm; s.refreshing = false; + if s.is_busy() { + s.again = true; + return; + } + let snap = match snap { + Ok(snap) => snap, + Err(error) => { + s.repo_error = Some(error); + cx.notify(); + if s.again { + this.scm_refresh(cx); + } + return; + } + }; + s.repo_error = None; let mut marks = HashMap::new(); let mut dirty_dirs = HashSet::new(); if let Some(repo) = &snap.repo { - for ch in snap.status.changes.iter().chain(&snap.status.staged).chain(&snap.status.conflicts) { - let full = repo.join(ch.path.replace('/', "\\")); - let key = full.to_string_lossy().to_lowercase(); - marks.entry(key).or_insert(ch.code); + for (ch, mark) in snap + .status + .changes + .iter() + .chain(&snap.status.untracked) + .chain(&snap.status.staged) + .map(|ch| (ch, ch.code)) + .chain(snap.status.conflicts.iter().map(|ch| (ch, '!'))) + { + let full = repo.join(&ch.path); + let key = |path: &std::path::Path| path.to_string_lossy().replace('/', "\\").to_lowercase(); + marks.entry(key(&full)).or_insert(mark); let mut p = full.parent(); while let Some(d) = p { if !d.starts_with(repo) { break; } - dirty_dirs.insert(d.to_string_lossy().to_lowercase()); + dirty_dirs.insert(key(d)); p = d.parent(); } } } s.marks = Rc::new(marks); s.dirty_dirs = Rc::new(dirty_dirs); + if s.repo != snap.repo { + s.log.clear(); + s.commit_open = None; + s.commit_files.clear(); + s.confirm_discard = None; + } s.repo = snap.repo; s.status = snap.status; if let Some(log) = snap.log { @@ -450,13 +566,35 @@ impl Workbench { .detach(); } + fn scm_has_dirty_repo_docs(&self) -> bool { + let Some(repo) = self.scm.repo.as_deref() else { + return false; + }; + self.docs.iter().any(|d| { + d.dirty + && !d.read_only + && !d.flux_lazy + && d.image.is_none() + && d.diff.is_none() + && d.editor.is_some() + && crate::panel::path_in_repo(repo, &d.path) + }) + } + pub(crate) fn scm_run(&mut self, label: &str, steps: Vec, cx: &mut Context, done: impl FnOnce(&mut Self, &str, &mut Context) + 'static) { let Some(dir) = self.scm.repo.clone().or_else(|| self.root.clone()) else { return }; - if self.scm.busy.is_some() { + if self.scm.is_busy() { self.status = tr("Source Control is busy, try again in a moment").into(); cx.notify(); return; } + let reload = steps.iter().any(|step| { + matches!( + step, + Step::Remote(RemoteAction::Pull | RemoteAction::Sync) | Step::Resolve { .. } + ) + }); + let generation = self.scm.workspace_generation; self.scm.busy = Some(label.to_string().into()); self.scm.error = None; self.scm.note = None; @@ -468,10 +606,10 @@ impl Workbench { .background_spawn(async move { let mut saved = Vec::new(); let mut last = String::new(); - for s in &steps { - match run_step(&dir, s, wsl.as_ref()) { + for step in &steps { + match run_step(&dir, step, wsl.as_ref()) { Ok(out) => { - if let Step::Save { path, gen, .. } = s { + if let Step::Save { path, gen, .. } = step { saved.push((path.clone(), *gen)); } last = out; @@ -483,11 +621,16 @@ impl Workbench { }) .await; _ = this.update(cx, |this, cx| { + if this.scm.workspace_generation != generation { + return; + } for (path, gen) in saved { - if let Some(d) = this.docs.iter_mut().find(|d| d.path == path) { - if d.gen == gen { - d.dirty = false; - } + if let Some(d) = this + .docs + .iter_mut() + .find(|d| crate::panel::same_path(&d.path, &path) && d.gen == gen) + { + d.dirty = false; } } this.scm.busy = None; @@ -505,6 +648,15 @@ impl Workbench { } } } + if reload { + this.agent.reloads.extend( + this.docs + .iter() + .filter(|d| !d.dirty && d.diff.as_ref().is_none_or(|x| !x.virtual_tab)) + .map(|d| d.path.clone()), + ); + this.refresh_tree(cx); + } this.scm_refresh(cx); cx.notify(); }); @@ -512,90 +664,90 @@ impl Workbench { .detach(); } - fn push_steps(&self) -> Vec { - if self.scm.status.upstream.is_some() { - vec![git_step(&["push"])] - } else { - vec![git_step(&["push", "-u", "origin", "HEAD"])] - } + pub(crate) fn scm_commit(&mut self, after: After, amend: bool, window: &mut Window, cx: &mut Context) { + self.scm_commit_with_options(after, amend, false, window, cx); } - pub(crate) fn scm_commit(&mut self, after: After, amend: bool, window: &mut Window, cx: &mut Context) { + fn scm_commit_with_options(&mut self, after: After, amend: bool, signoff: bool, window: &mut Window, cx: &mut Context) { let msg = self.scm.message.read(cx).value().trim().to_string(); - let st = self.scm.status.clone(); - if !st.conflicts.is_empty() { - self.scm.error = Some("Resolve the merge conflicts first (files marked !).".into()); - cx.notify(); - return; - } - if msg.is_empty() && !amend { - self.scm.error = Some("Type a commit message first.".into()); - let h = self.scm.message.focus_handle(cx); - h.focus(window, cx); - cx.notify(); - return; - } - if st.staged.is_empty() && st.changes.is_empty() && !amend { - self.scm.error = Some("There are no changes to commit.".into()); - cx.notify(); + let has_dirty_docs = self.scm_has_dirty_repo_docs(); + let smart_all = match self.scm.status.check_smart_commit(&msg, amend, has_dirty_docs) { + Ok(v) => v, + Err(key) => { + self.scm.error = Some(tr(key).to_string()); + if msg.is_empty() { + self.scm.message.focus_handle(cx).focus(window, cx); + } + cx.notify(); + return; + } + }; + if after != After::Nothing && !self.scm_can_push(cx) { return; } let mut steps = Vec::new(); - for d in &self.docs { - if !d.dirty || d.image.is_some() || d.read_only || d.flux_lazy { - continue; - } - if let Some(ed) = d.editor.as_ref() { - steps.push(Step::Save { - path: d.path.clone(), - gen: d.gen, - text: ed.read(cx).value().to_string(), - crlf: d.crlf, - nbt: d.nbt_format, - }); + if let Some(repo) = self.scm.repo.as_deref() { + for d in &self.docs { + if !d.dirty + || d.read_only + || d.flux_lazy + || d.image.is_some() + || d.diff.is_some() + || !crate::panel::path_in_repo(repo, &d.path) + { + continue; + } + if let Some(ed) = d.editor.as_ref() { + steps.push(Step::Save { + path: d.path.clone(), + gen: d.gen, + text: ed.read(cx).value().to_string(), + crlf: d.crlf, + nbt: d.nbt_format, + }); + } } } - if st.staged.is_empty() && !amend { - steps.push(git_step(&["add", "-A"])); // smart commit - } - let mut args: Vec = vec!["commit".into(), "--quiet".into()]; - if amend { - args.push("--amend".into()); - } - if msg.is_empty() { - args.push("--no-edit".into()); - steps.push(Step::Git(args, None)); - } else { - args.extend(["--file".into(), "-".into()]); - steps.push(Step::Git(args, Some(msg))); + if smart_all { + steps.push(git_step(&["add", "-A"])); } + steps.push(Step::Commit { + message: msg.clone(), + amend, + signoff, + }); + self.scm_run(tr("Committing…"), steps, cx, move |this, _, cx| { + if this.scm.message.read(cx).value().trim() == msg { + this.scm.clear_message = true; + } + this.status = tr("Committed").into(); + this.scm_after_commit(after, cx); + }); + } + + fn scm_after_commit(&mut self, after: After, cx: &mut Context) { match after { After::Nothing => {} - After::Push => steps.extend(self.push_steps()), - After::Sync => { - steps.push(git_step(&["pull", "--autostash"])); - steps.extend(self.push_steps()); - } + After::Push => self.scm_run(tr("Pushing…"), vec![Step::Remote(RemoteAction::Push)], cx, |this, _, _| { + this.status = tr("Committed and pushed").into(); + }), + After::Sync => self.scm_sync(cx), } - let label = match after { - After::Nothing => "Committing…", - After::Push => "Committing and pushing…", - After::Sync => "Committing and syncing…", - }; - self.scm_run(label, steps, cx, move |this, _, _| { - this.scm.clear_message = true; - this.status = match after { - After::Nothing => "Committed".into(), - After::Push => "Committed and pushed".into(), - After::Sync => "Committed and synced".into(), - }; - }); + } + + fn scm_can_push(&mut self, cx: &mut Context) -> bool { + if self.scm.status.branch.is_some() { + return true; + } + self.scm.error = Some(tr("Switch to a branch before pushing or syncing.").to_string()); + cx.notify(); + false } pub(crate) fn scm_sync(&mut self, cx: &mut Context) { - let mut steps = vec![git_step(&["pull", "--autostash"])]; - steps.extend(self.push_steps()); - self.scm_run("Syncing…", steps, cx, |this, _, _| this.status = tr("Synced with the remote").into()); + self.scm_run(tr("Syncing…"), vec![Step::Remote(RemoteAction::Sync)], cx, |this, _, _| { + this.status = tr("Synced with the remote").into(); + }); } fn scm_create_pr(&mut self, cx: &mut Context) { @@ -604,7 +756,7 @@ impl Workbench { cx.notify(); return; } - let mut steps = self.push_steps(); + let mut steps = vec![Step::Remote(RemoteAction::Push)]; steps.push(Step::Gh(vec!["pr".into(), "create".into(), "--fill".into()])); self.scm_run("Creating pull request…", steps, cx, |this, out, _| { let url = find_url(out); @@ -619,6 +771,8 @@ impl Workbench { cx.notify(); return; } + let generation = self.scm.workspace_generation; + let dir_guard = dir.clone(); let wsl = self.wsl.clone(); cx.spawn(async move |this, cx| { let (wf, runs) = cx @@ -633,6 +787,9 @@ impl Workbench { }) .await; _ = this.update(cx, |this, cx| { + if this.scm.workspace_generation != generation || this.scm.repo.as_ref() != Some(&dir_guard) { + return; + } this.scm.actions_loaded = true; let s = |v: &serde_json::Value, k: &str| v.get(k).map(|x| x.as_str().map(String::from).unwrap_or_else(|| x.to_string())).unwrap_or_default(); match wf.and_then(|t| serde_json::from_str::>(&t).map_err(|e| e.to_string())) { @@ -684,122 +841,335 @@ impl Workbench { }); } - fn scm_stage(&mut self, path: Option, stage: bool, cx: &mut Context) { - let step = match (stage, path) { - (true, Some(p)) => Step::Git(vec!["add".into(), "--".into(), p], None), - (true, None) => git_step(&["add", "-A"]), - (false, Some(p)) => Step::Git(vec!["restore".into(), "--staged".into(), "--".into(), p], None), - (false, None) => git_step(&["restore", "--staged", "."]), + pub(crate) fn scm_paths( + &mut self, + group: Group, + path: Option, + discard: bool, + cx: &mut Context, + ) { + let Some(repo) = self.scm.repo.as_ref() else { + return; }; - self.scm_run(if stage { "Staging…" } else { "Unstaging…" }, vec![step], cx, |_, _, _| {}); - } - - fn scm_discard(&mut self, ch: FileChange, cx: &mut Context) { - if self.scm.confirm_discard.as_deref() != Some(ch.path.as_str()) { - self.scm.confirm_discard = Some(ch.path.clone()); - cx.notify(); + if self.scm.is_busy() { return; } - if ch.code == 'U' { - if let Some(repo) = &self.scm.repo { - let full = repo.join(ch.path.replace('/', "\\")); - if let Err(e) = crate::core::delete_path(&full) { - self.scm.error = Some(e); - } - } - self.scm.confirm_discard = None; - self.refresh_tree(cx); - self.scm_refresh(cx); + let files: Vec<_> = self + .scm + .status + .files(group) + .iter() + .filter(|file| path.as_ref().is_none_or(|path| *path == file.path)) + .cloned() + .collect(); + if files.is_empty() { return; } - let path = ch.path.clone(); - self.scm_run("Discarding…", vec![Step::Git(vec!["restore".into(), "--".into(), path], None)], cx, |this, _, cx| { - this.agent.reloads.extend(this.docs.iter().map(|d| d.path.clone())); - cx.notify(); - }); + if discard { + let selection = (group, path, files.clone()); + if self.scm.confirm_discard.as_ref() != Some(&selection) { + self.scm.confirm_discard = Some(selection); + cx.notify(); + return; + } + if crate::scm_git::file_paths(&files).iter().any(|p| { + let full = repo.join(p); + self.docs.iter().any(|doc| doc.dirty && crate::panel::same_path(&doc.path, &full)) + }) { + self.scm.error = + Some(tr("Save or close the modified editor before discarding.").to_string()); + cx.notify(); + return; + } + } + let label = if discard { + tr("Discarding…") + } else if group == Group::Staged { + tr("Unstaging…") + } else { + tr("Staging…") + }; + self.scm_run( + label, + vec![Step::Paths { + group, + files, + discard, + }], + cx, + move |this, _, cx| { + if discard { + this.agent.reloads.extend( + this.docs + .iter() + .filter(|doc| !doc.dirty && doc.diff.as_ref().is_none_or(|x| !x.virtual_tab)) + .map(|doc| doc.path.clone()), + ); + this.refresh_tree(cx); + } + }, + ); } - fn scm_show_diff(&mut self, ch: FileChange, staged: bool, cx: &mut Context) { - let Some(dir) = self.scm.repo.clone() else { return }; - let mut args = vec!["-c".to_string(), "core.quotepath=off".into(), "diff".into()]; - if staged { - args.push("--cached".into()); + fn scm_diff_key(repo: &std::path::Path, group: Group, path: &str) -> PathBuf { + PathBuf::from(format!( + "flux-diff://{}/{}/{}", + repo.display(), + group as u8, + path + )) + } + + fn scm_show_diff( + &mut self, + ch: FileChange, + group: Group, + window: &mut Window, + cx: &mut Context, + ) { + let Some(repo) = self.scm.repo.clone() else { + return; + }; + let generation = self.scm.workspace_generation; + let file_name = ch.path.rsplit('/').next().unwrap_or(&ch.path).to_string(); + let badge = match group { + Group::Staged => tr("Index"), + Group::Conflicts => tr("Conflict"), + Group::Changes | Group::Untracked => tr("Working Tree"), + }; + let virtual_key = Self::scm_diff_key(&repo, group, &ch.path); + let wsl = self.wsl.clone(); + cx.spawn_in(window, async move |this, cx| { + let dir = repo.clone(); + let file = ch.clone(); + let result = cx + .background_spawn(async move { + crate::scm_git::file_diff(&dir, &file, group, wsl.as_ref()) + }) + .await; + _ = this.update_in(cx, |this, window, cx| { + if this.scm.workspace_generation != generation + || this.scm.repo.as_ref() != Some(&repo) + { + return; + } + let (patch, conflict_text, target) = match result { + Ok(diff) => diff, + Err(error) => { + this.scm.error = Some(error); + cx.notify(); + return; + } + }; + this.open_scm_diff_tab( + crate::diff_view::ScmDiffSpec { + virtual_key, + tab_title: format!("{file_name} ({badge})"), + display_name: ch.path.clone(), + badge: badge.to_string(), + patch, + conflict_text, + target, + scm_stage: Some((repo, ch.path, group)), + multi_file: false, + }, + window, + cx, + ); + }); + }) + .detach(); + } + + fn scm_toggle_commit(&mut self, hash: String, cx: &mut Context) { + if self.scm.commit_open.as_deref() == Some(hash.as_str()) { + self.scm.commit_open = None; + return cx.notify(); + } + self.scm.commit_open = Some(hash.clone()); + cx.notify(); + if self.scm.commit_files.contains_key(&hash) { + return; } - args.extend(["--".into(), ch.path.clone()]); - let untracked = ch.code == 'U'; - let path = ch.path.clone(); + let Some(dir) = self.scm.repo.clone() else { return }; + let generation = self.scm.workspace_generation; + let dir_guard = dir.clone(); let wsl = self.wsl.clone(); cx.spawn(async move |this, cx| { - let text = cx + let h = hash.clone(); + let result = cx .background_spawn(async move { - if untracked { - std::fs::read_to_string(dir.join(&path)).map(|t| t.lines().map(|l| format!("+{l}")).collect::>().join("\n")).unwrap_or_default() - } else { - run_step(&dir, &Step::Git(args, None), wsl.as_ref()).unwrap_or_else(|e| e) - } + run_step( + &dir, + &Step::Git( + [ + "-c", + "core.quotepath=off", + "show", + "--format=", + "--name-status", + "-m", + "--first-parent", + "-z", + &h, + ] + .map(String::from) + .to_vec(), + None, + ), + wsl.as_ref(), + ) + .map(|s| crate::scm_incoming::parse_name_status(&s)) }) .await; _ = this.update(cx, |this, cx| { - this.out_lines.clear(); - let mut head = Line::new(&ch.path, crate::term::LineKind::Cmd); - head.meta = if staged { "Staged diff".into() } else { "Diff".into() }; - this.out_lines.push(head); - for l in text.lines() { - let kind = if l.starts_with("+++") || l.starts_with("---") || l.starts_with("diff ") || l.starts_with("index ") { - crate::term::LineKind::Dim - } else if l.starts_with('+') { - crate::term::LineKind::Success - } else if l.starts_with('-') { - crate::term::LineKind::Err - } else if l.starts_with("@@") { - crate::term::LineKind::Hunk - } else { - crate::term::LineKind::Normal - }; - this.out_lines.push(Line::new(l, kind)); + if this.scm.workspace_generation != generation + || this.scm.repo.as_ref() != Some(&dir_guard) + { + return; } - if text.trim().is_empty() { - push_line(&mut this.out_lines, "No textual changes (binary file or mode change).", crate::term::LineKind::Dim); + match result { + Ok(files) => { + this.scm.commit_files.insert(hash, files); + } + Err(e) => { + if this.scm.commit_open.as_deref() == Some(hash.as_str()) { + this.scm.commit_open = None; + } + this.scm.error = Some(e); + } } - this.panel_open = true; - this.panel_tab = PanelTab::Output; - this.out_scroll.scroll_to_item(0, ScrollStrategy::Top); cx.notify(); }); }) .detach(); } - fn scm_show_commit(&mut self, hash: String, cx: &mut Context) { + pub(crate) fn scm_show_commit_file( + &mut self, + hash: String, + short: String, + path: String, + window: &mut Window, + cx: &mut Context, + ) { let Some(dir) = self.scm.repo.clone() else { return }; + let generation = self.scm.workspace_generation; + let dir_guard = dir.clone(); let wsl = self.wsl.clone(); - cx.spawn(async move |this, cx| { - let text = cx + let file_name = path.rsplit('/').next().unwrap_or(&path).to_string(); + let full_path = dir.join(&path); + let target = if wsl.is_some() || full_path.is_file() { + Some(full_path) + } else { + None + }; + let virtual_key = PathBuf::from(format!("flux-diff://commit/{hash}/{path}")); + let p_bg = path.clone(); + cx.spawn_in(window, async move |this, cx| { + let result = cx .background_spawn(async move { - run_step(&dir, &Step::Git(["show", "--stat", "--format=%h %s%n%an <%ae>, %ad%n%n%b", "--date=format:%Y-%m-%d %H:%M", &hash].map(String::from).to_vec(), None), wsl.as_ref()) - .unwrap_or_else(|e| e) + crate::scm_git::show_commit_diff(&dir, &hash, Some(&p_bg), true, wsl.as_ref()) }) .await; - _ = this.update(cx, |this, cx| { - this.out_lines.clear(); - for (i, l) in text.lines().enumerate() { - let kind = if i == 0 { - crate::term::LineKind::Code - } else if l.contains(" | ") || l.contains("changed,") { - crate::term::LineKind::Normal - } else { - crate::term::LineKind::Dim - }; - push_line(&mut this.out_lines, l, kind); + _ = this.update_in(cx, |this, window, cx| { + if this.scm.workspace_generation != generation + || this.scm.repo.as_ref() != Some(&dir_guard) + { + return; } - this.panel_open = true; - this.panel_tab = PanelTab::Output; - cx.notify(); + let patch = match result { + Ok(patch) => patch, + Err(e) => { + this.scm.error = Some(e); + cx.notify(); + return; + } + }; + this.open_scm_diff_tab( + crate::diff_view::ScmDiffSpec { + virtual_key, + tab_title: format!("{file_name} ({short})"), + display_name: path, + badge: short, + patch, + conflict_text: None, + target, + scm_stage: None, + multi_file: false, + }, + window, + cx, + ); + }); + }) + .detach(); + } + + fn scm_show_commit_all( + &mut self, + hash: String, + short: String, + subject: String, + window: &mut Window, + cx: &mut Context, + ) { + let Some(dir) = self.scm.repo.clone() else { + return; + }; + let generation = self.scm.workspace_generation; + let dir_guard = dir.clone(); + let wsl = self.wsl.clone(); + let virtual_key = PathBuf::from(format!("flux-diff://commit/{hash}")); + cx.spawn_in(window, async move |this, cx| { + let result = cx + .background_spawn(async move { + crate::scm_git::show_commit_diff(&dir, &hash, None, true, wsl.as_ref()) + }) + .await; + _ = this.update_in(cx, |this, window, cx| { + if this.scm.workspace_generation != generation + || this.scm.repo.as_ref() != Some(&dir_guard) + { + return; + } + let patch = match result { + Ok(patch) => patch, + Err(e) => { + this.scm.error = Some(e); + cx.notify(); + return; + } + }; + this.open_scm_diff_tab( + crate::diff_view::ScmDiffSpec { + virtual_key, + tab_title: format!("{short} · {subject}"), + display_name: subject, + badge: short, + patch, + conflict_text: None, + target: None, + scm_stage: None, + multi_file: true, + }, + window, + cx, + ); }); }) .detach(); } + pub(crate) fn scm_drag_pane(&mut self, y: f32) { + let Some(drag) = self.scm.pane_drag.as_ref() else { + return; + }; + for (id, h) in apply_sash_drag(drag, y) { + self.scm.pane_h[id as usize] = Some(h); + } + } + pub(crate) fn render_scm(&self, cx: &mut Context) -> AnyElement { let s = &self.scm; @@ -807,52 +1177,97 @@ impl Workbench { return div().p_3().text_sm().text_color(c(theme::FG_DIM)).child(tr("Open a folder to use Source Control.")).into_any_element(); } if s.repo.is_none() { + let status = if s.refreshing || s.last_refresh.is_none() { + tr("Checking for a Git repository…") + } else { + tr("This folder is not a Git repository.") + }; return v_flex() .p_3() .gap_3() .text_sm() - .child(div().text_color(c(theme::FG_MUTED)).child(tr("This folder is not a Git repository."))) .child( - Button::new("scm-init").label(tr("Initialize Repository")).primary().small().w_full().on_click(cx.listener(|this, _, _, cx| { - let dir = this.root.clone(); - this.scm.repo = dir; - this.scm_run("Initializing…", vec![git_step(&["init"])], cx, |this, _, _| this.status = tr("Git repository created").into()); - })), + div() + .text_color(c(theme::FG_MUTED)) + .child(s.repo_error.clone().unwrap_or_else(|| status.to_string())), ) + .when(!s.refreshing && s.repo_error.is_none(), |v| { + v.child( + Button::new("scm-init") + .label(tr("Initialize Repository")) + .primary() + .small() + .w_full() + .disabled(s.is_busy()) + .on_click(cx.listener(|this, _, _, cx| { + this.scm_run( + tr("Initializing…"), + vec![git_step(&["init"])], + cx, + |this, _, _| { + this.status = tr("Git repository created").into(); + }, + ); + })), + ) + }) + .when_some(s.busy.clone().or_else(|| s.fetching.then(|| tr("Fetching…").into())), |v, status| { + v.child(div().text_xs().child(status)) + }) + .when_some(s.error.clone(), |v, error| { + v.child(div().text_color(c(theme::DANGER)).child(error)) + }) .into_any_element(); } let st = &s.status; - let branch = st.branch.clone().unwrap_or_else(|| "detached HEAD".into()); - let nothing_staged = st.staged.is_empty(); - let commit_label = match (nothing_staged, st.count()) { - (_, 0) => "Commit".to_string(), - (true, _) => "Commit All".to_string(), - (false, _) => "Commit".to_string(), - }; - + let has_dirty_docs = self.scm_has_dirty_repo_docs(); + let smart_all = st.staged.is_empty() + && (!st.changes.is_empty() || !st.untracked.is_empty() || has_dirty_docs); + let can_commit = !s.is_busy() + && st + .check_smart_commit(&s.message.read(cx).value(), false, has_dirty_docs) + .is_ok(); let commit_row = h_flex() .w_full() + .gap_px() .child( Button::new("scm-commit") .icon(Icon::new(IconName::Check)) - .label(commit_label) + .label(if smart_all { + tr("Commit All") + } else { + tr("Commit") + }) + .disabled(!can_commit) .primary() .small() .flex_1() - .tooltip(if nothing_staged { "Nothing is staged, so every change is committed (like VS Code's smart commit)" } else { "Commit the staged changes" }) - .on_click(cx.listener(|this, _, w, cx| this.scm_commit(After::Nothing, false, w, cx))), + .tooltip(if smart_all { + tr("Stage everything and commit") + } else { + tr("Commit the staged changes (Enter)") + }) + .on_click( + cx.listener(|this, _, w, cx| this.scm_commit(After::Nothing, false, w, cx)), + ), ) .child( - Button::new("scm-commit-more").icon(Icon::new(IconName::ChevronDown)).primary().small().dropdown_menu(|m: PopupMenu, _, _| { - m.min_w(px(220.)) - .menu(tr("Commit & Push"), Box::new(ScmCommitPush)) - .menu(tr("Commit & Sync"), Box::new(ScmCommitSync)) - .separator() - .menu(tr("Commit (Amend)"), Box::new(ScmCommitAmend)) - }), + Button::new("scm-commit-more") + .icon(Icon::new(IconName::ChevronDown)) + .disabled(s.is_busy()) + .primary() + .small() + .dropdown_menu(|m: PopupMenu, _, _| { + m.min_w(px(220.)) + .menu(tr("Commit & Push"), Box::new(ScmCommitPush)) + .menu(tr("Commit & Sync"), Box::new(ScmCommitSync)) + .separator() + .menu(tr("Commit (Amend)"), Box::new(ScmCommitAmend)) + .menu(tr("Commit (Sign Off)"), Box::new(ScmCommitSignoff)) + }), ); - let mut body = v_flex().id("scm-body").flex_1().min_h_0().overflow_y_scroll().pb_2(); + let mut top = v_flex().w_full().min_w_0().flex_none().pt_1p5(); if s.confirm_uninit { let home = std::env::var("USERPROFILE").unwrap_or_default(); let mut where_: String = s.repo.as_ref().map(|r| r.display().to_string()).unwrap_or_default(); @@ -861,10 +1276,11 @@ impl Workbench { where_ = format!("~{}", &where_[home.len()..]); } let folder = s.repo.as_ref().and_then(|r| r.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - body = body.child( + top = top.child( v_flex() .flex_none() - .mx_3() + .ml_3() + .mr(px(SCROLLBAR_PAD)) .mb_2() .p_2() .gap_2() @@ -895,18 +1311,33 @@ impl Workbench { ); } if let Some(card) = self.render_scm_incoming(cx) { - body = body.child(card); + let incoming_el: AnyElement = if s.incoming_shown { + div() + .w_full() + .min_w_0() + .max_h(theme::u(180.)) + .overflow_y_scrollbar() + .id("scm-in-scroll") + .scroll_bounce(false) + .child(card) + .into_any_element() + } else { + card + }; + top = top.child(incoming_el); } - body = body.child( + top = top.child( v_flex() + .w_full() + .min_w_0() .flex_none() .px_3() .pb_2() - .gap_2() - .child(crate::ui::McInput::new(&s.message).small()) + .gap_1p5() + .child(div().key_context("ScmMessage").child(crate::ui::McInput::new(&s.message).small())) .child(commit_row) - .when_some(s.busy.clone(), |v, b| v.child(div().text_xs().text_color(c(theme::BLUE)).child(b))) - .when_some(s.error.clone(), |v, e| { + .when_some(s.busy.clone().or_else(|| s.fetching.then(|| tr("Fetching…").into())), |v, b| v.child(div().text_xs().text_color(c(theme::BLUE)).child(b))) + .when_some(s.error.clone().or_else(|| s.repo_error.clone()), |v, e| { v.child( div() .p_2() @@ -942,11 +1373,74 @@ impl Workbench { }), ); + if let Some((group, path, files)) = &s.confirm_discard { + let group = *group; + let path = path.clone(); + let detail = path.clone().unwrap_or_else(|| { + if files.len() == 1 { + files[0].path.clone() + } else { + crate::trf!("Discard {n} files in {group}?"; n => files.len(), group => group_title(group)).to_string() + } + }); + top = top.child( + v_flex() + .mx_3() + .mb_2() + .p_2() + .gap_1() + .border_1() + .border_color(c(theme::BORDER)) + .text_xs() + .child(div().text_color(c(theme::FG_STRONG)).child(detail)) + .child(div().text_color(c(theme::FG_MUTED)).child(match group { + Group::Untracked => tr("Untracked files will be deleted."), + Group::Staged if st.head.is_none() => { + tr("Remove these files from the index and working tree.") + } + Group::Staged => { + tr("Restore the index and working tree to the last commit.") + } + Group::Conflicts => { + tr("Restore the original merge conflict in the working tree.") + } + Group::Changes => tr("Restore the working tree from the index."), + })) + .child( + h_flex() + .gap_2() + .child( + Button::new("scm-discard-yes") + .label(tr("Discard")) + .danger() + .xsmall() + .on_click(cx.listener(move |this, _, _, cx| { + this.scm_paths(group, path.clone(), true, cx) + })), + ) + .child( + Button::new("scm-discard-no") + .label(tr("Cancel")) + .ghost() + .xsmall() + .on_click(cx.listener(|this, _, _, cx| { + this.scm.confirm_discard = None; + cx.notify(); + })), + ), + ), + ); + } + let section = |id: &'static str, title: String, count: usize, open: bool| { scm_row() .id(id) - .px_2() + .pl_2() + .pr(px(SCROLLBAR_PAD)) .gap_1() + .items_center() + .cursor_pointer() + .hover(|s| s.bg(c(theme::BG_HOVER))) .text_xs() .font_weight(FontWeight::SEMIBOLD) .text_color(c(theme::FG_MUTED)) @@ -965,40 +1459,51 @@ impl Workbench { div() .flex_none() .px_1p5() - .rounded_full() - .bg(c(theme::BG_HOVER)) + .rounded(px(8.)) + .bg(c(theme::BG_ELEVATED)) .text_color(c(theme::FG)) .child(count.to_string()), ) }) }; + let active_doc_path = self + .active + .and_then(|i| self.docs.get(i)) + .map(|d| d.path.clone()); let file_row = - |i: usize, kind: u8, ch: &FileChange, this: &Self, cx: &mut Context| { + |i: usize, depth: usize, group: Group, ch: &FileChange, this: &Self, cx: &mut Context| { + let kind = group as u8; let name = ch.path.rsplit('/').next().unwrap_or(&ch.path).to_string(); - let dir = ch - .path - .rsplit_once('/') - .map(|d| d.0.replace('/', "\\")) - .unwrap_or_default(); - let col = code_color(ch.code); + let dir = if this.scm.show_tree { + String::new() + } else { + ch.path.rsplit_once('/').map(|(parent, _)| parent.to_string()).unwrap_or_default() + }; + let col = if group == Group::Conflicts { + theme::DANGER + } else { + code_color(ch.code) + }; let deleted = ch.code == 'D'; - let full = this - .scm - .repo - .as_ref() - .map(|r| r.join(ch.path.replace('/', "\\"))); + let full = this.scm.repo.as_ref().map(|r| r.join(&ch.path)); let staged = kind == 1; - let confirm = this.scm.confirm_discard.as_deref() == Some(ch.path.as_str()); - let (c1, c2, c3) = (ch.clone(), ch.clone(), ch.clone()); + let busy = this.scm.is_busy(); + let is_active = this.scm.repo.as_ref().is_some_and(|repo| { + active_doc_path.as_ref() == Some(&Self::scm_diff_key(repo, group, &ch.path)) + }); + let (ch_click, discard_path, full_open) = (ch.clone(), ch.path.clone(), full); scm_row() .id(("scm-f", i * 4 + kind as usize)) .group("scm-row") - .pl(theme::u(18.)) - .pr_2() + .relative() + .pl(theme::u(22. + depth.min(12) as f32 * 12.)) + .pr(px(SCROLLBAR_PAD)) .gap_1p5() - .text_size(theme::u(11.5)) + .items_center() + .text_size(theme::u(13.)) .cursor_pointer() + .when(is_active, |h| h.bg(c(theme::SELECT))) .hover(|s| s.bg(c(theme::BG_HOVER))) .child(crate::files::file_icon_el(&name, theme::u(14.))) .child( @@ -1006,7 +1511,7 @@ impl Workbench { .flex_shrink(1.) .min_w_0() .truncate() - .text_color(c(col)) + .text_color(c(theme::FG)) .when(deleted, |d| d.line_through()) .child(name), ) @@ -1020,49 +1525,58 @@ impl Workbench { .child(dir), ) .child( - h_flex() + div() .flex_none() + .w(theme::u(12.)) + .text_right() + .text_xs() + .font_weight(FontWeight::BOLD) + .text_color(c(col)) + .child(ch.code.to_string()), + ) + // Overlay actions on hover so unhovered rows use the full width for filename and path. + .child( + h_flex() + .absolute() + .top_0() + .bottom_0() + .right(px(SCROLLBAR_PAD) + theme::u(14.)) + .items_center() .gap_px() + .pl_1p5() + .pr_0p5() + .bg(c(theme::BG_HOVER)) .invisible() .group_hover("scm-row", |s| s.visible()) - .when(!staged && kind != 2, |h| { - h.child( - Button::new(("scm-diff", i)) - .icon(Icon::new(Ico::FileDiff)) - .ghost() - .xsmall() - .tooltip(tr("Show changes")) - .on_click(cx.listener(move |this, _, _, cx| { - cx.stop_propagation(); - this.scm_show_diff(c1.clone(), false, cx); - })), - ) - .child( - Button::new(("scm-discard", i)) - .icon(Icon::new(Ico::Undo2)) - .ghost() - .xsmall() - .when(confirm, |b| b.label(tr("Discard?"))) - .tooltip(tr("Discard changes (click twice)")) - .on_click(cx.listener(move |this, _, _, cx| { - cx.stop_propagation(); - this.scm_discard(c2.clone(), cx); - })), - ) - }) - .when(staged, |h| { + .when(!deleted, |h| { h.child( - Button::new(("scm-sdiff", i)) - .icon(Icon::new(Ico::FileDiff)) + Button::new(("scm-open", i * 4 + kind as usize)) + .icon(Icon::new(Ico::FileCode)) .ghost() .xsmall() - .tooltip(tr("Show staged changes")) - .on_click(cx.listener(move |this, _, _, cx| { + .tooltip(tr("Open file")) + .on_click(cx.listener(move |this, _, w, cx| { cx.stop_propagation(); - this.scm_show_diff(c3.clone(), true, cx); + if let Some(f) = + full_open.clone().filter(|f| f.is_file()) + { + this.open_file(f, w, cx); + } })), ) }) + .child( + Button::new(("scm-discard", i * 4 + kind as usize)) + .icon(Icon::new(Ico::Undo2)) + .ghost() + .xsmall() + .disabled(busy) + .tooltip(tr("Discard")) + .on_click(cx.listener(move |this, _, _, cx| { + cx.stop_propagation(); + this.scm_paths(group, Some(discard_path.clone()), true, cx); + })), + ) .child({ let p = ch.path.clone(); Button::new(("scm-stage", i * 4 + kind as usize)) @@ -1073,308 +1587,845 @@ impl Workbench { })) .ghost() .xsmall() - .tooltip(if staged { "Unstage" } else { "Stage" }) + .disabled(busy) + .tooltip(if staged { tr("Unstage") } else { tr("Stage") }) .on_click(cx.listener(move |this, _, _, cx| { cx.stop_propagation(); - this.scm_stage(Some(p.clone()), !staged, cx); + this.scm_paths(group, Some(p.clone()), false, cx); })) }), ) - .child( - div() - .flex_none() - .w(theme::u(12.)) - .text_xs() - .font_weight(FontWeight::BOLD) - .text_color(c(col)) - .child(ch.code.to_string()), - ) .on_click(cx.listener(move |this, _, w, cx| { - if let Some(f) = full.clone().filter(|f| f.is_file()) { - this.open_file(f, w, cx); - } + this.scm_show_diff(ch_click.clone(), group, w, cx); })) }; - if !st.conflicts.is_empty() { - body = body.child(section("scm-sec-conf", "Merge Changes".into(), st.conflicts.len(), true)); - for (i, ch) in st.conflicts.iter().enumerate().take(MAX_ROWS) { - body = body.child(file_row(i, 2, ch, self, cx)); - } - } - if !st.staged.is_empty() { - body = body.child(section("scm-sec-staged", "Staged Changes".into(), st.staged.len(), true).child( - Button::new("scm-unstage-all").icon(Icon::new(IconName::Minus)).ghost().xsmall().tooltip(tr("Unstage All")).on_click(cx.listener(|this, _, _, cx| { - this.scm_stage(None, false, cx); - })), - )); - for (i, ch) in st.staged.iter().enumerate().take(MAX_ROWS) { - body = body.child(file_row(i, 1, ch, self, cx)); - } - body = body.children(more_rows(st.staged.len())); - } - body = body.child(section("scm-sec-changes", "Changes".into(), st.changes.len(), true).when(!st.changes.is_empty(), |h| { - h.child(Button::new("scm-stage-all").icon(Icon::new(IconName::Plus)).ghost().xsmall().tooltip(tr("Stage All")).on_click(cx.listener(|this, _, _, cx| { - this.scm_stage(None, true, cx); - }))) - })); - let untracked = st.changes.iter().filter(|c| c.code == 'U').count(); - if untracked > 200 { - let mut by: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); - for ch in st.changes.iter().filter(|c| c.code == 'U') { - if let Some((top, _)) = ch.path.split_once('/') { - *by.entry(top).or_default() += 1; - } - } - let mut top: Vec<(&str, usize)> = by.into_iter().collect(); - top.sort_by(|a, b| b.1.cmp(&a.1)); - body = body.child( - v_flex() - .flex_none() - .mx_3() - .my_1() - .p_2() - .gap_1() - .rounded(px(6.)) - .border_1() - .border_color(c(theme::BORDER)) - .bg(c(theme::BG_ELEVATED)) - .text_xs() - .child(div().text_color(c(theme::FG_STRONG)).child(crate::trf!("{n} untracked files"; n => untracked))) - .child(div().text_color(c(theme::FG_DIM)).child(tr("Folders with the most of them. Ignore the ones git should not track (they go to .gitignore)."))) - .children(top.into_iter().take(6).enumerate().map(|(i, (dir, n))| { - let pattern = format!("{dir}/"); - h_flex() - .flex_none() - .gap_2() - .h(theme::u(ROW_H)) - .child(Icon::new(IconName::Folder).size(theme::u(13.)).text_color(c(theme::FOLDER))) - .child(div().flex_1().min_w_0().truncate().text_color(c(theme::FG)).child(pattern.clone())) - .child(div().flex_none().text_color(c(theme::FG_DIM)).child(n.to_string())) - .child(Button::new(("scm-ignore", i)).label(tr("Ignore")).xsmall().on_click(cx.listener(move |this, _, _, cx| this.scm_ignore(pattern.clone(), cx)))) - })), - ); - } - for (i, ch) in st.changes.iter().enumerate().take(MAX_ROWS) { - body = body.child(file_row(i, 0, ch, self, cx)); - } - body = body.children(more_rows(st.changes.len())); - if st.count() == 0 { - body = body.child( - div() - .flex_none() - .px(theme::u(18.)) - .py_1() - .text_xs() - .text_color(c(theme::FG_DIM)) - .child(tr("No changes. The working tree matches the last commit.")), - ); + struct PaneBuilt { + spec: PaneSpec, + scroll_id: &'static str, + header: AnyElement, + rows: Option, } - let sync_label = match (&st.upstream, st.ahead, st.behind) { - (None, ..) => "Publish Branch".to_string(), - (Some(_), 0, 0) => "Up to date".to_string(), - (Some(_), a, b) => format!("Sync {b}↓ {a}↑"), + let row_h = f32::from(theme::u(ROW_H)); + let graph_h = row_h; + let header_h = row_h; + let flex_min = |natural: f32, unit: f32, min_rows: f32| { + (header_h + min_rows * unit).min(natural).max(header_h) }; - body = body.child( - h_flex() - .flex_none() - .px_3() - .pt_2() - .gap_1() - .child( - Button::new("scm-sync") - .icon(Icon::new(if st.upstream.is_none() { Ico::CloudUpload } else { Ico::RefreshCcw })) - .label(sync_label) - .tooltip(if st.upstream.is_none() { format!("Push {branch} to origin and track it") } else { format!("Pull, then push {branch}") }) - .small() - .flex_1() - .on_click(cx.listener(|this, _, _, cx| { - if this.scm.status.upstream.is_none() { - let steps = this.push_steps(); - this.scm_run("Publishing branch…", steps, cx, |this, _, _| this.status = tr("Branch published").into()); + let mut panes: Vec = Vec::with_capacity(6); + + for (group, pane, open, id) in [ + ( + Group::Conflicts, + ScmPane::Conflicts, + s.show_conflicts, + "scm-conflicts", + ), + (Group::Staged, ScmPane::Staged, s.show_staged, "scm-staged"), + ( + Group::Changes, + ScmPane::Changes, + s.show_changes, + "scm-changes", + ), + ( + Group::Untracked, + ScmPane::Untracked, + s.show_untracked, + "scm-untracked", + ), + ] { + if !s.show_changes_view { + break; + } + let files = st.files(group); + if files.is_empty() && !(group == Group::Changes && st.count() == 0) { + continue; + } + let staged = group == Group::Staged; + let hdr = section(id, group_title(group).into(), files.len(), open) + .pl_3() + .when(!files.is_empty(), |h| { + h.child( + Button::new(("scm-group-stage", group as usize)) + .icon(Icon::new(if staged { + IconName::Minus } else { - this.scm_sync(cx); + IconName::Plus + })) + .ghost() + .xsmall() + .disabled(s.is_busy()) + .tooltip(if staged { + tr("Unstage All") + } else { + tr("Stage All") + }) + .on_click(cx.listener(move |this, _, _, cx| { + cx.stop_propagation(); + this.scm_paths(group, None, false, cx); + })), + ) + .child( + Button::new(("scm-group-discard", group as usize)) + .icon(Icon::new(Ico::Undo2)) + .ghost() + .xsmall() + .disabled(s.is_busy()) + .tooltip(tr("Discard All")) + .on_click(cx.listener(move |this, _, _, cx| { + cx.stop_propagation(); + this.scm_paths(group, None, true, cx); + })), + ) + }) + .on_click(cx.listener(move |this, _, _, cx| { + let expanded = match group { + Group::Conflicts => &mut this.scm.show_conflicts, + Group::Staged => &mut this.scm.show_staged, + Group::Changes => &mut this.scm.show_changes, + Group::Untracked => &mut this.scm.show_untracked, + }; + *expanded = !*expanded; + cx.notify(); + })) + .into_any_element(); + let limit = s.row_limits[group as usize]; + let more = files.len().saturating_sub(limit).min(MAX_ROWS); + let displayed = &files[..files.len().min(limit)]; + let collapsed = &s.collapsed_folders[group as usize]; + let tree = (s.show_tree && open).then(|| change_tree_rows(displayed, collapsed)); + let rows_n = (tree.as_ref().map_or(displayed.len(), Vec::len) + usize::from(more > 0)).max(1); + let extra = if group == Group::Untracked && files.len() > MAX_ROWS { + 190. + } else { + 0. + }; + let natural_h = header_h + rows_n as f32 * row_h + extra; + let rows = open.then(|| { + let mut col = v_flex().w_full().min_w_0().pb_1(); + if group == Group::Untracked && files.len() > MAX_ROWS { + let mut by: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for ch in files { + if let Some((top, _)) = ch.path.split_once('/') { + *by.entry(top).or_default() += 1; + } + } + let mut top_dirs: Vec<(&str, usize)> = by.into_iter().collect(); + top_dirs.sort_by_key(|a| std::cmp::Reverse(a.1)); + col = col.child( + v_flex() + .flex_shrink_0() + .ml_3() + .mr(px(SCROLLBAR_PAD)) + .my_1() + .p_2() + .gap_1() + .rounded(px(6.)) + .border_1() + .border_color(c(theme::BORDER)) + .bg(c(theme::BG_ELEVATED)) + .text_xs() + .child(div().text_color(c(theme::FG_STRONG)).child(crate::trf!("{n} untracked files"; n => files.len()))) + .child(div().text_color(c(theme::FG_DIM)).child(tr("Folders with the most of them. Ignore the ones git should not track (they go to .gitignore)."))) + .children(top_dirs.into_iter().take(6).enumerate().map(|(i, (dir, n))| { + let pattern = format!("{dir}/"); + h_flex() + .gap_2() + .h(theme::u(ROW_H)) + .items_center() + .child(Icon::new(IconName::Folder).size(theme::u(13.)).text_color(c(theme::FOLDER))) + .child(div().flex_1().min_w_0().truncate().text_color(c(theme::FG)).child(pattern.clone())) + .child(div().flex_none().text_color(c(theme::FG_DIM)).child(n.to_string())) + .child(Button::new(("scm-ignore", i)).label(tr("Ignore")).xsmall().on_click(cx.listener(move |this, _, _, cx| this.scm_ignore(pattern.clone(), cx)))) + })), + ); + } + if let Some(tree) = tree { + for (row, entry) in tree.into_iter().enumerate() { + match entry { + ChangeTreeRow::File(i, depth) => { + col = col.child(file_row(i, depth, group, &displayed[i], self, cx)); } - })), - ) - .child( - Button::new("scm-pr") - .icon(Icon::new(Ico::GitPullRequest)) - .small() - .tooltip(tr("Create a pull request on GitHub (gh pr create --fill)")) - .on_click(cx.listener(|this, _, _, cx| this.scm_create_pr(cx))), - ), - ); + ChangeTreeRow::Folder(path, depth) => { + let expanded = !collapsed.contains(path); + let name = path.rsplit('/').next().unwrap_or(path).to_string(); + let path = path.to_string(); + col = col.child( + h_flex() + .id(("scm-folder", row * 4 + group as usize)) + .w_full() + .min_w_0() + .flex_none() + .h(theme::u(ROW_H)) + .pl(theme::u(10. + depth.min(12) as f32 * 12.)) + .pr(px(SCROLLBAR_PAD)) + .gap_1() + .cursor_pointer() + .hover(|h| h.bg(c(theme::BG_HOVER))) + .child(Icon::new(if expanded { IconName::ChevronDown } else { IconName::ChevronRight }).size(theme::u(12.))) + .child(Icon::new(IconName::Folder).size(theme::u(14.)).text_color(c(theme::FOLDER))) + .child(div().min_w_0().truncate().text_sm().child(name)) + .on_click(cx.listener(move |this, _, _, cx| { + let folders = &mut this.scm.collapsed_folders[group as usize]; + if !folders.remove(&path) { + folders.insert(path.clone()); + } + cx.notify(); + })), + ); + } + } + } + } else { + for (i, ch) in displayed.iter().enumerate() { + col = col.child(file_row(i, 0, group, ch, self, cx)); + } + } + if more > 0 { + col = col.child(Button::new(("scm-show-more", group as usize)).ghost().xsmall() + .label(crate::trf!("Show {n} more files"; n => more)) + .on_click(cx.listener(move |this, _, _, cx| { + this.scm.row_limits[group as usize] += more; + cx.notify(); + }))); + } + if files.is_empty() { + col = col.child(div().px(theme::u(18.)).py_1().text_xs().text_color(c(theme::FG_MUTED)).child(tr("No changes."))); + } + col.into_any_element() + }); + panes.push(PaneBuilt { + spec: PaneSpec { + id: pane, + flexible: open, + min_h: if open { + flex_min(natural_h, row_h, 2.) + } else { + header_h + }, + natural_h, + saved: s.pane_h[pane as usize], + }, + scroll_id: id, + header: hdr, + rows, + }); + } - body = body.child( - section("scm-sec-graph", "Graph".into(), 0, s.show_graph).mt_2().cursor_pointer().on_click(cx.listener(|this, _, _, cx| { - this.scm.show_graph = !this.scm.show_graph; - if this.scm.show_graph { - this.scm_refresh(cx); + { + let hdr = section("scm-sec-graph", tr("Graph").to_uppercase(), 0, s.show_graph) + .border_t_1() + .border_color(c(theme::BORDER)) + .on_click(cx.listener(|this, _, _, cx| { + this.scm.show_graph = !this.scm.show_graph; + if this.scm.show_graph { + this.scm_refresh(cx); + } + cx.notify(); + })) + .into_any_element(); + let open_extra = s + .commit_open + .as_ref() + .map(|h| { + (1 + s.commit_files.get(h).map(|f| f.len().min(60)).unwrap_or(1)) as f32 * row_h + }) + .unwrap_or(0.); + let natural = header_h + s.log.len().max(1) as f32 * graph_h + open_extra; + let flexible = s.show_graph; + let rows = flexible.then(|| { + let mut col = v_flex().w_full().min_w_0().pb_1(); + let n = s.log.len(); + if n == 0 { + col = col.child(div().flex_shrink_0().px(theme::u(18.)).py_1().text_xs().text_color(c(theme::FG_DIM)).child(tr("No commits yet."))); } - cx.notify(); - })), - ); - if s.show_graph { - let n = s.log.len(); - for (i, cm) in s.log.iter().enumerate() { - let hash = cm.hash.clone(); - let lane = graph_lane(i == 0, i + 1 == n, theme::ACCENT, 0.55, !cm.merge); - body = body.child( - scm_row() - .id(("scm-c", i)) - .pl(theme::u(12.)) - .pr_2() - .gap_1p5() - .text_size(theme::u(11.5)) - .cursor_pointer() - .hover(|s| s.bg(c(theme::BG_HOVER))) - .child(lane) + for (i, cm) in s.log.iter().enumerate() { + let hash = cm.hash.clone(); + let open = s.commit_open.as_deref() == Some(cm.hash.as_str()); + let (lane_top, lane_bottom, dot_top) = lane_geometry(i, n, open); + let line_col = if cm.is_head { theme::BLUE } else { theme::ACCENT }; + let badge = cm.refs.first().cloned(); + let has_refs = badge.is_some(); + let lane = div() + .relative() + .w(theme::u(14.)) + .h_full() + .flex_none() .child( div() - .flex_1() - .min_w_0() - .truncate() - .text_color(c(theme::FG)) - .child(cm.subject.clone()), + .absolute() + .left(theme::u(6.)) + .w(px(2.)) + .top(theme::u(lane_top)) + .bottom(theme::u(lane_bottom)) + .bg(c(line_col).opacity(0.6)), ) - .children(cm.refs.first().map(|r| { - let remote = r.starts_with("origin/"); + .child( div() - .flex_shrink(1.) - .min_w_0() - .max_w(theme::u(110.)) - .truncate() - .px_1p5() - .rounded(px(8.)) - .text_xs() - .bg(c(if remote { theme::BLUE } else { theme::ACCENT }).opacity(0.22)) - .text_color(c(if remote { theme::BLUE } else { theme::ACCENT_TEXT })) - .child(r.clone()) - })) - .when(cm.refs.len() > 1, |h| h.child(div().flex_none().text_xs().text_color(c(theme::FG_DIM)).child(format!("+{}", cm.refs.len() - 1)))) - .tooltip({ - let refs = if cm.refs.is_empty() { String::new() } else { format!("\n{}", cm.refs.join(", ")) }; - let tip = format!("{} {}\n{} · {}{refs}", cm.short, cm.subject, cm.author, cm.when); - move |w, cx| Tooltip::new(tip.clone()).build(w, cx) - }) - .on_click(cx.listener(move |this, _, _, cx| this.scm_show_commit(hash.clone(), cx))), - ); - } + .absolute() + .left(theme::u(3.)) + .top(theme::u(dot_top)) + .size(theme::u(8.)) + .rounded_full() + .border_2() + .border_color(c(line_col)) + .bg(if cm.is_head || !cm.merge { + c(line_col) + } else { + c(theme::BG_SIDE) + }), + ); + col = col.child( + h_flex() + .id(("scm-c", i)) + .w_full() + .min_w_0() + .flex_shrink_0() + .overflow_hidden() + .h(theme::u(ROW_H)) + .pl_3() + .pr(px(SCROLLBAR_PAD)) + .gap_1() + .items_center() + .text_size(theme::u(11.5)) + .cursor_pointer() + .when(open, |h| h.bg(c(theme::SELECT))) + .hover(|s| s.bg(c(theme::BG_HOVER))) + .child(lane) + .child( + h_flex() + .flex_1() + .min_w_0() + .overflow_hidden() + .gap_1p5() + .items_center() + .child( + div() + .flex_shrink(1.) + .min_w_0() + .truncate() + .when(cm.is_head, |d| d.font_weight(FontWeight::SEMIBOLD).text_color(c(theme::FG_STRONG))) + .when(!cm.is_head, |d| d.text_color(c(theme::FG))) + .child(cm.subject.clone()), + ) + .when(!has_refs && !cm.author.is_empty(), |h| { + h.child( + div() + .flex_shrink(1.) + .min_w_0() + .max_w(theme::u(86.)) + .truncate() + .text_size(theme::u(10.5)) + .text_color(c(theme::FG_DIM)) + .child(cm.author.clone()), + ) + }), + ) + .children(badge.map(|label| { + let tint = if cm.is_head { theme::BLUE } else { theme::ACCENT }; + h_flex() + .flex_shrink(1.) + .min_w_0() + .max_w(theme::u(108.)) + .h(theme::u(17.)) + .px_1p5() + .items_center() + .rounded_full() + .border_1() + .border_color(c(tint).opacity(0.45)) + .bg(c(tint).opacity(0.18)) + .text_size(theme::u(10.5)) + .font_weight(FontWeight::MEDIUM) + .text_color(c(tint)) + .child(div().min_w_0().truncate().child(label)) + })) + .when(cm.refs.len() > 1, |h| { + h.child(div().flex_none().text_size(theme::u(10.)).text_color(c(theme::FG_DIM)).child(format!("+{}", cm.refs.len() - 1))) + }) + .tooltip({ + let refs = if cm.refs.is_empty() { String::new() } else { format!("\n{}", cm.refs.join(", ")) }; + let tip = format!("{} {}\n{} · {}{refs}", cm.short, cm.subject, cm.author, cm.when); + move |w, cx| Tooltip::new(tip.clone()).build(w, cx) + }) + .on_click(cx.listener(move |this, _, _, cx| this.scm_toggle_commit(hash.clone(), cx))), + ); + if !open { + continue; + } + let (h_all, short_all, subj_all) = (cm.hash.clone(), cm.short.clone(), cm.subject.clone()); + col = col.child( + h_flex() + .w_full() + .min_w_0() + .flex_shrink_0() + .overflow_hidden() + .h(theme::u(ROW_H)) + .pl(theme::u(26.)) + .pr(px(SCROLLBAR_PAD)) + .gap_1p5() + .items_center() + .bg(c(theme::BG_ELEVATED).opacity(0.6)) + .text_size(theme::u(10.5)) + .text_color(c(theme::FG_DIM)) + .child(div().flex_none().font_weight(FontWeight::MEDIUM).text_color(c(theme::ACCENT_TEXT)).child(cm.short.clone())) + .child(div().flex_1().min_w_0().truncate().child(format!("{} · {}", cm.author, cm.when))) + .child( + div() + .id(("scm-c-all", i)) + .flex_none() + .px_1p5() + .py(px(1.)) + .rounded(px(4.)) + .cursor_pointer() + .text_color(c(theme::FG_MUTED)) + .hover(|s| s.bg(c(theme::BG_HOVER)).text_color(c(theme::FG_STRONG))) + .child(tr("View full diff")) + .on_click(cx.listener(move |this, _, w, cx| { + this.scm_show_commit_all(h_all.clone(), short_all.clone(), subj_all.clone(), w, cx); + })), + ), + ); + match s.commit_files.get(&cm.hash) { + None => { + col = col.child( + h_flex() + .w_full() + .min_w_0() + .flex_shrink_0() + .h(theme::u(ROW_H)) + .pl(theme::u(26.)) + .pr(px(SCROLLBAR_PAD)) + .gap_1p5() + .items_center() + .text_xs() + .text_color(c(theme::FG_DIM)) + .child(tr("Reading the changed files…")), + ); + } + Some(files) if files.is_empty() => { + col = col.child( + h_flex() + .w_full() + .min_w_0() + .flex_shrink_0() + .h(theme::u(ROW_H)) + .pl(theme::u(26.)) + .pr(px(SCROLLBAR_PAD)) + .gap_1p5() + .items_center() + .text_xs() + .text_color(c(theme::FG_DIM)) + .child(tr("No changed files.")), + ); + } + Some(files) => { + for (k, (code, fpath)) in files.iter().enumerate().take(60) { + let (h_f, short_f, p_f) = (cm.hash.clone(), cm.short.clone(), fpath.clone()); + let name = fpath.rsplit('/').next().unwrap_or(fpath).to_string(); + let dir = fpath.rsplit_once('/').map(|(d, _)| d.replace('/', "\\")).unwrap_or_default(); + let col_tok = code_color(*code); + let file_key = PathBuf::from(format!("flux-diff://commit/{}/{}", cm.hash, fpath)); + let is_active = active_doc_path.as_ref() == Some(&file_key); + col = col.child( + h_flex() + .id(("scm-cf", i * 1000 + k)) + .w_full() + .min_w_0() + .flex_none() + .overflow_hidden() + .h(theme::u(ROW_H)) + .pl(theme::u(26.)) + .pr(px(SCROLLBAR_PAD)) + .gap_1p5() + .items_center() + .text_xs() + .cursor_pointer() + .when(is_active, |h| h.bg(c(theme::SELECT))) + .hover(|s| s.bg(c(theme::BG_HOVER))) + .child(crate::files::file_icon_el(&name, theme::u(13.))) + .child(div().flex_shrink(1.).min_w_0().truncate().text_color(c(col_tok)).child(name)) + .child(div().flex_1().min_w_0().truncate().text_color(c(theme::FG_DIM)).child(dir)) + .child(div().flex_none().w(theme::u(12.)).text_right().font_weight(FontWeight::BOLD).text_color(c(col_tok)).child(code.to_string())) + .on_click(cx.listener(move |this, _, w, cx| { + this.scm_show_commit_file(h_f.clone(), short_f.clone(), p_f.clone(), w, cx); + })), + ); + } + if files.len() > 60 { + col = col.child( + h_flex() + .w_full() + .min_w_0() + .flex_shrink_0() + .h(theme::u(ROW_H)) + .pl(theme::u(26.)) + .pr(px(SCROLLBAR_PAD)) + .gap_1p5() + .items_center() + .text_xs() + .text_color(c(theme::FG_DIM)) + .child(crate::trf!("… and {n} more files"; n => files.len() - 60)), + ); + } + } + } + } + col.into_any_element() + }); + panes.push(PaneBuilt { + spec: PaneSpec { + id: ScmPane::Graph, + flexible, + min_h: if flexible { + flex_min(natural, graph_h, 3.) + } else { + header_h + }, + natural_h: natural, + saved: s.pane_h[ScmPane::Graph as usize], + }, + scroll_id: "scm-scroll-graph", + header: hdr, + rows, + }); } - body = body.child( - section("scm-sec-actions", "GitHub Actions (deploy)".into(), 0, s.show_actions).mt_2().cursor_pointer().on_click(cx.listener(|this, _, _, cx| { + { + let hdr = section( + "scm-sec-actions", + "GitHub Actions (deploy)".into(), + 0, + s.show_actions, + ) + .on_click(cx.listener(|this, _, _, cx| { this.scm.show_actions = !this.scm.show_actions; if this.scm.show_actions { this.scm_load_actions(cx); } cx.notify(); - })), - ); - if s.show_actions { - if s.workflows.is_empty() && s.runs.is_empty() { - body = body.child( - div() - .flex_none() - .px(theme::u(18.)) - .py_1() - .text_xs() - .text_color(c(theme::FG_DIM)) - .child(if s.actions_loaded { - "No active workflows in this repository." - } else { - "Loading workflows…" - }), - ); - } - for (i, wf) in s.workflows.iter().enumerate() { - let w = wf.clone(); - body = body.child( - scm_row() - .pl(theme::u(18.)) - .pr_2() - .gap_1p5() - .text_size(theme::u(11.5)) - .child(Icon::new(Ico::Rocket).flex_none().size(theme::u(14.)).text_color(c(theme::FG_MUTED))) - .child(div().flex_1().min_w_0().truncate().child(wf.name.clone())) - .child( - Button::new(("scm-wf", i)) - .icon(Icon::new(IconName::Play)) - .label(tr("Run")) - .ghost() - .xsmall() - .tooltip(tr("gh workflow run on the current branch (needs workflow_dispatch)")) - .on_click(cx.listener(move |this, _, _, cx| this.scm_run_workflow(w.clone(), cx))), - ), - ); + })) + .into_any_element(); + let rows_n = (s.workflows.len() + s.runs.len()).max(1); + let natural = header_h + rows_n as f32 * row_h; + let flexible = s.show_actions; + let rows = flexible.then(|| { + let mut col = v_flex().w_full().min_w_0().pb_1(); + if s.workflows.is_empty() && s.runs.is_empty() { + col = col.child(div().flex_shrink_0().px(theme::u(18.)).py_1().text_xs().text_color(c(theme::FG_DIM)).child(if s.actions_loaded { "No active workflows in this repository." } else { "Loading workflows…" })); + } + for (i, wf) in s.workflows.iter().enumerate() { + let w = wf.clone(); + col = col.child( + h_flex() + .w_full() + .min_w_0() + .flex_shrink_0() + .overflow_hidden() + .h(theme::u(ROW_H)) + .pl(theme::u(18.)) + .pr(px(SCROLLBAR_PAD)) + .gap_1p5() + .items_center() + .text_size(theme::u(11.5)) + .child(Icon::new(Ico::Rocket).flex_none().size(theme::u(14.)).text_color(c(theme::FG_MUTED))) + .child(div().flex_1().min_w_0().truncate().child(wf.name.clone())) + .child( + Button::new(("scm-wf", i)) + .icon(Icon::new(IconName::Play)) + .label(tr("Run")) + .ghost() + .xsmall() + .tooltip(tr("gh workflow run on the current branch (needs workflow_dispatch)")) + .on_click(cx.listener(move |this, _, _, cx| this.scm_run_workflow(w.clone(), cx))), + ), + ); + } + for (i, r) in s.runs.iter().enumerate() { + let (mark, col_tok) = match (r.status.as_str(), r.conclusion.as_str()) { + ("completed", "success") => ("✓", theme::GREEN), + ("completed", "failure") => ("✕", theme::DANGER), + ("completed", _) => ("–", theme::FG_DIM), + _ => ("●", theme::BLUE), + }; + let url = r.url.clone(); + col = col.child( + h_flex() + .id(("scm-run", i)) + .w_full() + .min_w_0() + .flex_shrink_0() + .overflow_hidden() + .h(theme::u(ROW_H)) + .pl(theme::u(18.)) + .pr(px(SCROLLBAR_PAD)) + .gap_1p5() + .items_center() + .text_size(theme::u(11.5)) + .cursor_pointer() + .hover(|s| s.bg(c(theme::BG_HOVER))) + .child( + div() + .flex_none() + .w(theme::u(12.)) + .text_color(c(col_tok)) + .child(mark), + ) + .child(div().flex_1().min_w_0().truncate().child(r.title.clone())) + .child( + div() + .flex_shrink(1.) + .min_w_0() + .max_w(theme::u(130.)) + .truncate() + .text_xs() + .text_color(c(theme::FG_DIM)) + .child(format!("{} · {}", r.workflow, r.branch)), + ) + .on_click(move |_, _, cx| cx.open_url(&url)), + ); + } + col.into_any_element() + }); + panes.push(PaneBuilt { + spec: PaneSpec { + id: ScmPane::Actions, + flexible, + min_h: if flexible { + flex_min(natural, row_h, 2.) + } else { + header_h + }, + natural_h: natural, + saved: s.pane_h[ScmPane::Actions as usize], + }, + scroll_id: "scm-scroll-actions", + header: hdr, + rows, + }); + } + + let specs: Vec = panes.iter().map(|p| p.spec).collect(); + let has_sash: Vec = (0..specs.len()) + .map(|i| { + i > 0 + && specs[..i].iter().any(|p| p.flexible) + && specs[i..].iter().any(|p| p.flexible) + }) + .collect(); + let sash_count = has_sash.iter().filter(|&&b| b).count(); + let stack_h = s.stack_h.get(); + let avail_h = if stack_h > 1. { + (stack_h - sash_count as f32 * SASH_H).max(120.) + } else { + 600. + }; + let heights = resolve_pane_heights(avail_h, &specs); + let active_sash = (self.resizing == 5) + .then(|| self.scm.pane_drag.as_ref().map(|d| d.sash)) + .flatten(); + let stack_ref = s.stack_h.clone(); + let mut stack = v_flex() + .flex_1() + .min_h_0() + .w_full() + .min_w_0() + .relative() + .on_prepaint(move |bounds, _, _| { + stack_ref.set(f32::from(bounds.size.height)); + }); + + let drag_ids: Vec = specs.iter().map(|p| p.id).collect(); + let drag_mins: Vec = specs.iter().map(|p| p.min_h).collect(); + let drag_maxs: Vec = specs + .iter() + .map(|p| if p.flexible { f32::INFINITY } else { p.min_h }) + .collect(); + + for (i, pane) in panes.into_iter().enumerate() { + let id = pane.spec.id; + if i > 0 { + if has_sash[i] { + let on = active_sash == Some(i); + let ids = drag_ids.clone(); + let mins = drag_mins.clone(); + let maxs = drag_maxs.clone(); + let fallback = heights.clone(); + stack = stack.child( + div() + .id(("scm-sash", i)) + .group("scm-sash") + .w_full() + .h(px(SASH_H)) + .flex_none() + .flex() + .items_center() + .cursor_row_resize() + .child( + div() + .w_full() + .h(if on { px(2.) } else { px(1.) }) + .bg(if on { + c(theme::ACCENT) + } else { + c(theme::BORDER) + }) + .group_hover("scm-sash", |st| { + st.h(px(2.)).bg(c(theme::ACCENT)) + }), + ) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, ev: &MouseDownEvent, _, cx| { + if ev.click_count == 2 { + this.scm.pane_h = [None; 6]; + cx.notify(); + return; + } + let painted = this.scm.painted_h.get(); + let start: Vec = ids + .iter() + .enumerate() + .map(|(j, pid)| { + let p = painted[*pid as usize]; + if p > 1. { + p + } else { + fallback[j] + } + }) + .collect(); + this.scm.pane_drag = Some(ScmPaneDrag { + sash: i, + y0: f32::from(ev.position.y), + ids: ids.clone(), + start, + mins: mins.clone(), + maxs: maxs.clone(), + }); + this.resizing = 5; + cx.notify(); + }), + ), + ); + } else { + stack = stack.child(div().w_full().h(px(1.)).flex_none().bg(c(theme::BORDER))); + } } - for (i, r) in s.runs.iter().enumerate() { - let (mark, col) = match (r.status.as_str(), r.conclusion.as_str()) { - ("completed", "success") => ("✓", theme::GREEN), - ("completed", "failure") => ("✕", theme::DANGER), - ("completed", _) => ("–", theme::FG_DIM), - _ => ("●", theme::BLUE), - }; - let url = r.url.clone(); - body = body.child( - scm_row() - .id(("scm-run", i)) - .pl(theme::u(18.)) - .pr_2() - .gap_1p5() - .text_size(theme::u(11.5)) - .cursor_pointer() - .hover(|s| s.bg(c(theme::BG_HOVER))) - .child( - div() - .flex_none() - .w(theme::u(12.)) - .text_color(c(col)) - .child(mark), - ) - .child(div().flex_1().min_w_0().truncate().child(r.title.clone())) - .child( - div() - .flex_shrink(1.) - .min_w_0() - .max_w(theme::u(130.)) - .truncate() - .text_xs() - .text_color(c(theme::FG_DIM)) - .child(format!("{} · {}", r.workflow, r.branch)), - ) - .on_click(move |_, _, cx| cx.open_url(&url)), - ); + let painted_ref = s.painted_h.clone(); + let mut box_el = v_flex() + .w_full() + .min_w_0() + .relative() + .overflow_hidden() + .child(pane.header) + .on_prepaint(move |bounds, _, _| { + let mut a = painted_ref.get(); + a[id as usize] = f32::from(bounds.size.height); + painted_ref.set(a); + }); + if pane.spec.flexible { + if let Some(rows_el) = pane.rows { + box_el = box_el.child( + div() + .flex_1() + .min_h_0() + .w_full() + .min_w_0() + .overflow_y_scrollbar() + .id(pane.scroll_id) + .scroll_bounce(false) + .child(rows_el), + ); + } + let h = heights[i].max(1.); + let eff_min = pane.spec.min_h.min(h); + box_el.style().flex_grow = Some(h); + box_el = box_el.flex_shrink_1().flex_basis(px(0.)).min_h(px(eff_min)); + } else { + box_el = box_el.flex_none().h(px(header_h)); } + stack = stack.child(box_el); } - v_flex().size_full().child(body).into_any_element() + + let heading = section("scm-changes-view", tr("Changes").to_uppercase(), 0, s.show_changes_view) + .border_t_1() + .border_b_1() + .border_color(c(theme::BORDER)) + .when(s.show_changes_view, |h| { + h.child( + Button::new("scm-view-mode") + .label(if s.show_tree { tr("List") } else { tr("Tree") }) + .ghost() + .xsmall() + .tooltip(if s.show_tree { tr("View as List") } else { tr("View as Tree") }) + .on_click(cx.listener(|this, _, _, cx| { + cx.stop_propagation(); + this.scm.show_tree = !this.scm.show_tree; + cx.notify(); + })), + ) + }) + .on_click(cx.listener(|this, _, _, cx| { + this.scm.show_changes_view = !this.scm.show_changes_view; + cx.notify(); + })); + + v_flex() + .size_full() + .min_h_0() + .bg(c(theme::BG_SIDE)) + .child(heading) + .when( + s.show_changes_view || s.is_busy() || s.error.is_some() || s.repo_error.is_some() + || s.confirm_discard.is_some() || s.confirm_uninit, + |v| v.child(top), + ) + .child(stack) + .into_any_element() } pub(crate) fn render_scm_header(&self, cx: &mut Context) -> impl IntoElement { h_flex() .gap_px() - .child(tool_button("scm-h-commit", IconName::Check, "Commit", cx, |this, w, cx| this.scm_commit(After::Nothing, false, w, cx))) - .child(tool_button("scm-h-refresh", IconName::RefreshCw, "Refresh", cx, |this, _, cx| this.scm_refresh(cx))) - .child(Button::new("scm-h-more").icon(Icon::new(IconName::Ellipsis)).ghost().xsmall().dropdown_menu(|m: PopupMenu, _, _| { - m.min_w(px(230.)) - .menu(tr("Pull"), Box::new(ScmPull)) - .menu(tr("Push"), Box::new(ScmPush)) - .menu(tr("Sync (Pull, then Push)"), Box::new(ScmSync)) - .menu(tr("Fetch"), Box::new(ScmFetch)) - .separator() - .menu(tr("Commit & Push"), Box::new(ScmCommitPush)) - .menu(tr("Commit (Amend)"), Box::new(ScmCommitAmend)) - .separator() - .menu(tr("Stage All Changes"), Box::new(ScmStageAll)) - .menu(tr("Unstage All Changes"), Box::new(ScmUnstageAll)) - .separator() - .menu(tr("Create Pull Request"), Box::new(ScmCreatePr)) - .menu(tr("Open Repository on GitHub"), Box::new(ScmOpenGithub)) - .separator() - .menu(tr("Remove Git from This Folder…"), Box::new(ScmRemoveGit)) - })) + .child(tool_button( + "scm-h-refresh", + IconName::RefreshCw, + "Refresh", + cx, + |this, _, cx| { + this.scm_refresh(cx); + }, + )) + .when(self.scm.repo.is_some(), |h| { + h.child( + Button::new("scm-h-more") + .icon(Icon::new(IconName::Ellipsis)) + .ghost() + .xsmall() + .disabled(self.scm.is_busy()) + .dropdown_menu(|m: PopupMenu, _, _| { + m.min_w(px(230.)) + .menu(tr("Pull"), Box::new(ScmPull)) + .menu(tr("Push"), Box::new(ScmPush)) + .menu(tr("Sync (Pull, then Push)"), Box::new(ScmSync)) + .menu(tr("Fetch"), Box::new(ScmFetch)) + .separator() + .menu(tr("Commit & Push"), Box::new(ScmCommitPush)) + .menu(tr("Commit (Amend)"), Box::new(ScmCommitAmend)) + .menu(tr("Commit (Sign Off)"), Box::new(ScmCommitSignoff)) + .separator() + .menu(tr("Stage All Changes"), Box::new(ScmStageAll)) + .menu(tr("Unstage All Changes"), Box::new(ScmUnstageAll)) + .separator() + .menu(tr("Create Pull Request"), Box::new(ScmCreatePr)) + .menu(tr("Open Repository on GitHub"), Box::new(ScmOpenGithub)) + .separator() + .menu(tr("Remove Git from This Folder…"), Box::new(ScmRemoveGit)) + }), + ) + }) } @@ -1391,25 +2442,32 @@ impl Workbench { pub(crate) fn on_scm_commit_sync(&mut self, _: &ScmCommitSync, w: &mut Window, cx: &mut Context) { self.scm_commit(After::Sync, false, w, cx); } + pub(crate) fn on_scm_commit_default(&mut self, _: &ScmCommitDefault, w: &mut Window, cx: &mut Context) { + self.scm_commit(After::Nothing, false, w, cx); + } + pub(crate) fn on_scm_commit_signoff(&mut self, _: &ScmCommitSignoff, w: &mut Window, cx: &mut Context) { + self.scm_commit_with_options(After::Nothing, false, true, w, cx); + } pub(crate) fn on_scm_commit_amend(&mut self, _: &ScmCommitAmend, w: &mut Window, cx: &mut Context) { self.scm_commit(After::Nothing, true, w, cx); } pub(crate) fn on_scm_pull(&mut self, _: &ScmPull, _: &mut Window, cx: &mut Context) { - self.scm_run("Pulling…", vec![git_step(&["pull", "--autostash"])], cx, |this, _, cx| { - this.agent.reloads.extend(this.docs.iter().filter(|d| !d.dirty).map(|d| d.path.clone())); - this.refresh_tree(cx); + self.scm_run(tr("Pulling…"), vec![Step::Remote(RemoteAction::Pull)], cx, |this, _, _| { this.status = tr("Pulled").into(); }); } pub(crate) fn on_scm_push(&mut self, _: &ScmPush, _: &mut Window, cx: &mut Context) { - let steps = self.push_steps(); - self.scm_run("Pushing…", steps, cx, |this, _, _| this.status = tr("Pushed").into()); + self.scm_run(tr("Pushing…"), vec![Step::Remote(RemoteAction::Push)], cx, |this, _, _| { + this.status = tr("Pushed").into(); + }); } pub(crate) fn on_scm_sync(&mut self, _: &ScmSync, _: &mut Window, cx: &mut Context) { self.scm_sync(cx); } pub(crate) fn on_scm_fetch(&mut self, _: &ScmFetch, _: &mut Window, cx: &mut Context) { - self.scm_run("Fetching…", vec![git_step(&["fetch", "--prune"])], cx, |this, _, _| this.status = tr("Fetched").into()); + self.scm_run(tr("Fetching…"), vec![Step::Remote(RemoteAction::Fetch)], cx, |this, _, _| { + this.status = tr("Fetched").into(); + }); } pub(crate) fn on_scm_remove_git(&mut self, _: &ScmRemoveGit, _: &mut Window, cx: &mut Context) { if self.scm.repo.is_some() { @@ -1423,12 +2481,16 @@ impl Workbench { fn scm_remove_git(&mut self, cx: &mut Context) { self.scm.confirm_uninit = false; let Some(repo) = self.scm.repo.clone() else { return }; + let generation = self.scm.workspace_generation; let git = repo.join(".git"); self.scm.busy = Some(tr("Removing Git…").into()); cx.notify(); cx.spawn(async move |this, cx| { let r = cx.background_spawn(async move { crate::core::delete_path(&git) }).await; _ = this.update(cx, |this, cx| { + if this.scm.workspace_generation != generation { + return; + } this.scm.busy = None; match r { Ok(()) => { @@ -1447,6 +2509,112 @@ impl Workbench { .detach(); } + pub(crate) fn scm_stage_hunk( + &mut self, + path: String, + group: Group, + expected: String, + index: usize, + window: &mut Window, + cx: &mut Context, + ) { + let Some(repo) = self.scm.repo.clone() else { + return; + }; + if self.scm.is_busy() { + return; + } + let key = Self::scm_diff_key(&repo, group, &path); + let generation = self.scm.workspace_generation; + let label = tr(if group == Group::Staged { "Unstaging…" } else { "Staging…" }); + self.scm.busy = Some(label.into()); + self.scm.error = None; + self.scm.note = None; + cx.notify(); + let wsl = self.wsl.clone(); + cx.spawn_in(window, async move |this, cx| { + let dir = repo.clone(); + let step = Step::Hunk { + path: path.clone(), + group, + expected, + index, + }; + let result = cx + .background_spawn(async move { + run_step(&dir, &step, wsl.as_ref())?; + let status = crate::scm_git::read_status(&dir, wsl.as_ref())?; + let Some(file) = status + .files(group) + .iter() + .find(|f| f.path == path && f.code == 'M') + .cloned() + else { + return Ok::<_, String>(None); + }; + let diff = crate::scm_git::file_diff(&dir, &file, group, wsl.as_ref())?; + Ok(Some((file, diff))) + }) + .await; + _ = this.update_in(cx, |this, window, cx| { + if this.scm.workspace_generation != generation { + return; + } + this.scm.busy = None; + this.scm_refresh(cx); + match result { + Ok(Some((file, (patch, conflict_text, target)))) => { + let file_name = file.path.rsplit('/').next().unwrap_or(&file.path).to_string(); + let badge = match group { + Group::Staged => tr("Index"), + Group::Conflicts => tr("Conflict"), + Group::Changes | Group::Untracked => tr("Working Tree"), + }; + this.open_scm_diff_tab( + crate::diff_view::ScmDiffSpec { + virtual_key: key.clone(), + tab_title: format!("{file_name} ({badge})"), + display_name: file.path.clone(), + badge: badge.to_string(), + patch, + conflict_text, + target, + scm_stage: Some((repo, file.path, group)), + multi_file: false, + }, + window, + cx, + ); + if let Some(state) = this + .docs + .iter() + .find(|d| d.path == key && d.diff.as_ref().is_some_and(|x| x.virtual_tab)) + .and_then(|d| d.diff.as_ref()) + .and_then(|d| d.state.clone()) + { + state.update(cx, |st, cx| { + let count = st.hunk_position().map(|(_, c)| c).unwrap_or(0); + if count > 0 { + st.jump_to_hunk(index.min(count - 1), cx); + } + }); + } + this.status = tr("Hunk updated.").into(); + } + Ok(None) => { + this.close_tabs_where(window, cx, |_, doc| { + doc.path == key && doc.diff.as_ref().is_some_and(|d| d.virtual_tab) + }); + this.status = tr("Hunk updated.").into(); + } + Err(e) => this.scm.error = Some(e), + } + cx.notify(); + }); + }) + .detach(); + } + fn scm_ignore(&mut self, pattern: String, cx: &mut Context) { let Some(repo) = self.scm.repo.clone() else { return }; let path = repo.join(".gitignore"); @@ -1468,10 +2636,17 @@ impl Workbench { } pub(crate) fn on_scm_stage_all(&mut self, _: &ScmStageAll, _: &mut Window, cx: &mut Context) { - self.scm_stage(None, true, cx); + if self.scm.repo.is_some() { + self.scm_run( + tr("Staging…"), + vec![git_step(&["add", "-A"])], + cx, + |_, _, _| {}, + ); + } } pub(crate) fn on_scm_unstage_all(&mut self, _: &ScmUnstageAll, _: &mut Window, cx: &mut Context) { - self.scm_stage(None, false, cx); + self.scm_paths(Group::Staged, None, false, cx); } pub(crate) fn on_scm_create_pr(&mut self, _: &ScmCreatePr, _: &mut Window, cx: &mut Context) { self.scm_create_pr(cx); @@ -1493,33 +2668,27 @@ impl Workbench { #[cfg(test)] mod tests { - use super::{find_url, parse_log, parse_status, scm_row, DOT_SIZE, DOT_TOP, LANE_MID, ROW_H}; + use super::{ + apply_sash_drag, change_tree_rows, find_url, lane_geometry, parse_log, + resolve_pane_heights, scm_row, ChangeTreeRow, FileChange, PaneSpec, ScmPane, ScmPaneDrag, + ROW_H, + }; use crate::theme; use gpui_kit::{Length, Overflow, Styled as _}; #[test] - fn porcelain_v2() { - let out = "# branch.oid abc\0# branch.head main\0# branch.upstream origin/main\0# branch.ab +2 -21\0\ -1 .M N... 100644 100644 100644 a b src/app.py\0\ -1 A. N... 000000 100644 100644 0 b new.txt\0\ -1 MM N... 100644 100644 100644 a b both.rs\0\ -2 R. N... 100644 100644 100644 a b R100 renamed.py\0old.py\0\ -? notes.md\0u UU N... 100644 100644 100644 100644 a b c conflict.txt\0"; - let st = parse_status(out); - assert_eq!(st.branch.as_deref(), Some("main")); - assert_eq!(st.upstream.as_deref(), Some("origin/main")); - assert_eq!((st.ahead, st.behind), (2, 21)); - assert_eq!(st.staged.iter().map(|c| (c.path.as_str(), c.code)).collect::>(), vec![("new.txt", 'A'), ("both.rs", 'M'), ("renamed.py", 'R')]); - assert_eq!(st.staged[2].orig.as_deref(), Some("old.py")); - assert_eq!(st.changes.iter().map(|c| (c.path.as_str(), c.code)).collect::>(), vec![("src/app.py", 'M'), ("both.rs", 'M'), ("notes.md", 'U')]); - assert_eq!(st.conflicts[0].path, "conflict.txt"); - assert_eq!(st.count(), 7); - } - - #[test] - fn spaces_in_paths() { - let st = parse_status("1 .M N... 100644 100644 100644 a b my folder/a file.py\0"); - assert_eq!(st.changes[0].path, "my folder/a file.py"); + fn changes_tree_groups_paths_and_hides_only_collapsed_descendants() { + use ChangeTreeRow::{File, Folder}; + let files = ["src/lib.rs", "README.md", "src/nested/main.rs", "other/end.rs"] + .map(|path| FileChange { path: path.into(), code: 'M', orig: None }); + assert_eq!( + change_tree_rows(&files, &["src".to_string()].into_iter().collect()), + vec![File(1, 0), Folder("other", 0), File(3, 1), Folder("src", 0)] + ); + assert_eq!( + change_tree_rows(&files, &["src/nested".to_string()].into_iter().collect()), + vec![File(1, 0), Folder("other", 0), File(3, 1), Folder("src", 0), File(0, 1), Folder("src/nested", 1)] + ); } #[test] @@ -1550,21 +2719,98 @@ mod tests { } #[test] - fn scm_row_height_clears_xs_controls_and_centers_lane() { - assert_eq!(LANE_MID * 2., ROW_H); - assert_eq!(DOT_TOP + DOT_SIZE * 0.5, LANE_MID); - for scale in [1.0_f32, 1.15, 1.3] { - let row_px = (ROW_H * scale).round(); - let xs_line_h = 0.75 * 16. * scale * 1.618_034; - let xsmall_btn_h = 1.25 * 16. * scale; - assert!( - row_px > xs_line_h, - "row_px {row_px} must exceed xs line_height {xs_line_h}" - ); - assert!( - row_px > xsmall_btn_h, - "row_px {row_px} must exceed xsmall button {xsmall_btn_h}" - ); - } + fn graph_lane_geometry_centers_dot_and_caps_ends() { + assert_eq!(lane_geometry(0, 1, false), (12., 12., 8.)); + assert_eq!(lane_geometry(0, 3, false), (12., 0., 8.)); + assert_eq!(lane_geometry(1, 3, false), (0., 0., 8.)); + assert_eq!(lane_geometry(2, 3, false), (0., 12., 8.)); + assert_eq!(lane_geometry(2, 3, true), (0., 0., 8.)); + } + + #[test] + fn pane_layout_splits_open_sections_and_cascades_sash_drag() { + let specs = vec![ + PaneSpec { + id: ScmPane::Staged, + flexible: true, + min_h: 72., + natural_h: 576., + saved: None, + }, + PaneSpec { + id: ScmPane::Changes, + flexible: false, + min_h: 24., + natural_h: 24., + saved: None, + }, + PaneSpec { + id: ScmPane::Graph, + flexible: true, + min_h: 100., + natural_h: 2000., + saved: None, + }, + PaneSpec { + id: ScmPane::Actions, + flexible: false, + min_h: 24., + natural_h: 24., + saved: None, + }, + ]; + let h = resolve_pane_heights(600., &specs); + assert!((h[0] - 276.).abs() < 0.1); + assert!((h[1] - 24.).abs() < 0.1); + assert!((h[2] - 276.).abs() < 0.1); + assert!((h[3] - 24.).abs() < 0.1); + + // Dragging sash above empty Changes cascades straight between Staged and Graph. + let drag = ScmPaneDrag { + sash: 1, + y0: 300., + ids: specs.iter().map(|s| s.id).collect(), + start: h.clone(), + mins: specs.iter().map(|s| s.min_h).collect(), + maxs: specs + .iter() + .map(|s| if s.flexible { f32::INFINITY } else { s.min_h }) + .collect(), + }; + let moved = apply_sash_drag(&drag, 200.); + assert_eq!(moved.len(), 2); + assert_eq!(moved[0].0, ScmPane::Staged); + assert!((moved[0].1 - 176.).abs() < 0.1); + assert_eq!(moved[1].0, ScmPane::Graph); + assert!((moved[1].1 - 376.).abs() < 0.1); + + // Dragging further respects min_h floor on Staged. + let clamped = apply_sash_drag(&drag, 0.); + assert!((clamped[0].1 - 72.).abs() < 0.1); + assert!((clamped[1].1 - 480.).abs() < 0.1); + } + + #[test] + fn pane_layout_shrinks_saved_heights_gracefully_on_small_window() { + let specs = vec![ + PaneSpec { + id: ScmPane::Staged, + flexible: true, + min_h: 72., + natural_h: 500., + saved: Some(380.), + }, + PaneSpec { + id: ScmPane::Changes, + flexible: true, + min_h: 72., + natural_h: 500., + saved: Some(220.), + }, + ]; + let h = resolve_pane_heights(400., &specs); + assert!((h[0] + h[1] - 400.).abs() < 0.1); + assert!(h[0] >= 72. && h[1] >= 72.); + assert!(h[0] > h[1]); } } diff --git a/src/scm_git.rs b/src/scm_git.rs new file mode 100644 index 0000000..27a7a28 --- /dev/null +++ b/src/scm_git.rs @@ -0,0 +1,1196 @@ +use crate::{i18n::tr, proc, remote::WslTarget}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Debug, PartialEq)] +pub struct FileChange { + pub path: String, + pub code: char, + pub orig: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RepoStatus { + pub head: Option, + pub branch: Option, + pub upstream: Option, + pub upstream_available: bool, + pub ahead: u32, + pub behind: u32, + pub staged: Vec, + pub changes: Vec, + pub untracked: Vec, + pub conflicts: Vec, +} + +impl RepoStatus { + pub fn count(&self) -> usize { + self.staged.len() + self.changes.len() + self.untracked.len() + self.conflicts.len() + } + + pub(crate) fn files(&self, group: Group) -> &[FileChange] { + match group { + Group::Changes => &self.changes, + Group::Staged => &self.staged, + Group::Conflicts => &self.conflicts, + Group::Untracked => &self.untracked, + } + } + + pub(crate) fn check_commit(&self, message: &str, amend: bool) -> Result<(), &'static str> { + if !self.conflicts.is_empty() { + Err("Resolve the merge conflicts before committing.") + } else if amend { + if self.head.is_none() { + Err("There is no commit to amend.") + } else if message.trim().is_empty() && self.staged.is_empty() { + Err("Stage changes or enter a new commit message to amend.") + } else { + Ok(()) + } + } else if message.trim().is_empty() { + Err("Enter a commit message.") + } else if self.staged.is_empty() { + Err("Stage changes before committing.") + } else { + Ok(()) + } + } + + pub(crate) fn check_smart_commit( + &self, + message: &str, + amend: bool, + has_dirty_docs: bool, + ) -> Result { + if !self.conflicts.is_empty() { + Err("Resolve the merge conflicts before committing.") + } else if amend { + if self.head.is_none() { + Err("There is no commit to amend.") + } else if message.trim().is_empty() && self.staged.is_empty() { + Err("Stage changes or enter a new commit message to amend.") + } else { + Ok(false) + } + } else if message.trim().is_empty() { + Err("Enter a commit message.") + } else if !self.staged.is_empty() { + Ok(false) + } else if !self.changes.is_empty() || !self.untracked.is_empty() || has_dirty_docs { + Ok(true) + } else { + Err("There are no changes to commit.") + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Group { + Changes = 0, + Staged = 1, + Conflicts = 2, + Untracked = 3, +} + +pub(crate) fn file_paths(files: &[FileChange]) -> Vec<&str> { + let mut paths: Vec<_> = files + .iter() + .flat_map(|file| { + [ + Some(file.path.as_str()), + file.orig.as_deref().filter(|_| file.code == 'R'), + ] + .into_iter() + .flatten() + }) + .collect(); + paths.sort_unstable(); + paths.dedup(); + paths +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Commit { + pub hash: String, + pub short: String, + pub subject: String, + pub author: String, + pub when: String, + pub refs: Vec, + pub merge: bool, + pub parents: Vec, + pub is_head: bool, +} + +pub fn parse_status(out: &str) -> RepoStatus { + let mut st = RepoStatus::default(); + let mut recs = out.split('\0').filter(|r| !r.is_empty()); + let letter = |c: char| { + if c == '?' { + 'U' + } else if c == 'T' { + 'M' + } else { + c + } + }; + while let Some(r) = recs.next() { + if let Some(oid) = r.strip_prefix("# branch.oid ") { + st.head = (oid != "(initial)").then(|| oid.to_string()); + } else if let Some(h) = r.strip_prefix("# branch.head ") { + st.branch = (h != "(detached)").then(|| h.to_string()); + } else if let Some(u) = r.strip_prefix("# branch.upstream ") { + st.upstream = Some(u.to_string()); + } else if let Some(ab) = r.strip_prefix("# branch.ab ") { + st.upstream_available = true; + let mut it = ab.split_whitespace(); + st.ahead = it + .next() + .and_then(|a| a.trim_start_matches('+').parse().ok()) + .unwrap_or(0); + st.behind = it + .next() + .and_then(|b| b.trim_start_matches('-').parse().ok()) + .unwrap_or(0); + } else if let Some(p) = r.strip_prefix("? ") { + st.untracked.push(FileChange { + path: p.to_string(), + code: 'U', + orig: None, + }); + } else if r.starts_with("1 ") || r.starts_with("2 ") { + let renamed = r.starts_with('2'); + let fields: Vec<&str> = r.splitn(if renamed { 10 } else { 9 }, ' ').collect(); + let orig = if renamed { + recs.next().map(str::to_string) + } else { + None + }; + if fields.len() != if renamed { 10 } else { 9 } { + continue; + } + let mut xy = fields[1].chars(); + let (Some(x), Some(y)) = (xy.next(), xy.next()) else { + continue; + }; + let path = fields[fields.len() - 1]; + for (code, group) in [(x, &mut st.staged), (y, &mut st.changes)] { + if code != '.' { + group.push(FileChange { + path: path.to_string(), + code: letter(code), + orig: if matches!(code, 'R' | 'C') { + orig.clone() + } else { + None + }, + }); + } + } + } else if r.starts_with("u ") { + if let Some(path) = r.splitn(11, ' ').nth(10) { + st.conflicts.push(FileChange { + path: path.to_string(), + code: 'U', + orig: None, + }); + } + } + } + st +} + +pub fn parse_log(out: &str) -> Vec { + out.split('\0') + .filter(|r| !r.trim().is_empty()) + .filter_map(|r| { + let f: Vec<&str> = r.trim_start_matches('\n').split('\x1f').collect(); + (f.len() >= 7).then(|| { + let raw_refs: Vec<&str> = f[5] + .split(", ") + .filter(|s| !s.is_empty() && *s != "origin/HEAD") + .collect(); + let is_head = raw_refs + .iter() + .any(|s| *s == "HEAD" || s.starts_with("HEAD -> ")); + let refs = raw_refs + .into_iter() + .filter(|s| *s != "HEAD") + .map(|s| s.replace("HEAD -> ", "")) + .collect(); + let parents: Vec = f[6].split_whitespace().map(str::to_string).collect(); + let merge = parents.len() > 1; + Commit { + hash: f[0].into(), + short: f[1].into(), + subject: f[2].into(), + author: f[3].into(), + when: f[4].into(), + refs, + merge, + parents, + is_head, + } + }) + }) + .collect() +} + +#[derive(Clone)] +pub(crate) enum Step { + Save { + path: PathBuf, + gen: u64, + text: String, + crlf: bool, + nbt: Option, + }, + Git(Vec, Option), + Resolve { + path: String, + expected: String, + resolved: String, + }, + Hunk { + path: String, + group: Group, + expected: String, + index: usize, + }, + Remote(RemoteAction), + Gh(Vec), + Commit { + message: String, + amend: bool, + signoff: bool, + }, + Paths { + group: Group, + files: Vec, + discard: bool, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RemoteAction { + Fetch, + Pull, + Push, + Sync, +} + +pub(crate) const REMOTE_ENV: &[(&str, &str)] = &[ + ("GCM_INTERACTIVE", "never"), + ("SSH_ASKPASS_REQUIRE", "never"), + ("GIT_HTTP_LOW_SPEED_LIMIT", "1"), + ("GIT_HTTP_LOW_SPEED_TIME", "30"), +]; + +pub(crate) fn git_step(args: &[&str]) -> Step { + Step::Git(args.iter().map(|s| s.to_string()).collect(), None) +} + +pub(crate) fn run_step( + dir: &Path, + step: &Step, + target: Option<&WslTarget>, +) -> Result { + use std::io::Write; + let (prog, args, input) = match step { + Step::Save { + path, + text, + crlf, + nbt, + .. + } => { + crate::workbench::write_doc_to_disk(target, path, text, *crlf, *nbt)?; + return Ok(String::new()); + } + Step::Resolve { + path, + expected, + resolved, + } => { + let full = dir.join(path); + let status = read_status(dir, target)?; + let current = + crate::workbench::read_file_bytes(target, &full, expected.len() as u64).ok(); + if !status.conflicts.iter().any(|file| file.path == *path) + || current.as_deref() != Some(expected.as_bytes()) + { + return Err( + tr("The conflict changed. Reopen it before saving the resolution.").into(), + ); + } + crate::workbench::write_doc_to_disk(target, &full, resolved, false, None)?; + return run_step( + dir, + &git_step(&["--literal-pathspecs", "add", "--", path]), + target, + ); + } + Step::Hunk { + path, + group, + expected, + index, + } => { + return apply_hunk(dir, path, *group, expected, *index, target); + } + Step::Remote(action) => return run_remote(dir, *action, target), + Step::Commit { + message, + amend, + signoff, + } => return commit(dir, message, *amend, *signoff, target), + Step::Paths { + group, + files, + discard, + } => return update_paths(dir, *group, files, *discard, target), + Step::Git(a, i) => ("git", a, i.clone()), + Step::Gh(a) => ("gh", a, None), + }; + let target = matches!(step, Step::Git(..)).then_some(target).flatten(); + let refs: Vec<&str> = args.iter().map(String::as_str).collect(); + let network = prog == "git" && matches!(refs.first(), Some(&("fetch" | "pull" | "push"))); + let mut cmd = match &target { + Some(t) => { + let cwd = t.linux_path(dir).unwrap_or_else(|| t.linux_root.clone()); + let owned: Vec = args.iter().map(|s| s.to_string()).collect(); + // The helper can time out before an operation finishes, so network writes are never retried. + if !network { + if let Some(r) = crate::remote::with_client(&t.distro.clone(), |c| { + c.git(&cwd, &owned, input.as_deref()) + }) { + match r { + Ok(g) if g.success => { + return Ok(if g.stdout.trim().is_empty() { + g.stderr.trim().to_string() + } else { + g.stdout + }) + } + Ok(g) => { + return Err(format!( + "{prog} {}: {}", + args.first().map(String::as_str).unwrap_or(""), + g.stderr.trim() + )) + } + Err(_) => {} + } + } + } + let mut env = vec![ + ("LC_ALL", "C"), + ("GIT_OPTIONAL_LOCKS", "0"), + ("GIT_TERMINAL_PROMPT", "0"), + ("NO_COLOR", "1"), + ]; + if network { + env.extend_from_slice(REMOTE_ENV); + } + crate::remote::program_command_env(t, &cwd, &env, prog, &refs) + } + None => { + let mut c = proc::command(prog); + c.args(args).current_dir(dir); + if network { + c.envs(REMOTE_ENV.iter().copied()); + } + c + } + }; + cmd.env("LC_ALL", "C") + .env("GIT_OPTIONAL_LOCKS", "0") + .env("GIT_TERMINAL_PROMPT", "0") + .env("GH_PROMPT_DISABLED", "1") + .env("NO_COLOR", "1") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()); + crate::github::apply_env(&mut cmd); + let mut child = cmd + .spawn() + .map_err(|e| format!("{prog} could not start: {e}"))?; + if let Some(mut stdin) = child.stdin.take() { + if let Some(text) = input { + let _ = stdin.write_all(text.as_bytes()); + } + } + let out = child.wait_with_output().map_err(|e| e.to_string())?; + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); + if out.status.success() { + Ok(if stdout.trim().is_empty() { + stderr + } else { + stdout + }) + } else { + let msg = if stderr.is_empty() { + stdout.trim().to_string() + } else { + stderr + }; + Err(format!( + "{prog} {}: {}", + args.first().map(String::as_str).unwrap_or(""), + msg + )) + } +} + +fn remote_error(error: String) -> String { + let lower = error.to_ascii_lowercase(); + let hint = if lower.contains("non-fast-forward") || lower.contains("(fetch first)") { + Some(tr( + "The remote branch has new commits. Pull or Sync before pushing again.", + )) + } else if lower.contains("permission denied (publickey") + || lower.contains("authentication failed") + || lower.contains("could not read username") + || lower.contains("could not read password") + || lower.contains("interactivity has been disabled") + || lower.contains("host key verification failed") + { + Some(tr( + "Check Git credentials or your SSH connection in a terminal, then retry.", + )) + } else { + None + }; + match hint { + Some(hint) => format!("{error}\n{hint}"), + None => error, + } +} + +fn run_remote( + dir: &Path, + action: RemoteAction, + target: Option<&WslTarget>, +) -> Result { + let git = |args: &[&str]| run_step(dir, &git_step(args), target); + let remotes = git(&["remote"])?; + if remotes.trim().is_empty() { + return Err(tr( + "No Git remote is configured. Add a remote before fetching, pulling, or pushing.", + ) + .into()); + } + if action == RemoteAction::Fetch { + return git(&["fetch", "--prune"]).map_err(remote_error); + } + let mut status = read_status(dir, target)?; + if status.branch.is_none() { + return Err(tr("Switch to a branch before pulling, pushing, or syncing.").into()); + } + if !status.conflicts.is_empty() || git(&["rev-parse", "--verify", "-q", "MERGE_HEAD"]).is_ok() { + return Err( + tr("Resolve and finish the merge, or abort it before using the remote.").into(), + ); + } + if action == RemoteAction::Pull && status.upstream.is_none() { + return Err(tr( + "This branch has no upstream. Set one or publish the branch before pulling.", + ) + .into()); + } + if action == RemoteAction::Pull || action == RemoteAction::Sync && status.upstream.is_some() { + let pulled = git(&["pull", "--autostash", "--no-edit"]).map_err(remote_error)?; + status = read_status(dir, target)?; + if !status.conflicts.is_empty() { + return Err( + tr("Pull left unresolved conflicts. Resolve them before continuing.").into(), + ); + } + if action == RemoteAction::Pull { + return Ok(pulled); + } + } + if status.head.is_none() { + return Err(tr("Create a commit before publishing this branch.").into()); + } + if status.upstream.is_some() { + git(&["push"]).map_err(remote_error) + } else if remotes.lines().any(|remote| remote == "origin") { + git(&["push", "-u", "origin", "HEAD"]).map_err(remote_error) + } else { + Err(tr("No origin remote is configured. Set the branch upstream before pushing.").into()) + } +} + +pub(crate) fn read_status(dir: &Path, target: Option<&WslTarget>) -> Result { + run_step( + dir, + &git_step(&["status", "--porcelain=v2", "--branch", "-z", "-uall"]), + target, + ) + .map(|s| parse_status(&s)) +} + +pub(crate) const MAX_DIFF_BYTES: usize = 2 * 1024 * 1024; +const FULL_CONTEXT_BLOB_LIMIT: usize = 256 * 1024; + +pub(crate) fn file_diff( + dir: &Path, + file: &FileChange, + group: Group, + target: Option<&WslTarget>, +) -> Result<(String, Option, Option), String> { + let full = dir.join(&file.path); + let open_path = if target.is_some() { + (file.code != 'D').then(|| full.clone()) + } else { + full.is_file().then(|| full.clone()) + }; + if group == Group::Untracked { + let limit = MAX_DIFF_BYTES as u64; + let bytes = crate::workbench::read_file_bytes(target, &full, limit)?; + let patch = if bytes.len() as u64 <= limit { + crate::diff_view::untracked_patch(&file.path, &bytes).unwrap_or_default() + } else { + return Err(tr("The untracked file is too large to preview.").to_string()); + }; + return Ok((patch, None, open_path)); + } + let conflict = (group == Group::Conflicts) + .then(|| { + crate::workbench::read_file_bytes(target, &full, MAX_DIFF_BYTES as u64) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + }) + .flatten() + .filter(|text| text.lines().any(|line| line.starts_with("<<<<<<<"))); + let mut args = vec![ + "--literal-pathspecs", + "-c", + "core.quotepath=off", + "diff", + "--no-color", + "--no-ext-diff", + "--no-textconv", + "--no-relative", + "--src-prefix=a/", + "--dst-prefix=b/", + "-U3", + ]; + match group { + Group::Staged => args.push("--cached"), + Group::Conflicts => args.push("--ours"), + _ => {} + } + args.push("--"); + args.extend(file_paths(std::slice::from_ref(file))); + let patch = run_step(dir, &git_step(&args), target)?; + if patch.len() > MAX_DIFF_BYTES { + return Err(tr("The diff is too large to preview.").to_string()); + } + Ok((patch, conflict, open_path)) +} + +pub(crate) fn show_commit_diff( + dir: &Path, + hash: &str, + path: Option<&str>, + first_parent: bool, + target: Option<&WslTarget>, +) -> Result { + let context_flag = match path { + Some(rel) => { + let spec = format!("{hash}:{rel}"); + let small_blob = run_step(dir, &git_step(&["cat-file", "-s", &spec]), target) + .ok() + .and_then(|s| s.trim().parse::().ok()) + .is_some_and(|sz| sz <= FULL_CONTEXT_BLOB_LIMIT); + if small_blob { + "-U10000" + } else { + "-U3" + } + } + None => "-U3", + }; + let mut args: Vec = vec![ + "--literal-pathspecs".into(), + "-c".into(), + "core.quotepath=off".into(), + "show".into(), + ]; + if first_parent { + args.push("-m".into()); + args.push("--first-parent".into()); + } + args.extend([ + "--format=".into(), + "--no-color".into(), + "--no-ext-diff".into(), + "--no-textconv".into(), + context_flag.into(), + hash.into(), + ]); + if let Some(rel) = path { + args.push("--".into()); + args.push(rel.into()); + } + let patch = run_step(dir, &Step::Git(args, None), target)?; + if patch.len() > MAX_DIFF_BYTES { + return Err(tr("The diff is too large to preview.").to_string()); + } + Ok(patch) +} + +fn patch_hunk(patch: &str, index: usize) -> Option { + let mut hunks = Vec::new(); + let mut offset = 0; + let mut files = 0; + for line in patch.split_inclusive('\n') { + if line.starts_with("diff --git ") { + files += 1; + } + if line.starts_with("@@ ") { + hunks.push(offset); + } + offset += line.len(); + } + if files != 1 { + return None; + } + let start = *hunks.get(index)?; + let end = hunks.get(index + 1).copied().unwrap_or(patch.len()); + Some(format!("{}{}", &patch[..hunks[0]], &patch[start..end])) +} + +fn apply_hunk( + dir: &Path, + path: &str, + group: Group, + expected: &str, + index: usize, + target: Option<&WslTarget>, +) -> Result { + let stale = + || tr("The diff changed. Reopen it before staging or unstaging a hunk.").to_string(); + if !matches!(group, Group::Changes | Group::Staged) { + return Err(stale()); + } + let status = read_status(dir, target)?; + let file = status + .files(group) + .iter() + .find(|file| file.path == path && file.code == 'M') + .ok_or_else(stale)?; + let (current, _, _) = file_diff(dir, file, group, target)?; + if current != expected { + return Err(stale()); + } + let patch = patch_hunk(¤t, index).ok_or_else(stale)?; + let mut args = vec!["apply".into(), "--cached".into()]; + if group == Group::Staged { + args.push("--reverse".into()); + } + args.push("-".into()); + run_step(dir, &Step::Git(args, Some(patch)), target) +} + +fn commit( + dir: &Path, + message: &str, + amend: bool, + signoff: bool, + target: Option<&WslTarget>, +) -> Result { + read_status(dir, target)? + .check_commit(message, amend) + .map_err(|key| tr(key).to_string())?; + for identity in ["GIT_AUTHOR_IDENT", "GIT_COMMITTER_IDENT"] { + run_step( + dir, + &git_step(&["-c", "user.useConfigOnly=true", "var", identity]), + target, + ) + .map_err(|_| tr("Configure Git user.name and user.email before committing.").to_string())?; + } + let mut args = vec!["commit".into(), "--quiet".into()]; + if amend { + args.push("--amend".into()); + } + if signoff { + args.push("--signoff".into()); + } + if message.trim().is_empty() { + args.push("--no-edit".into()); + run_step(dir, &Step::Git(args, None), target) + } else { + args.push("--file=-".into()); + run_step(dir, &Step::Git(args, Some(message.to_string())), target) + } +} + +fn update_paths( + dir: &Path, + group: Group, + files: &[FileChange], + discard: bool, + target: Option<&WslTarget>, +) -> Result { + let status = read_status(dir, target)?; + let current = status.files(group); + let selected: std::collections::HashMap<_, _> = current + .iter() + .map(|file| (file.path.as_str(), file)) + .collect(); + if files.iter().any(|file| { + selected + .get(file.path.as_str()) + .is_none_or(|current| discard && *current != file) + }) { + return Err( + tr("The selected files changed. Review Source Control and try again.").to_string(), + ); + } + let paths = file_paths(files); + if paths.is_empty() { + return Ok(String::new()); + } + let args: &[&str] = match (group, discard) { + (Group::Staged, false) if status.head.is_none() => &["rm", "--cached", "-f"], + (Group::Staged, false) => &["restore", "--staged"], + (_, false) => &["add", "-A"], + (Group::Untracked, true) => { + if paths + .iter() + .any(|path| dir.join(path).symlink_metadata().is_ok_and(|m| m.is_dir())) + { + return Err( + tr("Discard untracked files individually inside nested repositories.") + .to_string(), + ); + } + // Git clean only accepts pathspecs as arguments, which are size-limited on Windows. + for path in paths { + run_step( + dir, + &git_step(&["--literal-pathspecs", "clean", "-f", "--", path]), + target, + )?; + } + return Ok(String::new()); + } + (Group::Changes, true) => &["restore", "--worktree"], + (Group::Conflicts, true) => &["restore", "--merge", "--worktree"], + (Group::Staged, true) => { + if status + .changes + .iter() + .chain(&status.untracked) + .chain(&status.conflicts) + .any(|file| { + file_paths(std::slice::from_ref(file)) + .iter() + .any(|p| paths.contains(p)) + }) + { + return Err( + tr("Discard or stage the working tree changes to these files first.") + .to_string(), + ); + } + if status.head.is_none() { + &["rm"] + } else { + &["restore", "--staged", "--worktree"] + } + } + }; + let mut argv = vec!["--literal-pathspecs".into()]; + argv.extend(args.iter().map(|s| s.to_string())); + argv.extend([ + "--pathspec-from-file=-".into(), + "--pathspec-file-nul".into(), + ]); + let mut input = paths.join("\0"); + input.push('\0'); + run_step(dir, &Step::Git(argv, Some(input)), target) +} + +#[derive(Default)] +pub(crate) struct Snapshot { + pub repo: Option, + pub status: RepoStatus, + pub log: Option>, + pub incoming: (Vec, Option), +} + +pub(crate) fn snapshot( + dir: &Path, + with_log: bool, + target: Option<&WslTarget>, +) -> Result { + let resolve = |p: &str| match target { + Some(t) => t.unc_path(p), + None => PathBuf::from(p), + }; + let top = match run_step(dir, &git_step(&["rev-parse", "--show-toplevel"]), target) { + Ok(top) => top, + Err(error) if error.contains("not a git repository") => { + return Ok(Snapshot::default()); + } + Err(error) => return Err(error), + }; + let repo = resolve(top.trim_end_matches(['\r', '\n'])); + let status = read_status(&repo, target)?; + let log = with_log.then(|| { + run_step( + &repo, + &git_step(&[ + "-c", + "i18n.logOutputEncoding=UTF-8", + "log", + "-n", + "80", + "--topo-order", + "--format=%H%x1f%h%x1f%s%x1f%an%x1f%ar%x1f%D%x1f%P", + "-z", + ]), + target, + ) + .map(|s| parse_log(&s)) + .unwrap_or_default() + }); + let incoming = if status.behind > 0 { + crate::scm_incoming::incoming(&repo, target) + } else { + Default::default() + }; + Ok(Snapshot { + repo: Some(repo), + status, + log, + incoming, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn porcelain_v2() { + let out = "# branch.oid abc\0# branch.head main\0# branch.upstream origin/main\0# branch.ab +2 -21\0\ +1 .M N... 100644 100644 100644 a b src/app.py\0\ +1 A. N... 000000 100644 100644 0 b new.txt\0\ +1 MM N... 100644 100644 100644 a b both.rs\0\ +2 R. N... 100644 100644 100644 a b R100 renamed.py\0old.py\0\ +? notes.md\0u UU N... 100644 100644 100644 100644 a b c conflict.txt\0"; + let st = parse_status(out); + assert_eq!(st.branch.as_deref(), Some("main")); + assert_eq!(st.upstream.as_deref(), Some("origin/main")); + assert!(st.upstream_available); + assert_eq!((st.ahead, st.behind), (2, 21)); + assert_eq!( + st.staged + .iter() + .map(|c| (c.path.as_str(), c.code)) + .collect::>(), + vec![("new.txt", 'A'), ("both.rs", 'M'), ("renamed.py", 'R')] + ); + assert_eq!(st.staged[2].orig.as_deref(), Some("old.py")); + assert_eq!( + st.changes + .iter() + .map(|c| (c.path.as_str(), c.code)) + .collect::>(), + vec![("src/app.py", 'M'), ("both.rs", 'M')] + ); + assert_eq!(st.untracked[0].path, "notes.md"); + assert_eq!(st.conflicts[0].code, 'U'); + assert_eq!(st.conflicts[0].path, "conflict.txt"); + assert_eq!(st.count(), 7); + } + + #[test] + fn spaces_in_paths() { + let st = parse_status("1 .M N... 100644 100644 100644 a b my folder/a file.py\0"); + assert_eq!(st.changes[0].path, "my folder/a file.py"); + } + + #[test] + fn hunk_stage_and_unstage_preserve_other_edits() { + let repo = TestRepo::new(); + let before = (1..=25).map(|n| format!("line {n}\n")).collect::(); + repo.write("file.txt", &before); + repo.change(Group::Untracked, false).unwrap(); + commit(&repo.0, "initial", false, true, None).unwrap(); + assert!(repo + .git(&["log", "-1", "--format=%B"]) + .contains("Signed-off-by:")); + let after = before + .replace("line 2\n", "first edit\n") + .replace("line 23\n", "second edit\n"); + repo.write("file.txt", &after); + let patch = file_diff(&repo.0, &repo.status().changes[0], Group::Changes, None) + .unwrap() + .0; + apply_hunk(&repo.0, "file.txt", Group::Changes, &patch, 1, None).unwrap(); + assert!(apply_hunk(&repo.0, "file.txt", Group::Changes, &patch, 0, None).is_err()); + let staged = file_diff(&repo.0, &repo.status().staged[0], Group::Staged, None) + .unwrap() + .0; + assert!(staged.contains("+second edit")); + assert!(!staged.contains("+first edit")); + apply_hunk(&repo.0, "file.txt", Group::Staged, &staged, 0, None).unwrap(); + assert!(repo.status().staged.is_empty()); + assert_eq!( + std::fs::read_to_string(repo.0.join("file.txt")).unwrap(), + after + ); + } + + #[test] + fn remote_error_keeps_git_diagnostics_and_adds_the_next_step() { + let rejected = "git push: ! [rejected] main -> main (fetch first)"; + let explained = remote_error(rejected.into()); + assert!(explained.starts_with(rejected)); + assert!(explained.ends_with(tr( + "The remote branch has new commits. Pull or Sync before pushing again." + ))); + let auth = remote_error("Permission denied (publickey).".into()); + assert!(auth.ends_with(tr( + "Check Git credentials or your SSH connection in a terminal, then retry." + ))); + assert_eq!( + remote_error("Could not resolve host".into()), + "Could not resolve host" + ); + } + + struct TestRepo(PathBuf); + + impl TestRepo { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "fluxcode-scm-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir(&path).unwrap(); + let repo = Self(path); + assert!(snapshot(&repo.0, false, None).unwrap().repo.is_none()); + repo.git(&["init", "-b", "main", "--template="]); + repo.git(&["config", "user.name", "FluxCode Test"]); + repo.git(&["config", "user.email", "fluxcode@example.invalid"]); + repo.git(&["config", "commit.gpgsign", "false"]); + repo + } + + fn git(&self, args: &[&str]) -> String { + run_step(&self.0, &git_step(args), None).unwrap() + } + + fn status(&self) -> RepoStatus { + read_status(&self.0, None).unwrap() + } + + fn write(&self, file: &str, text: &str) { + std::fs::write(self.0.join(file), text).unwrap(); + } + + fn change(&self, group: Group, discard: bool) -> Result { + update_paths(&self.0, group, self.status().files(group), discard, None) + } + } + + impl Drop for TestRepo { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn remote_preflight_explains_missing_remote_origin_and_upstream() { + let repo = TestRepo::new(); + for action in [ + RemoteAction::Fetch, + RemoteAction::Pull, + RemoteAction::Push, + RemoteAction::Sync, + ] { + assert_eq!(run_remote(&repo.0, action, None).unwrap_err(), + tr("No Git remote is configured. Add a remote before fetching, pulling, or pushing.")); + } + repo.git(&["remote", "add", "alternate", "./missing-local-remote.git"]); + repo.write("staged.txt", "first\n"); + repo.change(Group::Untracked, false).unwrap(); + commit(&repo.0, "first", false, false, None).unwrap(); + assert_eq!( + run_remote(&repo.0, RemoteAction::Pull, None).unwrap_err(), + tr("This branch has no upstream. Set one or publish the branch before pulling.") + ); + assert_eq!( + run_remote(&repo.0, RemoteAction::Sync, None).unwrap_err(), + tr("No origin remote is configured. Set the branch upstream before pushing.") + ); + } + + #[test] + fn initial_branch_requires_stage_and_message_and_can_unstage() { + let repo = TestRepo::new(); + assert!(!repo.status().check_commit("first", false).is_ok()); + assert!(repo.status().check_commit("amend", true).is_err()); + repo.write("a[1].txt", "one\n"); + repo.write("a1.txt", "two\n"); + let before = repo.status(); + let one = before + .untracked + .iter() + .find(|file| file.path == "a[1].txt") + .unwrap(); + update_paths( + &repo.0, + Group::Untracked, + std::slice::from_ref(one), + false, + None, + ) + .unwrap(); + assert_eq!(repo.status().staged.len(), 1); + assert!(repo.status().check_commit(" ", false).is_err()); + assert!(repo.status().check_commit("first", false).is_ok()); + assert!(repo.status().head.is_none()); + repo.change(Group::Staged, false).unwrap(); + assert_eq!(repo.status().untracked.len(), 2); + repo.change(Group::Untracked, false).unwrap(); + commit(&repo.0, "first", false, false, None).unwrap(); + assert!(repo.status().head.is_some()); + assert_eq!(repo.status().count(), 0); + repo.git(&["checkout", "--detach"]); + repo.write("a1.txt", "amended\n"); + repo.change(Group::Changes, false).unwrap(); + assert!(repo.status().branch.is_none()); + commit(&repo.0, "amended", true, false, None).unwrap(); + assert_eq!(repo.git(&["log", "-1", "--format=%s"]).trim(), "amended"); + } + + #[test] + fn rename_and_discard_keep_index_and_worktree_separate() { + let repo = TestRepo::new(); + repo.write("old name.txt", "original\n"); + repo.change(Group::Untracked, false).unwrap(); + commit(&repo.0, "first", false, false, None).unwrap(); + repo.git(&["mv", "old name.txt", "new name.txt"]); + let status = repo.status(); + let renamed = &status.staged[0]; + assert_eq!(renamed.orig.as_deref(), Some("old name.txt")); + let (patch, _, _) = file_diff(&repo.0, renamed, Group::Staged, None).unwrap(); + assert!(patch.contains("rename from old name.txt\nrename to new name.txt")); + repo.write("new name.txt", "worktree edit\n"); + repo.write("untracked.txt", "untracked\n"); + assert!(repo.change(Group::Staged, true).is_err()); + assert_eq!(repo.status().staged[0].code, 'R'); + let unstaged = repo.status(); + assert_eq!(unstaged.changes[0].orig, None); + let (patch, _, _) = file_diff(&repo.0, &unstaged.changes[0], Group::Changes, None).unwrap(); + assert!(patch.contains("-original\n+worktree edit")); + repo.change(Group::Changes, true).unwrap(); + assert!(repo.0.join("untracked.txt").is_file()); + repo.change(Group::Staged, true).unwrap(); + assert!(repo.0.join("old name.txt").is_file()); + assert!(!repo.0.join("new name.txt").exists()); + repo.change(Group::Untracked, true).unwrap(); + assert_eq!(repo.status().count(), 0); + } + + #[test] + fn resetting_conflict_edits_keeps_the_index_unmerged() { + let repo = TestRepo::new(); + repo.write("same.txt", "base\n"); + repo.change(Group::Untracked, false).unwrap(); + commit(&repo.0, "base", false, false, None).unwrap(); + repo.git(&["checkout", "-b", "topic"]); + repo.write("same.txt", "topic\n"); + repo.change(Group::Changes, false).unwrap(); + commit(&repo.0, "topic", false, false, None).unwrap(); + repo.git(&["checkout", "main"]); + repo.write("same.txt", "main\n"); + repo.change(Group::Changes, false).unwrap(); + commit(&repo.0, "main", false, false, None).unwrap(); + assert!(run_step(&repo.0, &git_step(&["merge", "--no-edit", "topic"]), None).is_err()); + let unmerged = repo.status(); + assert_eq!(unmerged.conflicts.len(), 1); + assert!(unmerged.check_commit("merge", false).is_err()); + repo.write("same.txt", "candidate resolution\n"); + repo.change(Group::Conflicts, true).unwrap(); + let restored = std::fs::read_to_string(repo.0.join("same.txt")).unwrap(); + assert!(restored.contains("<<<<<<<")); + assert_eq!(repo.status().conflicts.len(), 1); + let save = |expected: String| Step::Resolve { + path: "same.txt".into(), + expected, + resolved: "resolved\n".into(), + }; + assert!(run_step(&repo.0, &save("stale".into()), None).is_err()); + assert_eq!( + std::fs::read_to_string(repo.0.join("same.txt")).unwrap(), + restored + ); + run_step(&repo.0, &save(restored), None).unwrap(); + assert!(repo.status().conflicts.is_empty()); + assert_eq!(repo.git(&["show", ":same.txt"]), "resolved\n"); + assert!(repo.status().check_commit("merge", false).is_ok()); + } + + #[test] + fn amend_allows_message_only_and_no_edit_staged() { + let repo = TestRepo::new(); + repo.write("a.txt", "v1\n"); + repo.change(Group::Untracked, false).unwrap(); + commit(&repo.0, "first", false, false, None).unwrap(); + + assert!(repo.status().check_commit("", true).is_err()); + assert!(repo.status().check_commit("reworded", true).is_ok()); + commit(&repo.0, "reworded", true, false, None).unwrap(); + assert_eq!(repo.git(&["log", "-1", "--format=%s"]).trim(), "reworded"); + + repo.write("a.txt", "v2\n"); + repo.change(Group::Changes, false).unwrap(); + assert!(repo.status().check_commit("", true).is_ok()); + commit(&repo.0, "", true, false, None).unwrap(); + assert_eq!(repo.git(&["log", "-1", "--format=%s"]).trim(), "reworded"); + assert_eq!(repo.git(&["show", "HEAD:a.txt"]), "v2\n"); + + let clean = repo.status(); + assert_eq!( + clean.check_smart_commit("msg", false, false), + Err("There are no changes to commit.") + ); + assert_eq!(clean.check_smart_commit("msg", false, true), Ok(true)); + repo.write("a.txt", "v3\n"); + assert_eq!( + repo.status().check_smart_commit("msg", false, false), + Ok(true) + ); + repo.change(Group::Changes, false).unwrap(); + assert_eq!( + repo.status().check_smart_commit("msg", false, false), + Ok(false) + ); + } + + #[test] + fn show_commit_diff_bounds_size_and_surfaces_errors() { + let repo = TestRepo::new(); + repo.write("small.txt", "one\ntwo\n"); + repo.change(Group::Untracked, false).unwrap(); + commit(&repo.0, "init", false, false, None).unwrap(); + let patch = show_commit_diff(&repo.0, "HEAD", Some("small.txt"), true, None).unwrap(); + assert!(patch.contains("+one\n+two")); + assert!(show_commit_diff(&repo.0, "deadbeefdeadbeef", None, true, None).is_err()); + } +} diff --git a/src/scm_incoming.rs b/src/scm_incoming.rs index 79340a6..390009c 100644 --- a/src/scm_incoming.rs +++ b/src/scm_incoming.rs @@ -1,12 +1,12 @@ use crate::i18n::tr; -use crate::scm::{code_color, Commit}; +use crate::scm::{code_color, lane_geometry, Commit, ROW_H, SCROLLBAR_PAD}; use crate::theme::{self, c}; use crate::workbench::*; use gpui_kit::assets::IconName as Ico; use gpui_kit::component::{ button::{Button, ButtonVariants}, - h_flex, v_flex, Icon, IconName, Sizable, + h_flex, v_flex, Disableable, Icon, IconName, Sizable, }; use gpui_kit::{prelude::FluentBuilder, *}; use std::path::Path; @@ -16,48 +16,7 @@ const EVERY: Duration = Duration::from_secs(300); pub const MAX_INCOMING: usize = 50; fn quiet_git(dir: &Path, args: &[&str], target: Option<&crate::remote::WslTarget>) -> Result { - if let Some(t) = target { - let cwd = t.linux_path(dir).unwrap_or_else(|| t.linux_root.clone()); - let owned: Vec = args.iter().map(|s| s.to_string()).collect(); - let attempt: Option> = - crate::remote::with_client(&t.distro.clone(), |c: &mut crate::remote::RemoteClient| c.git(&cwd, &owned, None)); - if let Some(r) = attempt { - match r { - Ok(g) if g.success => return Ok(g.stdout), - Ok(g) => return Err(g.stderr.trim().to_string()), - Err(_) => {} - } - } - } - let mut cmd = match target { - Some(t) => { - let cwd = t.linux_path(dir).unwrap_or_else(|| t.linux_root.clone()); - crate::remote::program_command_env( - t, - &cwd, - &[("GIT_OPTIONAL_LOCKS", "0"), ("GIT_TERMINAL_PROMPT", "0"), ("GCM_INTERACTIVE", "never"), ("NO_COLOR", "1")], - "git", - args, - ) - } - None => { - let mut c = crate::proc::command("git"); - c.args(args).current_dir(dir); - c - } - }; - cmd.env("GIT_OPTIONAL_LOCKS", "0") - .env("GIT_TERMINAL_PROMPT", "0") - .env("GCM_INTERACTIVE", "never") - .env("NO_COLOR", "1") - .stdin(std::process::Stdio::null()); - crate::github::apply_env(&mut cmd); - let out = cmd.output().map_err(|e| e.to_string())?; - if out.status.success() { - Ok(String::from_utf8_lossy(&out.stdout).into_owned()) - } else { - Err(String::from_utf8_lossy(&out.stderr).trim().to_string()) - } + crate::scm_git::run_step(dir, &crate::scm_git::git_step(args), target) } pub fn incoming(repo: &Path, target: Option<&crate::remote::WslTarget>) -> (Vec, Option) { @@ -111,18 +70,24 @@ impl Workbench { pub(crate) fn scm_fetch_quietly(&mut self, cx: &mut Context) { let Some(repo) = self.scm.repo.clone() else { return }; - if self.scm.fetching || self.scm.status.upstream.is_none() || self.scm.busy.is_some() { + if self.scm.is_busy() || self.scm.status.upstream.is_none() { return; } self.scm.fetching = true; + cx.notify(); self.scm.last_fetch = Some(Instant::now()); + let generation = self.scm.workspace_generation; let wsl = self.wsl.clone(); cx.spawn(async move |this, cx| { - let res = cx.background_spawn(async move { quiet_git(&repo, &["fetch", "--quiet", "--prune"], wsl.as_ref()) }).await; + let res = cx.background_spawn(async move { crate::scm_git::run_step(&repo, &crate::scm_git::Step::Remote(crate::scm_git::RemoteAction::Fetch), wsl.as_ref()) }).await; _ = this.update(cx, |this, cx| { + if this.scm.workspace_generation != generation { + return; + } this.scm.fetching = false; _ = res; this.scm_refresh(cx); + cx.notify(); }); }) .detach(); @@ -149,49 +114,91 @@ impl Workbench { return; } let Some(repo) = self.scm.repo.clone() else { return }; + let generation = self.scm.workspace_generation; let wsl = self.wsl.clone(); cx.spawn(async move |this, cx| { let h = hash.clone(); - let files = cx - .background_spawn(async move { quiet_git(&repo, &["-c", "core.quotepath=off", "show", "--format=", "--name-status", "-z", &h], wsl.as_ref()).map(|s| parse_name_status(&s)).unwrap_or_default() }) + let res = cx + .background_spawn(async move { + quiet_git(&repo, &["-c", "core.quotepath=off", "show", "--format=", "--name-status", "-z", &h], wsl.as_ref()) + .map(|s| parse_name_status(&s)) + .map(|files| (repo, files)) + }) .await; _ = this.update(cx, |this, cx| { - this.scm.incoming_files.insert(hash, files); + match res { + Ok((repo, files)) => { + if this.scm.workspace_generation != generation || this.scm.repo.as_ref() != Some(&repo) { + return; + } + this.scm.incoming_files.insert(hash, files); + } + Err(e) => { + if this.scm.workspace_generation == generation { + this.scm.incoming_open = None; + this.scm.error = Some(e); + } + } + } cx.notify(); }); }) .detach(); } - fn scm_show_incoming_file(&mut self, hash: String, path: String, cx: &mut Context) { + fn scm_show_incoming_file( + &mut self, + hash: String, + path: String, + window: &mut Window, + cx: &mut Context, + ) { let Some(repo) = self.scm.repo.clone() else { return }; + let generation = self.scm.workspace_generation; let wsl = self.wsl.clone(); - cx.spawn(async move |this, cx| { - let (h, p) = (hash.clone(), path.clone()); - let text = cx.background_spawn(async move { quiet_git(&repo, &["-c", "core.quotepath=off", "show", "--format=%h %s%n%an, %ar%n", &h, "--", &p], wsl.as_ref()).unwrap_or_else(|e| e) }).await; - _ = this.update(cx, |this, cx| { - this.out_lines.clear(); - let mut head = Line::new(&path, crate::term::LineKind::Cmd); - head.meta = crate::trf!("In {hash}, not pulled yet"; hash => &hash[..hash.len().min(8)]).into(); - this.out_lines.push(head); - for l in text.lines() { - let kind = if l.starts_with("+++") || l.starts_with("---") || l.starts_with("diff ") || l.starts_with("index ") { - crate::term::LineKind::Dim - } else if l.starts_with('+') { - crate::term::LineKind::Success - } else if l.starts_with('-') { - crate::term::LineKind::Err - } else if l.starts_with("@@") { - crate::term::LineKind::Hunk - } else { - crate::term::LineKind::Normal - }; - this.out_lines.push(Line::new(l, kind)); + let short = hash[..hash.len().min(7)].to_string(); + let file_name = path.rsplit('/').next().unwrap_or(&path).to_string(); + let full_path = repo.join(&path); + let target = if wsl.is_some() || full_path.is_file() { + Some(full_path) + } else { + None + }; + let virtual_key = std::path::PathBuf::from(format!("flux-diff://incoming/{hash}/{path}")); + cx.spawn_in(window, async move |this, cx| { + let (h, p, r) = (hash.clone(), path.clone(), repo.clone()); + let res = cx + .background_spawn(async move { + crate::scm_git::show_commit_diff(&r, &h, Some(&p), false, wsl.as_ref()) + }) + .await; + _ = this.update_in(cx, |this, window, cx| { + if this.scm.workspace_generation != generation || this.scm.repo.as_ref() != Some(&repo) { + return; } - this.panel_open = true; - this.panel_tab = PanelTab::Output; - this.out_scroll.scroll_to_item(0, ScrollStrategy::Top); - cx.notify(); + let patch = match res { + Ok(patch) => patch, + Err(e) => { + this.scm.error = Some(e); + cx.notify(); + return; + } + }; + this.open_scm_diff_tab( + crate::diff_view::ScmDiffSpec { + virtual_key, + tab_title: format!("{file_name} ({short})"), + display_name: path, + badge: short, + patch, + conflict_text: None, + target, + scm_stage: None, + multi_file: false, + }, + window, + cx, + ); }); }) .detach(); @@ -211,8 +218,10 @@ impl Workbench { .group("scm-in-head") .px_2() .gap_1() + .items_center() .text_xs() .cursor_pointer() + .hover(|st| st.bg(c(theme::BG_HOVER))) .child(Icon::new(if open_list { IconName::ChevronDown } else { IconName::ChevronRight }).flex_none().size(theme::u(14.)).text_color(c(theme::FG_MUTED))) .child(div().flex_none().font_weight(FontWeight::SEMIBOLD).text_color(c(theme::FG_MUTED)).child(tr("Incoming"))) .child(div().flex_1().min_w_0().truncate().text_color(c(theme::FG_DIM)).child(upstream.clone())) @@ -227,19 +236,26 @@ impl Workbench { .label(tr("Pull")) .xsmall() .ghost() + .disabled(s.is_busy()) .tooltip(if dirty { tr("Pull them in (your changes are set aside and put back: git pull --autostash)") } else { tr("Pull them in (git pull)") }) .on_click(cx.listener(|this, _, w, cx| this.on_scm_pull(&ScmPull, w, cx))); - let later = Button::new("scm-in-later").icon(Icon::new(IconName::Close)).xsmall().ghost().tooltip(tr("Not now: hide this until more commits arrive")).on_click(cx.listener(|this, _, _, cx| { - this.scm.incoming_dismissed = this.scm.incoming_head.clone(); - cx.notify(); - })); - let mut col = v_flex().flex_none().pb_2().child( + let later = Button::new("scm-in-later") + .icon(Icon::new(IconName::Close)) + .xsmall() + .ghost() + .tooltip(tr("Not now: hide this until more commits arrive")) + .on_click(cx.listener(|this, _, _, cx| { + this.scm.incoming_dismissed = this.scm.incoming_head.clone(); + cx.notify(); + })); + let mut col = v_flex().w_full().min_w_0().flex_none().pb_2().child( h_flex() - .flex_none() .w_full() .min_w_0() - .pr_1() + .flex_none() + .pr(px(SCROLLBAR_PAD)) .gap_0p5() + .items_center() .child(header.flex_1().min_w_0()) .child(pull) .child(later), @@ -247,27 +263,74 @@ impl Workbench { if !open_list { return Some(col.into_any_element()); } - let last = s.incoming.len().saturating_sub(1); + let total = s.incoming.len(); + let last = total.saturating_sub(1); for (i, cm) in s.incoming.iter().enumerate() { let open = s.incoming_open.as_deref() == Some(cm.hash.as_str()); let hash = cm.hash.clone(); - let lane = crate::scm::graph_lane(i == 0, i == last && !open, theme::BLUE, 0.45, false); - let tip: SharedString = format!("{}\n{} · {} · {}", cm.subject, cm.short, cm.author, cm.when).into(); + let (line_top, line_bottom, dot_top) = lane_geometry(i, total, open); + let lane = div() + .relative() + .w(theme::u(14.)) + .h_full() + .flex_none() + .child( + div() + .absolute() + .left(theme::u(6.)) + .w(px(2.)) + .top(theme::u(line_top)) + .bottom(theme::u(line_bottom)) + .bg(c(theme::BLUE).opacity(0.45)), + ) + .child( + div() + .absolute() + .left(theme::u(3.)) + .top(theme::u(dot_top)) + .size(theme::u(8.)) + .rounded_full() + .border_2() + .border_color(c(theme::BLUE)) + .bg(c(theme::BG_SIDE)), + ); + let tip: SharedString = + format!("{}\n{} · {} · {}", cm.subject, cm.short, cm.author, cm.when).into(); col = col.child( crate::scm::scm_row() .id(("scm-in", i)) .pl(theme::u(12.)) - .pr_2() + .pr(px(SCROLLBAR_PAD)) .gap_1p5() + .items_center() .text_size(theme::u(11.5)) .cursor_pointer() .when(open, |h| h.bg(c(theme::BG_HOVER))) .hover(|st| st.bg(c(theme::BG_HOVER))) .child(lane) - .child(div().flex_1().min_w(theme::u(60.)).truncate().text_color(c(theme::FG)).child(cm.subject.clone())) - .child(div().flex_none().max_w(theme::u(90.)).truncate().text_color(c(theme::FG_DIM)).child(cm.author.clone())) - .tooltip(move |w, cx| gpui_kit::component::tooltip::Tooltip::new(tip.clone()).build(w, cx)) - .on_click(cx.listener(move |this, _, _, cx| this.scm_open_incoming(hash.clone(), cx))), + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_color(c(theme::FG)) + .child(cm.subject.clone()), + ) + .child( + div() + .flex_shrink(1.) + .min_w_0() + .max_w(theme::u(90.)) + .truncate() + .text_color(c(theme::FG_DIM)) + .child(cm.author.clone()), + ) + .tooltip(move |w, cx| { + gpui_kit::component::tooltip::Tooltip::new(tip.clone()).build(w, cx) + }) + .on_click( + cx.listener(move |this, _, _, cx| this.scm_open_incoming(hash.clone(), cx)), + ), ); if !open { continue; @@ -278,7 +341,7 @@ impl Workbench { col = col.child( div() .flex_none() - .h(theme::u(crate::scm::ROW_H)) + .h(theme::u(ROW_H)) .pl(pad) .flex() .items_center() @@ -298,27 +361,74 @@ impl Workbench { .relative() .when(i < last, |h| h.child(div().absolute().left(theme::u(18.)).top_0().bottom_0().w(px(2.)).bg(c(theme::BLUE).opacity(0.45)))) .pl(pad) - .pr_2() + .pr(px(SCROLLBAR_PAD)) .gap_1p5() + .items_center() .text_xs() .cursor_pointer() .hover(|st| st.bg(c(theme::BG_HOVER))) .child(crate::files::file_icon_el(&name, theme::u(14.))) - .child(div().flex_none().max_w(relative(0.6)).truncate().text_color(c(theme::FG)).child(name)) - .child(div().flex_1().min_w_0().truncate().text_color(c(theme::FG_DIM)).child(dir)) - .child(div().flex_none().w(theme::u(12.)).font_weight(FontWeight::BOLD).text_color(c(code_color(*code))).child(code.to_string())) - .tooltip(|w, cx| gpui_kit::component::tooltip::Tooltip::new(tr("Show what changed")).build(w, cx)) - .on_click(cx.listener(move |this, _, _, cx| this.scm_show_incoming_file(h.clone(), p.clone(), cx))), + .child( + div() + .flex_shrink(1.) + .min_w_0() + .max_w(relative(0.6)) + .truncate() + .text_color(c(theme::FG)) + .child(name), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_color(c(theme::FG_DIM)) + .child(dir), + ) + .child( + div() + .flex_none() + .w(theme::u(12.)) + .text_right() + .font_weight(FontWeight::BOLD) + .text_color(c(code_color(*code))) + .child(code.to_string()), + ) + .tooltip(|w, cx| { + gpui_kit::component::tooltip::Tooltip::new(tr( + "Show what changed", + )) + .build(w, cx) + }) + .on_click(cx.listener(move |this, _, w, cx| { + this.scm_show_incoming_file(h.clone(), p.clone(), w, cx) + })), ); } if files.len() > 60 { - col = col.child(div().flex_none().pl(pad).py_1().text_xs().text_color(c(theme::FG_DIM)).child(crate::trf!("… and {n} more files"; n => files.len() - 60))); + col = col.child( + div() + .flex_none() + .pl(pad) + .py_1() + .text_xs() + .text_color(c(theme::FG_DIM)) + .child(crate::trf!("… and {n} more files"; n => files.len() - 60)), + ); } } } } if n > s.incoming.len() { - col = col.child(div().flex_none().pl(theme::u(34.)).py_1().text_xs().text_color(c(theme::FG_DIM)).child(crate::trf!("… and {n} older ones"; n => n - s.incoming.len()))); + col = col.child( + div() + .flex_none() + .pl(theme::u(34.)) + .py_1() + .text_xs() + .text_color(c(theme::FG_DIM)) + .child(crate::trf!("… and {n} older ones"; n => n - s.incoming.len())), + ); } Some(col.into_any_element()) } diff --git a/src/workbench.rs b/src/workbench.rs index 37c071c..39a6b56 100644 --- a/src/workbench.rs +++ b/src/workbench.rs @@ -38,7 +38,7 @@ actions!( ExplorerDelete, ExplorerRefresh, ExplorerUp, ExplorerDown, ExplorerLeft, ExplorerRight, ExplorerOpen, CopyPath, CopyRelativePath, CancelPending, RevealInExplorer, ShowSettings, About, TogglePreview, ReloadPreview, NextTheme, NextIconTheme, ChooseTheme, ChooseIconTheme, TabAccept, TermHistoryPrev, TermHistoryNext, TermComplete, TermInterrupt, TermEscape, TermClear, - GoToProblem, ScmShow, ScmCommitPush, ScmCommitSync, ScmCommitAmend, ScmPull, ScmPush, ScmSync, ScmFetch, + GoToProblem, ScmShow, ScmCommitPush, ScmCommitSync, ScmCommitAmend, ScmCommitDefault, ScmCommitSignoff, ScmPull, ScmPush, ScmSync, ScmFetch, ScmStageAll, ScmUnstageAll, ScmCreatePr, ScmOpenGithub, ScmRemoveGit, QuickOpenFile, QuickClose, QuickUp, QuickDown, AgentUseOpenCode, AgentMentionUp, AgentMentionDown, AgentMentionAccept, AgentMentionClose, AgentForceSend, AgentMenuUp, AgentMenuDown, AgentMenuPick, AgentMenuClose, @@ -70,6 +70,7 @@ pub fn bind_keys(cx: &mut App) { KeyBinding::new("ctrl-shift-a", ShowAgent, None), KeyBinding::new("ctrl-l", ToggleAgent, None), KeyBinding::new("ctrl-shift-g", ScmShow, None), + KeyBinding::new("ctrl-enter", ScmCommitDefault, Some("ScmMessage > Input")), KeyBinding::new("ctrl-p", QuickOpenFile, None), KeyBinding::new("up", QuickUp, Some("QuickOpen > Input")), KeyBinding::new("down", QuickDown, Some("QuickOpen > Input")), @@ -862,6 +863,9 @@ impl Workbench { } pub(crate) fn open_folder(&mut self, root: PathBuf, cx: &mut Context) { + if self.root.as_ref() != Some(&root) { + self.scm_reset_workspace(); + } self.root = Some(root.clone()); let previous = std::mem::replace(&mut self.wsl, crate::remote::WslTarget::from_path(&root)); if previous.as_ref().map(|t| t.distro.clone()) != self.wsl.as_ref().map(|t| t.distro.clone()) { @@ -4115,7 +4119,8 @@ impl Workbench { let st = &self.scm.status; let dirty = if st.count() > 0 { "*" } else { "" }; let sync = match &st.upstream { - None => "Publish".to_string(), + None => tr("Publish Branch").to_string(), + Some(_) if !st.upstream_available => tr("Upstream unavailable").to_string(), Some(_) => format!("{}↓ {}↑", st.behind, st.ahead), }; h.child( @@ -4138,7 +4143,7 @@ impl Workbench { cx.listener(|this, _, w, cx| this.on_scm_show(&ScmShow, w, cx)), ), ) - .when(medium, |h| { + .when(st.branch.is_some() && st.head.is_some(), |h| { h.child( h_flex() .id("sb-sync") @@ -4147,8 +4152,9 @@ impl Workbench { .h_full() .px_2() .gap_1() - .cursor_pointer() - .hover(|s| s.bg(c(theme::BG_HOVER))) + .when(!self.scm.is_busy(), |h| { + h.cursor_pointer().hover(|s| s.bg(c(theme::BG_HOVER))) + }) .child( Icon::new(if st.upstream.is_some() { gpui_kit::assets::IconName::RefreshCcw @@ -4158,14 +4164,14 @@ impl Workbench { .flex_none() .size(theme::u(13.)), ) - .child(if self.scm.busy.is_some() { + .child(if self.scm.is_busy() { "…".to_string() } else { sync }) - .on_click( - cx.listener(|this, _, w, cx| this.on_scm_sync(&ScmSync, w, cx)), - ), + .when(!self.scm.is_busy(), |h| { + h.on_click(cx.listener(|this, _, w, cx| this.on_scm_sync(&ScmSync, w, cx))) + }), ) }) }, @@ -4426,6 +4432,7 @@ impl Render for Workbench { } if self.scm.clear_message { self.scm.clear_message = false; + self.scm.msg_non_empty = false; self.scm.message.update(cx, |s, cx| s.set_value("", window, cx)); } window.set_rem_size(theme::rem()); @@ -4750,6 +4757,7 @@ impl Render for Workbench { this.settings.full_right_w = w; } } + 5 => this.scm_drag_pane(f32::from(ev.position.y)), 6 => this.diff_drag_ruler(f32::from(ev.position.y), cx), _ => return, } @@ -4762,6 +4770,7 @@ impl Render for Workbench { this.agent.full.drag = None; this.settings.save(); } + 5 => this.scm.pane_drag = None, 6 => this.diff_ruler_drag = None, _ => {} } @@ -4770,6 +4779,8 @@ impl Render for Workbench { } })) .on_action(cx.listener(Self::on_quick_open)) + .on_action(cx.listener(Self::on_scm_commit_default)) + .on_action(cx.listener(Self::on_scm_commit_signoff)) .on_action(cx.listener(Self::on_quick_close)) .on_action(cx.listener(Self::on_quick_up)) .on_action(cx.listener(Self::on_quick_down)) @@ -5028,6 +5039,34 @@ fn remote_write(target: &crate::remote::WslTarget, path: &std::path::Path, bytes crate::remote::with_client(&distro, |c| c.write(&linux, bytes, crlf).ok()).flatten() } +pub(crate) fn read_file_bytes( + wsl: Option<&crate::remote::WslTarget>, + path: &Path, + limit: u64, +) -> Result, String> { + use std::io::Read as _; + if let Some(t) = wsl { + if let Some(bytes) = remote_read(t, path, limit.saturating_add(1)) { + return Ok(bytes); + } + } + let mut bytes = Vec::new(); + let meta = path.symlink_metadata().map_err(|e| e.to_string())?; + if meta.is_symlink() { + bytes = path + .read_link() + .map_err(|e| e.to_string())? + .to_string_lossy() + .as_bytes() + .to_vec(); + } else if meta.is_file() { + std::fs::File::open(path) + .and_then(|file| file.take(limit.saturating_add(1)).read_to_end(&mut bytes)) + .map_err(|e| e.to_string())?; + } + Ok(bytes) +} + pub(crate) fn write_doc_to_disk( wsl: Option<&crate::remote::WslTarget>, path: &Path, From f7ccc45b4f7a33b16caea31a312490d80b9105d4 Mon Sep 17 00:00:00 2001 From: ThinhNguyen2005 Date: Sat, 28 Nov 2026 01:11:04 +0700 Subject: [PATCH 3/7] initialize scm diff fields on the main viewer path --- src/diff_view.rs | 3 +++ src/panel.rs | 4 +--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/diff_view.rs b/src/diff_view.rs index 0a2e944..d662351 100644 --- a/src/diff_view.rs +++ b/src/diff_view.rs @@ -191,6 +191,9 @@ pub fn parse_with_state(text: &str, cx: &mut Context) -> DiffDoc { multi_file, empty_note: None, virtual_tab: false, + conflict_original: None, + scm_patch: None, + scm_stage: None, }; } let mut doc = parse(text); diff --git a/src/panel.rs b/src/panel.rs index afa34de..c1c2cc7 100644 --- a/src/panel.rs +++ b/src/panel.rs @@ -265,7 +265,6 @@ fn mono_kind(k: LineKind) -> bool { | LineKind::Dim | LineKind::Success | LineKind::Frame - | LineKind::Hunk | LineKind::Code | LineKind::Caret | LineKind::Blank @@ -2031,8 +2030,7 @@ impl Workbench { | LineKind::Warn | LineKind::Dim | LineKind::Success - | LineKind::Frame - | LineKind::Hunk => (cols.mono, 2), + | LineKind::Frame => (cols.mono, 2), LineKind::Code if !marked => (cols.mono, 2), LineKind::CardMsg | LineKind::CardHint => (cols.card, 0), LineKind::Result if l.err => (cols.result, 0), From 46a05f35393830947f764ea715775a4c4beb3b3e Mon Sep 17 00:00:00 2001 From: ThinhNguyen2005 Date: Sat, 28 Nov 2026 01:38:52 +0700 Subject: [PATCH 4/7] bound git diff capture and prevent wsl write retries --- src/i18n_id.rs | 4 +++ src/scm_git.rs | 92 ++++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 82 insertions(+), 14 deletions(-) diff --git a/src/i18n_id.rs b/src/i18n_id.rs index df1c44b..fbb3aa6 100644 --- a/src/i18n_id.rs +++ b/src/i18n_id.rs @@ -2246,6 +2246,10 @@ pub const ID: &[(&str, &str)] = &[ "Simpan editor yang belum tersimpan sebelum mengganti branch atau file Git.", ), ("The diff is too large to preview.", "Diff terlalu besar untuk ditampilkan."), + ( + "Git helper failed. Refresh to check the result: {error}", + "Helper Git gagal. Refresh untuk memeriksa hasilnya: {error}", + ), ( "The untracked file is too large to preview.", "File untracked terlalu besar untuk ditampilkan.", diff --git a/src/scm_git.rs b/src/scm_git.rs index 27a7a28..bf8c539 100644 --- a/src/scm_git.rs +++ b/src/scm_git.rs @@ -246,6 +246,7 @@ pub(crate) enum Step { nbt: Option, }, Git(Vec, Option), + Preview(Vec), Resolve { path: String, expected: String, @@ -350,17 +351,19 @@ pub(crate) fn run_step( discard, } => return update_paths(dir, *group, files, *discard, target), Step::Git(a, i) => ("git", a, i.clone()), + Step::Preview(a) => ("git", a, None), Step::Gh(a) => ("gh", a, None), }; - let target = matches!(step, Step::Git(..)).then_some(target).flatten(); + let preview = matches!(step, Step::Preview(_)); + let target = (prog == "git").then_some(target).flatten(); let refs: Vec<&str> = args.iter().map(String::as_str).collect(); let network = prog == "git" && matches!(refs.first(), Some(&("fetch" | "pull" | "push"))); let mut cmd = match &target { Some(t) => { let cwd = t.linux_path(dir).unwrap_or_else(|| t.linux_root.clone()); let owned: Vec = args.iter().map(|s| s.to_string()).collect(); - // The helper can time out before an operation finishes, so network writes are never retried. - if !network { + // Preview output is capped locally. An RPC failure can leave a Git write in flight. + if !network && !preview { if let Some(r) = crate::remote::with_client(&t.distro.clone(), |c| { c.git(&cwd, &owned, input.as_deref()) }) { @@ -379,7 +382,11 @@ pub(crate) fn run_step( g.stderr.trim() )) } - Err(_) => {} + Err(e) => { + return Err( + crate::trf!("Git helper failed. Refresh to check the result: {error}"; error => e), + ) + } } } } @@ -420,7 +427,11 @@ pub(crate) fn run_step( let _ = stdin.write_all(text.as_bytes()); } } - let out = child.wait_with_output().map_err(|e| e.to_string())?; + let out = if preview { + preview_output(child)? + } else { + child.wait_with_output().map_err(|e| e.to_string())? + }; let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); if out.status.success() { @@ -443,6 +454,45 @@ pub(crate) fn run_step( } } +fn preview_output(mut child: std::process::Child) -> Result { + use std::io::{self, Read}; + + let mut stdout = child.stdout.take().ok_or("Git stdout is unavailable")?; + let mut stderr = child.stderr.take().ok_or("Git stderr is unavailable")?; + std::thread::scope(|scope| { + let errors = scope.spawn(move || { + let mut captured = Vec::new(); + stderr.by_ref().take(8192).read_to_end(&mut captured)?; + io::copy(&mut stderr, &mut io::sink())?; + Ok::<_, io::Error>(captured) + }); + let mut captured = Vec::new(); + let read = stdout + .by_ref() + .take(MAX_DIFF_BYTES as u64 + 1) + .read_to_end(&mut captured); + let oversized = captured.len() > MAX_DIFF_BYTES; + if oversized || read.is_err() { + let _ = child.kill(); + } + drop(stdout); + let status = child.wait().map_err(|e| e.to_string()); + let stderr = errors + .join() + .map_err(|_| "Git stderr reader failed".to_string())? + .map_err(|e| e.to_string()); + if oversized { + return Err(tr("The diff is too large to preview.").into()); + } + read.map_err(|e| e.to_string())?; + Ok(std::process::Output { + status: status?, + stdout: captured, + stderr: stderr?, + }) + }) +} + fn remote_error(error: String) -> String { let lower = error.to_ascii_lowercase(); let hint = if lower.contains("non-fast-forward") || lower.contains("(fetch first)") { @@ -585,10 +635,11 @@ pub(crate) fn file_diff( } args.push("--"); args.extend(file_paths(std::slice::from_ref(file))); - let patch = run_step(dir, &git_step(&args), target)?; - if patch.len() > MAX_DIFF_BYTES { - return Err(tr("The diff is too large to preview.").to_string()); - } + let patch = run_step( + dir, + &Step::Preview(args.into_iter().map(str::to_string).collect()), + target, + )?; Ok((patch, conflict, open_path)) } @@ -636,11 +687,7 @@ pub(crate) fn show_commit_diff( args.push("--".into()); args.push(rel.into()); } - let patch = run_step(dir, &Step::Git(args, None), target)?; - if patch.len() > MAX_DIFF_BYTES { - return Err(tr("The diff is too large to preview.").to_string()); - } - Ok(patch) + run_step(dir, &Step::Preview(args), target) } fn patch_hunk(patch: &str, index: usize) -> Option { @@ -1192,5 +1239,22 @@ mod tests { let patch = show_commit_diff(&repo.0, "HEAD", Some("small.txt"), true, None).unwrap(); assert!(patch.contains("+one\n+two")); assert!(show_commit_diff(&repo.0, "deadbeefdeadbeef", None, true, None).is_err()); + + repo.write( + "small.txt", + &"large preview line\n".repeat(MAX_DIFF_BYTES / 16), + ); + let file = repo.status().changes.remove(0); + let too_large = tr("The diff is too large to preview."); + assert_eq!( + file_diff(&repo.0, &file, Group::Changes, None).unwrap_err(), + too_large + ); + repo.change(Group::Changes, false).unwrap(); + commit(&repo.0, "large patch", false, false, None).unwrap(); + assert_eq!( + show_commit_diff(&repo.0, "HEAD", Some("small.txt"), true, None).unwrap_err(), + too_large + ); } } From 1c894d1d1774af6507f289a958bdda2b9f080553 Mon Sep 17 00:00:00 2001 From: ThinhNguyen2005 Date: Sat, 28 Nov 2026 02:26:42 +0700 Subject: [PATCH 5/7] bound conflict previews and retry WSL reads --- src/scm.rs | 14 +++++- src/scm_git.rs | 119 ++++++++++++++++++++++++++++++++++++++++++---- src/ws_context.rs | 7 ++- 3 files changed, 130 insertions(+), 10 deletions(-) diff --git a/src/scm.rs b/src/scm.rs index b6eaab9..96422f6 100644 --- a/src/scm.rs +++ b/src/scm.rs @@ -2234,7 +2234,19 @@ impl Workbench { let rows = flexible.then(|| { let mut col = v_flex().w_full().min_w_0().pb_1(); if s.workflows.is_empty() && s.runs.is_empty() { - col = col.child(div().flex_shrink_0().px(theme::u(18.)).py_1().text_xs().text_color(c(theme::FG_DIM)).child(if s.actions_loaded { "No active workflows in this repository." } else { "Loading workflows…" })); + col = col.child( + div() + .flex_shrink_0() + .px(theme::u(18.)) + .py_1() + .text_xs() + .text_color(c(theme::FG_DIM)) + .child(if s.actions_loaded { + "No active workflows in this repository." + } else { + "Loading workflows…" + }), + ); } for (i, wf) in s.workflows.iter().enumerate() { let w = wf.clone(); diff --git a/src/scm_git.rs b/src/scm_git.rs index bf8c539..ae534b0 100644 --- a/src/scm_git.rs +++ b/src/scm_git.rs @@ -382,10 +382,11 @@ pub(crate) fn run_step( g.stderr.trim() )) } + Err(_) if read_only_git_args(args) => {} Err(e) => { return Err( crate::trf!("Git helper failed. Refresh to check the result: {error}"; error => e), - ) + ); } } } @@ -454,6 +455,52 @@ pub(crate) fn run_step( } } +fn read_only_git_args(args: &[String]) -> bool { + let mut args = args.iter().map(String::as_str).peekable(); + loop { + match args.peek().copied() { + Some("--literal-pathspecs" | "--no-pager") => { + args.next(); + } + Some("-c") => { + args.next(); + let Some(value) = args.next() else { + return false; + }; + if !matches!(value, "core.quotepath=off" | "i18n.logOutputEncoding=UTF-8") { + return false; + } + } + Some("-C") => { + args.next(); + if args.next().is_none() { + return false; + } + } + _ => break, + } + } + let Some(command) = args.next() else { + return false; + }; + let rest: Vec<_> = args.collect(); + if rest + .iter() + .any(|arg| *arg == "--output" || arg.starts_with("--output=")) + { + return false; + } + match command { + "status" | "log" | "show" | "cat-file" | "rev-parse" | "for-each-ref" => true, + "symbolic-ref" => matches!( + rest.as_slice(), + ["--short", "HEAD"] | ["-q", "--short", "HEAD"] + ), + "remote" => matches!(rest.as_slice(), ["get-url", _] | ["get-url", "--push", _]), + _ => false, + } +} + fn preview_output(mut child: std::process::Child) -> Result { use std::io::{self, Read}; @@ -607,14 +654,19 @@ pub(crate) fn file_diff( }; return Ok((patch, None, open_path)); } - let conflict = (group == Group::Conflicts) - .then(|| { - crate::workbench::read_file_bytes(target, &full, MAX_DIFF_BYTES as u64) + let conflict = if group == Group::Conflicts { + match crate::workbench::read_file_bytes(target, &full, MAX_DIFF_BYTES as u64) { + Ok(bytes) if bytes.len() > MAX_DIFF_BYTES => { + return Err(tr("The diff is too large to preview.").into()); + } + Ok(bytes) => String::from_utf8(bytes) .ok() - .and_then(|bytes| String::from_utf8(bytes).ok()) - }) - .flatten() - .filter(|text| text.lines().any(|line| line.starts_with("<<<<<<<"))); + .filter(|text| text.lines().any(|line| line.starts_with("<<<<<<<"))), + Err(_) => None, + } + } else { + None + }; let mut args = vec![ "--literal-pathspecs", "-c", @@ -925,6 +977,29 @@ pub(crate) fn snapshot( mod tests { use super::*; + #[test] + fn wsl_fallback_allows_only_read_git_commands_after_global_options() { + let args = |parts: &[&str]| parts.iter().map(|s| (*s).to_string()).collect::>(); + assert!(read_only_git_args(&args(&[ + "--literal-pathspecs", + "-c", + "i18n.logOutputEncoding=UTF-8", + "log", + "-n", + "80", + ]))); + assert!(read_only_git_args(&args(&["remote", "get-url", "origin"]))); + assert!(!read_only_git_args(&args(&["reset", "--hard"]))); + assert!(!read_only_git_args(&args(&[ + "remote", "set-url", "origin", "url" + ]))); + assert!(!read_only_git_args(&args(&[ + "-c", + "alias.status=!git reset", + "status" + ]))); + } + #[test] fn porcelain_v2() { let out = "# branch.oid abc\0# branch.head main\0# branch.upstream origin/main\0# branch.ab +2 -21\0\ @@ -1193,6 +1268,34 @@ mod tests { assert!(repo.status().check_commit("merge", false).is_ok()); } + #[test] + fn oversized_conflict_content_is_rejected_even_when_the_diff_is_small() { + let repo = TestRepo::new(); + let shared = "same line\n".repeat(MAX_DIFF_BYTES / 10 + 1); + let base = format!("base\n{shared}"); + repo.write("large.txt", &base); + repo.git(&["add", "large.txt"]); + commit(&repo.0, "base", false, false, None).unwrap(); + + repo.git(&["checkout", "-b", "topic"]); + repo.write("large.txt", &base.replace("base\n", "topic\n")); + repo.git(&["add", "large.txt"]); + commit(&repo.0, "topic", false, false, None).unwrap(); + + repo.git(&["checkout", "main"]); + repo.write("large.txt", &base.replace("base\n", "current\n")); + repo.git(&["add", "large.txt"]); + commit(&repo.0, "current", false, false, None).unwrap(); + assert!(run_step(&repo.0, &git_step(&["merge", "topic"]), None).is_err()); + + let file = repo.status().conflicts.remove(0); + assert!(repo.git(&["diff", "--ours", "--", "large.txt"]).len() < 1024); + assert_eq!( + file_diff(&repo.0, &file, Group::Conflicts, None).unwrap_err(), + tr("The diff is too large to preview.") + ); + } + #[test] fn amend_allows_message_only_and_no_edit_staged() { let repo = TestRepo::new(); diff --git a/src/ws_context.rs b/src/ws_context.rs index 19db34d..1e77399 100644 --- a/src/ws_context.rs +++ b/src/ws_context.rs @@ -348,7 +348,12 @@ pub fn overview(i: &Inputs) -> String { let branch = g.branch.as_deref().unwrap_or("(detached)"); let mut line = format!("Git: branch {branch}"); if let Some(up) = &g.upstream { - let _ = write!(line, ", tracking {up} ({} ahead, {} behind)", g.ahead, g.behind); + let _ = write!( + line, + ", tracking {up} ({} ahead, {} behind)", + g.ahead, + g.behind + ); } let changed: Vec = g .conflicts From 558331212370ed72860d84a94cff35bd7306c0e6 Mon Sep 17 00:00:00 2001 From: ThinhNguyen2005 Date: Sat, 28 Nov 2026 02:38:03 +0700 Subject: [PATCH 6/7] format workspace tracking arguments --- src/ws_context.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/ws_context.rs b/src/ws_context.rs index 1e77399..d241582 100644 --- a/src/ws_context.rs +++ b/src/ws_context.rs @@ -351,8 +351,7 @@ pub fn overview(i: &Inputs) -> String { let _ = write!( line, ", tracking {up} ({} ahead, {} behind)", - g.ahead, - g.behind + g.ahead, g.behind ); } let changed: Vec = g From 527c24a6f064aaf108c345326a69e8ee01de6b7c Mon Sep 17 00:00:00 2001 From: ThinhNguyen2005 Date: Sat, 28 Nov 2026 20:05:27 +0700 Subject: [PATCH 7/7] fix conflict staging retries and source control labels --- src/diff_view.rs | 2 +- src/i18n_id.rs | 38 +++++++++++++++++++++++++++++++++++ src/scm_git.rs | 52 ++++++++++++++++++++++++++++++++++++++++++------ 3 files changed, 85 insertions(+), 7 deletions(-) diff --git a/src/diff_view.rs b/src/diff_view.rs index d662351..e62ffcb 100644 --- a/src/diff_view.rs +++ b/src/diff_view.rs @@ -617,7 +617,7 @@ impl Workbench { h.child( btn( "diff-ctx", - if is_full { "Full file" } else { "Changes only" }, + if is_full { "Changes only" } else { "Full file" }, false, ) .on_click(cx.listener(move |_, _, _, cx| { diff --git a/src/i18n_id.rs b/src/i18n_id.rs index fbb3aa6..aa83262 100644 --- a/src/i18n_id.rs +++ b/src/i18n_id.rs @@ -2193,6 +2193,39 @@ pub const ID: &[(&str, &str)] = &[ ("Inline", "Sebaris"), ("Full file", "Seluruh file"), ("Changes only", "Perubahan saja"), + ("Checking for a Git repository…", "Memeriksa repository Git…"), + ("Commit the staged changes (Enter)", "Commit perubahan yang sudah di-stage (Enter)"), + ("Discard All", "Buang Semua"), + ("Discard {n} files in {group}?", "Buang {n} file di {group}?"), + ("Merge Conflicts", "Konflik Merge"), + ( + "Remove these files from the index and working tree.", + "Hapus file ini dari index dan working tree.", + ), + ( + "Restore the index and working tree to the last commit.", + "Pulihkan index dan working tree ke commit terakhir.", + ), + ( + "Restore the original merge conflict in the working tree.", + "Pulihkan konflik merge semula di working tree.", + ), + ( + "Restore the working tree from the index.", + "Pulihkan working tree dari index.", + ), + ("Running Git…", "Menjalankan Git…"), + ( + "Save or close the modified editor before discarding.", + "Simpan atau tutup editor yang sudah diubah sebelum membuang.", + ), + ("Show {n} more files", "Tampilkan {n} file lainnya"), + ( + "Switch to a branch before pushing or syncing.", + "Pindah ke branch sebelum push atau sync.", + ), + ("Untracked Files", "File Untracked"), + ("Untracked files will be deleted.", "File untracked akan dihapus."), ("Previous change", "Perubahan sebelumnya"), ("Next change", "Perubahan berikutnya"), ( @@ -2224,6 +2257,7 @@ pub const ID: &[(&str, &str)] = &[ ("No commits yet.", "Belum ada commit."), ("View full diff", "Lihat diff penuh"), ("No changed files.", "Tidak ada file berubah."), + ("No changes.", "Tidak ada perubahan."), ("Publish Branch", "Publikasikan Branch"), ("Upstream unavailable", "Upstream tidak tersedia"), ("Hunk {n}/{total}", "Hunk {n}/{total}"), @@ -2262,6 +2296,10 @@ pub const ID: &[(&str, &str)] = &[ "The conflict changed. Reopen it before saving the resolution.", "Konflik berubah. Buka ulang sebelum menyimpan resolusi.", ), + ( + "Conflict resolution was saved, but staging failed: {error}", + "Resolusi konflik sudah disimpan, tetapi gagal di-stage: {error}", + ), ( "The selected files changed. Review Source Control and try again.", "File terpilih berubah. Periksa Source Control lalu coba lagi.", diff --git a/src/scm_git.rs b/src/scm_git.rs index ae534b0..a6e23e9 100644 --- a/src/scm_git.rs +++ b/src/scm_git.rs @@ -315,21 +315,33 @@ pub(crate) fn run_step( } => { let full = dir.join(path); let status = read_status(dir, target)?; - let current = - crate::workbench::read_file_bytes(target, &full, expected.len() as u64).ok(); + let current = crate::workbench::read_file_bytes( + target, + &full, + expected.len().max(resolved.len()) as u64, + ) + .ok(); if !status.conflicts.iter().any(|file| file.path == *path) - || current.as_deref() != Some(expected.as_bytes()) + || !matches!( + current.as_deref(), + Some(bytes) if bytes == expected.as_bytes() || bytes == resolved.as_bytes() + ) { return Err( tr("The conflict changed. Reopen it before saving the resolution.").into(), ); } - crate::workbench::write_doc_to_disk(target, &full, resolved, false, None)?; + if current.as_deref() != Some(resolved.as_bytes()) { + crate::workbench::write_doc_to_disk(target, &full, resolved, false, None)?; + } return run_step( dir, &git_step(&["--literal-pathspecs", "add", "--", path]), target, - ); + ) + .map_err(|error| { + crate::trf!("Conflict resolution was saved, but staging failed: {error}"; error => error) + }); } Step::Hunk { path, @@ -1257,11 +1269,39 @@ mod tests { expected, resolved: "resolved\n".into(), }; - assert!(run_step(&repo.0, &save("stale".into()), None).is_err()); + let stale = run_step(&repo.0, &save("stale".into()), None).unwrap_err(); + assert_eq!( + stale, + tr("The conflict changed. Reopen it before saving the resolution.") + ); assert_eq!( std::fs::read_to_string(repo.0.join("same.txt")).unwrap(), restored ); + let lock = repo.0.join(".git/index.lock"); + std::fs::write(&lock, b"").unwrap(); + let failed = run_step(&repo.0, &save(restored.clone()), None).unwrap_err(); + assert!(failed.contains("Conflict resolution was saved, but staging failed:")); + assert!(failed.contains("index.lock")); + assert_eq!( + std::fs::read_to_string(repo.0.join("same.txt")).unwrap(), + "resolved\n" + ); + assert_eq!(repo.status().conflicts.len(), 1); + + repo.write("same.txt", "changed outside the editor\n"); + let stale = run_step(&repo.0, &save(restored.clone()), None).unwrap_err(); + assert_eq!( + stale, + tr("The conflict changed. Reopen it before saving the resolution.") + ); + assert_eq!( + std::fs::read_to_string(repo.0.join("same.txt")).unwrap(), + "changed outside the editor\n" + ); + + std::fs::remove_file(lock).unwrap(); + repo.write("same.txt", "resolved\n"); run_step(&repo.0, &save(restored), None).unwrap(); assert!(repo.status().conflicts.is_empty()); assert_eq!(repo.git(&["show", ":same.txt"]), "resolved\n");