From 710593c8d338c43bed6163efaf67d95046050b5a Mon Sep 17 00:00:00 2001 From: Christian Lauinger Date: Fri, 6 Nov 2026 13:13:02 +0100 Subject: [PATCH 01/50] feat(hooks): run post-checkout, post-merge and post-rewrite hooks Every operation that runs a post-* hook in git now runs it through the existing hook runner, with git's arguments and stdin: post-checkout after checkouts, clones, new worktrees, discards and stash file applies, post-merge after merges and pulls that merged or fast-forwarded, and post-rewrite after amend, reword, rebase, interactive rebase and pull with rebase. A failing post-hook is reported as a warning and never undoes the operation. Pull all runs post-merge per repository that fast-forwarded, inside the same locked section as the fast-forward, and Skip hooks, Pull without hooks and Pull all without hooks skip them. Refs #82, #69 --- apps/desktop/src-tauri/src/commands.rs | 186 ++++-- apps/desktop/src-tauri/src/core/branch.rs | 118 +++- apps/desktop/src-tauri/src/core/commit.rs | 64 +- .../src-tauri/src/core/group_update.rs | 17 +- apps/desktop/src-tauri/src/core/hooks.rs | 200 ++++++- apps/desktop/src-tauri/src/core/mod.rs | 1 + apps/desktop/src-tauri/src/core/post_hooks.rs | 268 +++++++++ apps/desktop/src-tauri/src/core/remote.rs | 62 +- apps/desktop/src-tauri/src/core/types.rs | 21 +- apps/desktop/src-tauri/src/lib.rs | 1 + apps/desktop/src-tauri/tests/clone_hooks.rs | 115 ++++ apps/desktop/src-tauri/tests/git_engine.rs | 551 +++++++++++++++++- apps/desktop/src/app/App.tsx | 2 + .../src/components/HookFailedDialog.tsx | 78 ++- apps/desktop/src/components/Toolbar.tsx | 9 + apps/desktop/src/components/hookWarnings.tsx | 50 ++ apps/desktop/src/core/ipc.ts | 94 ++- .../src/features/commit/WorkingCopyPanel.tsx | 13 +- .../features/repository/GroupUpdateDialog.tsx | 27 +- .../src/features/repository/WelcomePage.tsx | 28 +- packages/core/src/git/types.ts | 12 + tests/e2e/smoke.spec.ts | 84 +++ 22 files changed, 1838 insertions(+), 163 deletions(-) create mode 100644 apps/desktop/src-tauri/src/core/post_hooks.rs create mode 100644 apps/desktop/src-tauri/tests/clone_hooks.rs create mode 100644 apps/desktop/src/components/hookWarnings.tsx diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index bea5d57c..dd542530 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -1,5 +1,6 @@ use tauri::{AppHandle, Emitter, State}; +use crate::core::post_hooks::{self, Hooked}; use crate::core::types::*; use crate::core::{ branch, commit, conflict, diff, files, history, hooks, misc, pull_preview, remote, repo, scan, @@ -8,6 +9,19 @@ use crate::core::{ use crate::error::AppResult; use crate::terminal::TerminalState; +fn report(app: &AppHandle, repo_path: &str, hooked: Hooked) -> T { + for warning in hooked.warnings { + let _ = app.emit( + "hook-warning", + HookWarningEvent { + repo_path: repo_path.to_string(), + warning, + }, + ); + } + hooked.value +} + async fn blocking( f: impl FnOnce() -> AppResult + Send + 'static, ) -> AppResult { @@ -62,12 +76,20 @@ pub async fn repo_clone( branch: Option, ) -> AppResult { let emitter = app.clone(); - let root = blocking(move || { - remote::clone(&url, &into, branch.as_deref(), move |pct| { - let _ = emitter.emit("clone-progress", pct); - }) + let cloned = blocking(move || { + post_hooks::clone( + &url, + &into, + branch.as_deref(), + move |pct| { + let _ = emitter.emit("clone-progress", pct); + }, + false, + ) }) .await?; + let root = cloned.value.clone(); + report(&app, &root, cloned); crate::state::recent_add(&app, &root)?; Ok(root) } @@ -138,23 +160,31 @@ pub async fn unstage_all(path: String) -> AppResult<()> { } #[tauri::command] -pub async fn discard_file(path: String, file: String) -> AppResult { - blocking(move || stage::discard_file(&path, &file)).await +pub async fn discard_file(app: AppHandle, path: String, file: String) -> AppResult { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::discard_file(&path, &file, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] -pub async fn discard_all(path: String) -> AppResult> { - blocking(move || stage::discard_all(&path)).await +pub async fn discard_all(app: AppHandle, path: String) -> AppResult> { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::discard_all(&path, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] -pub async fn discard_staged_file(path: String, file: String) -> AppResult { - blocking(move || stage::discard_staged_file(&path, &file)).await +pub async fn discard_staged_file(app: AppHandle, path: String, file: String) -> AppResult { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::discard_staged_file(&path, &file, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] -pub async fn discard_staged_all(path: String) -> AppResult> { - blocking(move || stage::discard_staged_all(&path)).await +pub async fn discard_staged_all(app: AppHandle, path: String) -> AppResult> { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::discard_staged_all(&path, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -305,11 +335,16 @@ pub async fn commit_create( #[tauri::command] pub async fn commit_amend( + app: AppHandle, path: String, message: Option, noVerify: Option, ) -> AppResult { - blocking(move || commit::amend(&path, message.as_deref(), noVerify.unwrap_or(false))).await + let repo_path = path.clone(); + let hooked = + blocking(move || post_hooks::amend(&path, message.as_deref(), noVerify.unwrap_or(false))) + .await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -318,8 +353,15 @@ pub async fn repo_hooks(path: String) -> AppResult> { } #[tauri::command] -pub async fn commit_reword(path: String, oid: String, message: String) -> AppResult { - blocking(move || commit::reword(&path, &oid, &message)).await +pub async fn commit_reword( + app: AppHandle, + path: String, + oid: String, + message: String, +) -> AppResult { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::reword(&path, &oid, &message, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -390,17 +432,19 @@ pub async fn branch_list(path: String) -> AppResult> { #[tauri::command] pub async fn branch_create( + app: AppHandle, path: String, name: String, fromOid: Option, checkout: bool, ) -> AppResult<()> { - blocking(move || { - submodule::synced(&path, || { - branch::create(&path, &name, fromOid.as_deref(), checkout) - }) + let repo_path = path.clone(); + let hooked = blocking(move || { + post_hooks::branch_create(&path, &name, fromOid.as_deref(), checkout, false) }) - .await + .await?; + report(&app, &repo_path, hooked); + Ok(()) } #[tauri::command] @@ -414,21 +458,32 @@ pub async fn branch_rename(path: String, oldName: String, newName: String) -> Ap } #[tauri::command] -pub async fn branch_checkout(path: String, name: String) -> AppResult<()> { - blocking(move || submodule::synced(&path, || branch::checkout_branch(&path, &name))).await +pub async fn branch_checkout(app: AppHandle, path: String, name: String) -> AppResult<()> { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::checkout_branch(&path, &name, false)).await?; + report(&app, &repo_path, hooked); + Ok(()) } #[tauri::command] -pub async fn checkout_detached(path: String, rev: String) -> AppResult<()> { - blocking(move || submodule::synced(&path, || branch::checkout_detached(&path, &rev))).await +pub async fn checkout_detached(app: AppHandle, path: String, rev: String) -> AppResult<()> { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::checkout_detached(&path, &rev, false)).await?; + report(&app, &repo_path, hooked); + Ok(()) } #[tauri::command] -pub async fn branch_merge(path: String, name: String, noFf: Option) -> AppResult { - blocking(move || { - submodule::synced(&path, || branch::merge(&path, &name, noFf.unwrap_or(false))) - }) - .await +pub async fn branch_merge( + app: AppHandle, + path: String, + name: String, + noFf: Option, +) -> AppResult { + let repo_path = path.clone(); + let hooked = + blocking(move || post_hooks::merge(&path, &name, noFf.unwrap_or(false), false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -437,13 +492,17 @@ pub async fn merge_abort(path: String) -> AppResult<()> { } #[tauri::command] -pub async fn branch_rebase(path: String, upstream: String) -> AppResult { - blocking(move || submodule::synced(&path, || branch::rebase(&path, &upstream))).await +pub async fn branch_rebase(app: AppHandle, path: String, upstream: String) -> AppResult { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::rebase(&path, &upstream, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] -pub async fn rebase_continue(path: String) -> AppResult { - blocking(move || submodule::synced(&path, || branch::rebase_continue(&path))).await +pub async fn rebase_continue(app: AppHandle, path: String) -> AppResult { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::rebase_continue(&path, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -458,14 +517,15 @@ pub async fn rebase_commits(path: String, baseOid: String) -> AppResult, ) -> AppResult { - blocking(move || { - submodule::synced(&path, || branch::rebase_interactive(&path, &baseOid, &todo)) - }) - .await + let repo_path = path.clone(); + let hooked = + blocking(move || post_hooks::rebase_interactive(&path, &baseOid, &todo, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -546,8 +606,8 @@ pub async fn repository_group_update( } #[tauri::command] -pub fn repository_group_start(runId: String) -> AppResult<()> { - crate::core::group_update::start(&runId) +pub fn repository_group_start(runId: String, noVerify: Option) -> AppResult<()> { + crate::core::group_update::start(&runId, noVerify.unwrap_or(false)) } #[tauri::command] @@ -562,12 +622,18 @@ pub async fn repository_group_finish(runId: String) -> AppResult<()> { #[tauri::command] pub async fn remote_pull( + app: AppHandle, path: String, remote: String, mode: Option, + noVerify: Option, ) -> AppResult { - blocking(move || submodule::synced(&path, || remote::pull(&path, &remote, mode.as_deref()))) - .await + let repo_path = path.clone(); + let hooked = blocking(move || { + post_hooks::pull(&path, &remote, mode.as_deref(), noVerify.unwrap_or(false)) + }) + .await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -600,8 +666,14 @@ pub async fn pull_preview(path: String, remote: String) -> AppResult AppResult { - blocking(move || remote::pull_branch(&path, &branch)).await +pub async fn remote_pull_branch( + app: AppHandle, + path: String, + branch: String, +) -> AppResult { + let repo_path = path.clone(); + let hooked = blocking(move || post_hooks::pull_branch(&path, &branch, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -659,11 +731,15 @@ pub async fn stash_files(path: String, index: usize) -> AppResult, ) -> AppResult> { - blocking(move || misc::stash_restore_files(&path, index, &paths)).await + let repo_path = path.clone(); + let hooked = + blocking(move || post_hooks::stash_restore_files(&path, index, &paths, false)).await?; + Ok(report(&app, &repo_path, hooked)) } #[tauri::command] @@ -702,8 +778,14 @@ pub async fn worktree_list(path: String) -> AppResult> { } #[tauri::command] -pub async fn worktree_add(path: String, request: WorktreeAddRequest) -> AppResult { - blocking(move || worktree::add(&path, &request)).await +pub async fn worktree_add( + app: AppHandle, + path: String, + request: WorktreeAddRequest, +) -> AppResult { + let added = blocking(move || post_hooks::worktree_add(&path, &request, false)).await?; + let created = added.value.clone(); + Ok(report(&app, &created, added)) } #[tauri::command] @@ -968,18 +1050,20 @@ pub async fn forge_request( #[tauri::command] pub async fn pr_checkout( + app: AppHandle, path: String, remote: String, sourceRef: String, branch: String, track: bool, ) -> AppResult<()> { - blocking(move || { - submodule::synced(&path, || { - remote::checkout_remote_ref(&path, &remote, &sourceRef, &branch, track) - }) + let repo_path = path.clone(); + let hooked = blocking(move || { + post_hooks::checkout_remote_ref(&path, &remote, &sourceRef, &branch, track, false) }) - .await + .await?; + report(&app, &repo_path, hooked); + Ok(()) } #[tauri::command] diff --git a/apps/desktop/src-tauri/src/core/branch.rs b/apps/desktop/src-tauri/src/core/branch.rs index 0f936e3d..43e8bb40 100644 --- a/apps/desktop/src-tauri/src/core/branch.rs +++ b/apps/desktop/src-tauri/src/core/branch.rs @@ -2,6 +2,7 @@ use git2::{build::CheckoutBuilder, BranchType, Repository, ResetType}; use crate::error::{AppError, AppResult}; +use super::hooks::PostHook; use super::types::{BranchInfo, CommitInfo, OpOutcome, RebaseTodoEntry}; pub fn list(path: &str) -> AppResult> { @@ -264,13 +265,31 @@ pub fn abort_merge(path: &str) -> AppResult<()> { } pub fn rebase(path: &str, upstream: &str) -> AppResult { + rebase_reporting(path, upstream).map(|(outcome, _)| outcome) +} + +pub(crate) fn rebase_reporting( + path: &str, + upstream: &str, +) -> AppResult<(OpOutcome, Vec)> { let repo = super::repo::open(path)?; let reference = resolve_branch_ref(&repo, upstream)?; let upstream_annotated = repo.reference_to_annotated_commit(&reference)?; let sig = repo.signature()?; + let previous = repo.head()?.peel_to_commit()?.id(); + + let onto = upstream_annotated.id(); let mut opts = git2::RebaseOptions::new(); let mut rebase = repo.rebase(None, Some(&upstream_annotated), None, Some(&mut opts))?; + let mut hooks: Vec = (previous != onto) + .then_some(PostHook::Checkout { + previous, + new: onto, + branch: true, + }) + .into_iter() + .collect(); while let Some(op) = rebase.next() { if let Err(error) = op { @@ -278,10 +297,13 @@ pub fn rebase(path: &str, upstream: &str) -> AppResult { } let index = repo.index()?; if index.has_conflicts() { - return Ok(OpOutcome { - status: "conflicts".into(), - message: "Rebase paused on conflicts. Resolve them, then continue.".into(), - }); + return Ok(( + OpOutcome { + status: "conflicts".into(), + message: "Rebase paused on conflicts. Resolve them, then continue.".into(), + }, + hooks, + )); } match rebase.commit(None, &sig, None) { Ok(_) => {} @@ -289,14 +311,34 @@ pub fn rebase(path: &str, upstream: &str) -> AppResult { Err(e) => return Err(e.into()), } } + let rewritten = rewritten_pairs(&repo); rebase.finish(Some(&sig))?; - Ok(OpOutcome { - status: "ok".into(), - message: format!("Rebased onto {upstream}"), - }) + hooks.extend(PostHook::rebased(rewritten)); + Ok(( + OpOutcome { + status: "ok".into(), + message: format!("Rebased onto {upstream}"), + }, + hooks, + )) +} + +fn rewritten_pairs(repo: &Repository) -> Vec<(git2::Oid, git2::Oid)> { + let file = repo.path().join("rebase-merge").join("rewritten"); + let Ok(text) = std::fs::read_to_string(file) else { + return Vec::new(); + }; + text.lines() + .filter_map(|line| { + let mut ids = line.split_whitespace(); + let old = git2::Oid::from_str(ids.next()?).ok()?; + let new = git2::Oid::from_str(ids.next()?).ok()?; + Some((old, new)) + }) + .collect() } -pub fn rebase_continue(path: &str) -> AppResult { +pub(crate) fn rebase_continue(path: &str) -> AppResult<(OpOutcome, Vec)> { let repo = super::repo::open(path)?; let sig = repo.signature()?; let mut rebase = repo.open_rebase(None)?; @@ -310,10 +352,13 @@ pub fn rebase_continue(path: &str) -> AppResult { { let index = repo.index()?; if index.has_conflicts() { - return Ok(OpOutcome { - status: "conflicts".into(), - message: "Conflicts are still unresolved.".into(), - }); + return Ok(( + OpOutcome { + status: "conflicts".into(), + message: "Conflicts are still unresolved.".into(), + }, + Vec::new(), + )); } } match rebase.commit(None, &sig, None) { @@ -328,10 +373,13 @@ pub fn rebase_continue(path: &str) -> AppResult { } let index = repo.index()?; if index.has_conflicts() { - return Ok(OpOutcome { - status: "conflicts".into(), - message: "Rebase paused on conflicts. Resolve them, then continue.".into(), - }); + return Ok(( + OpOutcome { + status: "conflicts".into(), + message: "Rebase paused on conflicts. Resolve them, then continue.".into(), + }, + Vec::new(), + )); } match rebase.commit(None, &sig, None) { Ok(_) => {} @@ -339,11 +387,15 @@ pub fn rebase_continue(path: &str) -> AppResult { Err(e) => return Err(e.into()), } } + let rewritten = rewritten_pairs(&repo); rebase.finish(Some(&sig))?; - Ok(OpOutcome { - status: "ok".into(), - message: "Rebase complete".into(), - }) + Ok(( + OpOutcome { + status: "ok".into(), + message: "Rebase complete".into(), + }, + PostHook::rebased(rewritten).into_iter().collect(), + )) } const STOPPED_STEP_MARK: &str = "angkorgit-stopped-step"; @@ -509,9 +561,18 @@ fn ensure_tracked_clean(repo: &Repository) -> AppResult<()> { } pub fn rebase_interactive(path: &str, base: &str, todo: &[RebaseTodoEntry]) -> AppResult { + rebase_interactive_reporting(path, base, todo).map(|(head, _)| head) +} + +pub(crate) fn rebase_interactive_reporting( + path: &str, + base: &str, + todo: &[RebaseTodoEntry], +) -> AppResult<(String, Vec)> { let repo = super::repo::open(path)?; let sig = super::commit::default_signature(&repo)?; ensure_tracked_clean(&repo)?; + let previous = repo.head()?.peel_to_commit()?.id(); let range = rebase_commits(path, base)?; let allowed: std::collections::HashSet<&str> = range.iter().map(|c| c.oid.as_str()).collect(); @@ -537,8 +598,11 @@ pub fn rebase_interactive(path: &str, base: &str, todo: &[RebaseTodoEntry]) -> A } let base_commit = repo.find_commit(git2::Oid::from_str(base)?)?; + let onto = base_commit.id(); let mut parent = base_commit; let mut built_any = false; + let mut rewritten: Vec<(git2::Oid, git2::Oid)> = Vec::new(); + let mut chain: Vec = Vec::new(); for entry in todo { if entry.action == "drop" { continue; @@ -575,7 +639,9 @@ pub fn rebase_interactive(path: &str, base: &str, todo: &[RebaseTodoEntry]) -> A let parent_refs: Vec<&git2::Commit> = grandparents.iter().collect(); let oid = repo.commit(None, &parent.author(), &sig, &message, &tree, &parent_refs)?; parent = repo.find_commit(oid)?; + chain.push(commit.id()); } else { + rewritten.extend(chain.drain(..).map(|old| (old, parent.id()))); let message = match entry.message.as_deref().map(str::trim) { Some(m) if entry.action == "reword" && !m.is_empty() => m.to_string(), _ => commit.message().unwrap_or("").to_string(), @@ -583,11 +649,19 @@ pub fn rebase_interactive(path: &str, base: &str, todo: &[RebaseTodoEntry]) -> A let oid = repo.commit(None, &commit.author(), &sig, &message, &tree, &[&parent])?; parent = repo.find_commit(oid)?; built_any = true; + chain.push(commit.id()); } } + rewritten.extend(chain.drain(..).map(|old| (old, parent.id()))); repo.reset(parent.as_object(), ResetType::Hard, None)?; - Ok(parent.id().to_string()) + let mut hooks = vec![PostHook::Checkout { + previous, + new: onto, + branch: true, + }]; + hooks.extend(PostHook::rebased(rewritten)); + Ok((parent.id().to_string(), hooks)) } fn is_trailer_line(line: &str) -> bool { diff --git a/apps/desktop/src-tauri/src/core/commit.rs b/apps/desktop/src-tauri/src/core/commit.rs index e9da39f0..42cb1bee 100644 --- a/apps/desktop/src-tauri/src/core/commit.rs +++ b/apps/desktop/src-tauri/src/core/commit.rs @@ -2,7 +2,7 @@ use git2::Repository; use crate::error::{AppError, AppResult}; -use super::hooks::CommitHooks; +use super::hooks::{CommitHooks, PostHook, Rewrite}; use super::types::{CommitOutcome, OpOutcome, RebaseTodoEntry}; pub(crate) fn default_signature(repo: &Repository) -> AppResult> { @@ -174,6 +174,21 @@ pub fn revert(path: &str, oid: &str) -> AppResult { } pub fn amend(path: &str, message: Option<&str>, no_verify: bool) -> AppResult { + amend_reporting(path, message, no_verify).map(|(outcome, _)| outcome) +} + +fn amended(old: git2::Oid, new: git2::Oid) -> PostHook { + PostHook::Rewrite { + command: Rewrite::Amend, + pairs: vec![(old, new)], + } +} + +pub(crate) fn amend_reporting( + path: &str, + message: Option<&str>, + no_verify: bool, +) -> AppResult<(CommitOutcome, PostHook)> { let repo = super::repo::open(path)?; let head = repo .head() @@ -204,10 +219,13 @@ pub fn amend(path: &str, message: Option<&str>, no_verify: bool) -> AppResult, no_verify: bool) -> AppResult AppResult { + reword_reporting(path, oid, message).map(|(oid, _)| oid) +} + +pub(crate) fn reword_reporting( + path: &str, + oid: &str, + message: &str, +) -> AppResult<(String, Vec)> { let message = message.trim_end(); if message.trim().is_empty() { return Err(AppError::other("the commit message cannot be empty")); @@ -242,7 +271,8 @@ pub fn reword(path: &str, oid: &str, message: &str) -> AppResult { .map_err(|_| AppError::other("nothing to reword: repository has no commits"))? .peel_to_commit()?; if target.id() == head.id() { - return reword_head(&repo, &head, message); + let new = reword_head(&repo, &head, message)?; + return Ok((new.to_string(), vec![amended(head.id(), new)])); } let parent = target.parent(0).map_err(|_| { AppError::other("the root commit can only be reworded while it is the latest commit") @@ -267,23 +297,22 @@ pub fn reword(path: &str, oid: &str, message: &str) -> AppResult { } }) .collect(); - let new_head = super::branch::rebase_interactive(path, &parent_oid, &todo)?; + let (new_head, hooks) = super::branch::rebase_interactive_reporting(path, &parent_oid, &todo)?; let mut commit = repo.find_commit(git2::Oid::from_str(&new_head)?)?; for _ in 0..index { commit = commit.parent(0)?; } - Ok(commit.id().to_string()) + Ok((commit.id().to_string(), hooks)) } -fn reword_head(repo: &Repository, head: &git2::Commit, message: &str) -> AppResult { +fn reword_head(repo: &Repository, head: &git2::Commit, message: &str) -> AppResult { if super::sign::signing_config(repo)?.is_none() { - let oid = head.amend(Some("HEAD"), None, None, None, Some(message), None)?; - return Ok(oid.to_string()); + return Ok(head.amend(Some("HEAD"), None, None, None, Some(message), None)?); } let tree = head.tree()?; let parents: Vec = head.parents().collect(); let parent_refs: Vec<&git2::Commit> = parents.iter().collect(); - let oid = super::sign::create_commit( + super::sign::create_commit( repo, Some("HEAD"), &head.author(), @@ -291,6 +320,5 @@ fn reword_head(repo: &Repository, head: &git2::Commit, message: &str) -> AppResu message, &tree, &parent_refs, - )?; - Ok(oid.to_string()) + ) } diff --git a/apps/desktop/src-tauri/src/core/group_update.rs b/apps/desktop/src-tauri/src/core/group_update.rs index 421afa46..b62a4226 100644 --- a/apps/desktop/src-tauri/src/core/group_update.rs +++ b/apps/desktop/src-tauri/src/core/group_update.rs @@ -9,6 +9,7 @@ use crate::error::{AppError, AppResult}; pub struct GroupUpdateControl { cancelled: Mutex, completed: Mutex>, + no_verify: bool, } #[derive(Clone)] @@ -26,6 +27,17 @@ pub(super) struct FetchProgress { } impl GroupUpdateControl { + pub fn skipping_hooks(no_verify: bool) -> Self { + GroupUpdateControl { + no_verify, + ..Default::default() + } + } + + pub fn skips_hooks(&self) -> bool { + self.no_verify + } + pub fn cancel(&self) -> AppResult<()> { *self .cancelled @@ -104,6 +116,7 @@ impl GroupUpdateControl { status: "failed".into(), message: error.to_string(), changes: Vec::new(), + ..Default::default() }, }; self.completed @@ -179,7 +192,7 @@ fn prune_expired(runs: &mut Runs, now: Instant) { }); } -pub fn start(id: &str) -> AppResult<()> { +pub fn start(id: &str, no_verify: bool) -> AppResult<()> { let mut runs = runs() .lock() .map_err(|_| AppError::other("Group update registry poisoned"))?; @@ -191,7 +204,7 @@ pub fn start(id: &str) -> AppResult<()> { runs.insert( id.into(), Run { - control: Arc::new(GroupUpdateControl::default()), + control: Arc::new(GroupUpdateControl::skipping_hooks(no_verify)), last_used: now, }, ); diff --git a/apps/desktop/src-tauri/src/core/hooks.rs b/apps/desktop/src-tauri/src/core/hooks.rs index 02796e03..51c45260 100644 --- a/apps/desktop/src-tauri/src/core/hooks.rs +++ b/apps/desktop/src-tauri/src/core/hooks.rs @@ -5,13 +5,24 @@ use std::time::Duration; use git2::{Oid, Repository}; +use super::types::HookWarning; use crate::ai_cli::{capture, capture_tree_child, search_path, spawn_tree}; use crate::error::{AppError, AppResult}; pub const PRE_COMMIT: &str = "pre-commit"; pub const COMMIT_MSG: &str = "commit-msg"; pub const PRE_PUSH: &str = "pre-push"; -const REPO_HOOKS: &[&str] = &[PRE_COMMIT, COMMIT_MSG, PRE_PUSH]; +pub const POST_CHECKOUT: &str = "post-checkout"; +pub const POST_MERGE: &str = "post-merge"; +pub const POST_REWRITE: &str = "post-rewrite"; +const REPO_HOOKS: &[&str] = &[ + PRE_COMMIT, + COMMIT_MSG, + PRE_PUSH, + POST_CHECKOUT, + POST_MERGE, + POST_REWRITE, +]; const MIN_GIT_VERSION: (u32, u32) = (2, 36); const TO_STDIN_VERSION: (u32, u32) = (2, 40); @@ -207,9 +218,14 @@ fn pick_runner( return Ok(Runner::Direct(file)); } let (major, minor) = git.version; + let input = if name == PRE_PUSH { + "the refs being pushed" + } else { + "the rewritten commits" + }; Err(format!( - "The {name} hook did not run because git {major}.{minor} cannot hand it the refs being \ - pushed. Git 2.40 or newer is needed to run it." + "The {name} hook did not run because git {major}.{minor} cannot hand it {input}. Git \ + 2.40 or newer is needed to run it." )) } @@ -522,6 +538,134 @@ fn rejected_as_non_fast_forward(repo: &Repository, r: &PushedRef) -> bool { } } +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Rewrite { + Amend, + Rebase, +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum PostHook { + Checkout { + previous: Oid, + new: Oid, + branch: bool, + }, + Merge, + Rewrite { + command: Rewrite, + pairs: Vec<(Oid, Oid)>, + }, +} + +impl PostHook { + pub(crate) fn merged(outcome: &super::types::OpOutcome) -> Vec { + match outcome.status.as_str() { + "ok" | "fast_forward" => vec![PostHook::Merge], + _ => Vec::new(), + } + } + + pub(crate) fn rebased(pairs: Vec<(Oid, Oid)>) -> Option { + let pairs: Vec<(Oid, Oid)> = pairs.into_iter().filter(|(old, new)| old != new).collect(); + (!pairs.is_empty()).then_some(PostHook::Rewrite { + command: Rewrite::Rebase, + pairs, + }) + } + + fn name(&self) -> &'static str { + match self { + PostHook::Checkout { .. } => POST_CHECKOUT, + PostHook::Merge => POST_MERGE, + PostHook::Rewrite { .. } => POST_REWRITE, + } + } + + fn args(&self) -> Vec { + match self { + PostHook::Checkout { + previous, + new, + branch, + } => vec![ + previous.to_string(), + new.to_string(), + if *branch { "1" } else { "0" }.to_string(), + ], + PostHook::Merge => vec!["0".to_string()], + PostHook::Rewrite { command, .. } => vec![match command { + Rewrite::Amend => "amend".to_string(), + Rewrite::Rebase => "rebase".to_string(), + }], + } + } + + fn input(&self) -> Option { + match self { + PostHook::Rewrite { pairs, .. } => Some( + pairs + .iter() + .map(|(old, new)| format!("{old} {new}\n")) + .collect(), + ), + _ => None, + } + } +} + +pub(crate) fn run_post(repo: &Repository, hooks: &[PostHook], no_verify: bool) -> Vec { + let mut warnings: Vec = Vec::new(); + let Some(workdir) = repo.workdir() else { + return warnings; + }; + if no_verify { + return warnings; + } + for hook in hooks { + let name = hook.name(); + let found = match present(repo, name) { + Ok(found) => found, + Err(error) => { + warnings.push(post_warning(name, None, error.to_string(), String::new())); + continue; + } + }; + if !found { + continue; + } + let input = hook.input(); + let runner = match runner(repo, workdir, name, input.is_some()) { + Ok(runner) => runner, + Err(reason) => { + if !warnings.iter().any(|w| w.message == reason) { + warnings.push(post_warning(name, None, reason, String::new())); + } + continue; + } + }; + let args = hook.args(); + let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect(); + if let Err(error) = run(repo, &runner, name, &args, &[], input.as_deref()) { + let (status, output) = match &error { + AppError::Hook { status, output, .. } => (Some(*status), output.clone()), + _ => (None, String::new()), + }; + warnings.push(post_warning(name, status, error.to_string(), output)); + } + } + warnings +} + +fn post_warning(hook: &str, status: Option, message: String, output: String) -> HookWarning { + HookWarning { + hook: hook.to_string(), + status, + message, + output, + } +} + fn commit_env(repo: &Repository, author: &git2::Signature<'_>) -> Vec<(&'static str, OsString)> { vec![ ("GIT_INDEX_FILE", repo.path().join("index").into_os_string()), @@ -591,6 +735,56 @@ mod tests { assert_eq!(git_date(git2::Time::new(0, 0)), "@0 +0000"); } + #[test] + fn post_hooks_get_the_args_and_stdin_git_passes() { + let a = Oid::from_str("1111111111111111111111111111111111111111").unwrap(); + let b = Oid::from_str("2222222222222222222222222222222222222222").unwrap(); + let switched = PostHook::Checkout { + previous: a, + new: b, + branch: true, + }; + assert_eq!( + switched.args(), + vec![a.to_string(), b.to_string(), "1".into()] + ); + assert_eq!(switched.input(), None); + let restored = PostHook::Checkout { + previous: a, + new: a, + branch: false, + }; + assert_eq!(restored.args()[2], "0"); + assert_eq!(PostHook::Merge.args(), vec!["0".to_string()]); + let amended = PostHook::Rewrite { + command: Rewrite::Amend, + pairs: vec![(a, a)], + }; + assert_eq!(amended.args(), vec!["amend".to_string()]); + assert_eq!(amended.input(), Some(format!("{a} {a}\n"))); + let Some(rebased) = PostHook::rebased(vec![(a, b), (b, b), (b, a)]) else { + panic!("a rebase that rewrote commits must run post-rewrite"); + }; + assert_eq!(rebased.args(), vec!["rebase".to_string()]); + assert_eq!(rebased.input(), Some(format!("{a} {b}\n{b} {a}\n"))); + assert_eq!(PostHook::rebased(vec![(a, a)]), None); + } + + #[test] + fn post_merge_follows_only_a_merge_that_moved_head() { + let outcome = |status: &str| super::super::types::OpOutcome { + status: status.into(), + message: String::new(), + }; + assert_eq!(PostHook::merged(&outcome("ok")), vec![PostHook::Merge]); + assert_eq!( + PostHook::merged(&outcome("fast_forward")), + vec![PostHook::Merge] + ); + assert!(PostHook::merged(&outcome("up_to_date")).is_empty()); + assert!(PostHook::merged(&outcome("conflicts")).is_empty()); + } + #[test] fn edited_messages_get_git_whitespace_cleanup() { assert_eq!( diff --git a/apps/desktop/src-tauri/src/core/mod.rs b/apps/desktop/src-tauri/src/core/mod.rs index 9a6b4522..11143996 100644 --- a/apps/desktop/src-tauri/src/core/mod.rs +++ b/apps/desktop/src-tauri/src/core/mod.rs @@ -10,6 +10,7 @@ pub mod group_update; pub mod history; pub mod hooks; pub mod misc; +pub mod post_hooks; pub mod pull_preview; pub mod remote; pub mod repo; diff --git a/apps/desktop/src-tauri/src/core/post_hooks.rs b/apps/desktop/src-tauri/src/core/post_hooks.rs new file mode 100644 index 00000000..a5e8d871 --- /dev/null +++ b/apps/desktop/src-tauri/src/core/post_hooks.rs @@ -0,0 +1,268 @@ +use std::path::Path; + +use git2::Oid; + +use super::hooks::{run_post, PostHook}; +use super::types::{CommitOutcome, HookWarning, OpOutcome, RebaseTodoEntry, WorktreeAddRequest}; +use super::{branch, commit, misc, remote, stage, submodule, worktree}; +use crate::error::AppResult; + +pub struct Hooked { + pub value: T, + pub warnings: Vec, +} + +impl Hooked { + fn plain(value: T) -> Self { + Hooked { + value, + warnings: Vec::new(), + } + } +} + +fn ran(path: &str, value: T, hooks: &[PostHook], no_verify: bool) -> Hooked { + let warnings = match super::repo::open(path) { + Ok(repo) if !hooks.is_empty() => run_post(&repo, hooks, no_verify), + _ => Vec::new(), + }; + Hooked { value, warnings } +} + +fn head_oid(path: &str) -> Oid { + super::repo::open(path) + .ok() + .and_then(|repo| repo.head().ok().and_then(|head| head.target())) + .unwrap_or_else(Oid::zero) +} + +fn switched( + path: &str, + no_verify: bool, + op: impl FnOnce() -> AppResult, +) -> AppResult> { + let previous = head_oid(path); + let value = submodule::synced(path, op)?; + let checkout = PostHook::Checkout { + previous, + new: head_oid(path), + branch: true, + }; + Ok(ran(path, value, &[checkout], no_verify)) +} + +fn restored(path: &str, value: T, no_verify: bool) -> Hooked { + let head = head_oid(path); + let checkout = PostHook::Checkout { + previous: head, + new: head, + branch: false, + }; + ran(path, value, &[checkout], no_verify) +} + +fn checked_out(path: &str, value: T, no_verify: bool) -> Hooked { + let head = head_oid(path); + if head.is_zero() { + return Hooked::plain(value); + } + let checkout = PostHook::Checkout { + previous: Oid::zero(), + new: head, + branch: true, + }; + ran(path, value, &[checkout], no_verify) +} + +pub fn checkout_branch(path: &str, name: &str, no_verify: bool) -> AppResult> { + switched(path, no_verify, || branch::checkout_branch(path, name)) +} + +pub fn checkout_detached(path: &str, rev: &str, no_verify: bool) -> AppResult> { + switched(path, no_verify, || branch::checkout_detached(path, rev)) +} + +pub fn branch_create( + path: &str, + name: &str, + from_oid: Option<&str>, + checkout: bool, + no_verify: bool, +) -> AppResult> { + let create = || branch::create(path, name, from_oid, checkout); + if checkout { + switched(path, no_verify, create) + } else { + submodule::synced(path, create).map(Hooked::plain) + } +} + +pub fn checkout_remote_ref( + path: &str, + remote_name: &str, + source_ref: &str, + local_branch: &str, + track: bool, + no_verify: bool, +) -> AppResult> { + switched(path, no_verify, || { + remote::checkout_remote_ref(path, remote_name, source_ref, local_branch, track) + }) +} + +pub fn merge(path: &str, name: &str, no_ff: bool, no_verify: bool) -> AppResult> { + let outcome = submodule::synced(path, || branch::merge(path, name, no_ff))?; + let hooks = PostHook::merged(&outcome); + Ok(ran(path, outcome, &hooks, no_verify)) +} + +pub fn pull( + path: &str, + remote_name: &str, + mode: Option<&str>, + no_verify: bool, +) -> AppResult> { + let (outcome, hooks) = + submodule::synced(path, || remote::pull_reporting(path, remote_name, mode))?; + Ok(ran(path, outcome, &hooks, no_verify)) +} + +pub fn pull_branch(path: &str, branch_name: &str, no_verify: bool) -> AppResult> { + let (outcome, hooks) = remote::pull_branch(path, branch_name)?; + Ok(ran(path, outcome, &hooks, no_verify)) +} + +pub fn rebase(path: &str, upstream: &str, no_verify: bool) -> AppResult> { + let (outcome, hooks) = submodule::synced(path, || branch::rebase_reporting(path, upstream))?; + Ok(ran(path, outcome, &hooks, no_verify)) +} + +pub fn rebase_continue(path: &str, no_verify: bool) -> AppResult> { + let (outcome, hooks) = submodule::synced(path, || branch::rebase_continue(path))?; + Ok(ran(path, outcome, &hooks, no_verify)) +} + +pub fn rebase_interactive( + path: &str, + base: &str, + todo: &[RebaseTodoEntry], + no_verify: bool, +) -> AppResult> { + let (head, hooks) = submodule::synced(path, || { + branch::rebase_interactive_reporting(path, base, todo) + })?; + Ok(ran(path, head, &hooks, no_verify)) +} + +pub fn amend( + path: &str, + message: Option<&str>, + no_verify: bool, +) -> AppResult> { + let (outcome, hook) = commit::amend_reporting(path, message, no_verify)?; + Ok(ran(path, outcome, &[hook], no_verify)) +} + +pub fn reword(path: &str, oid: &str, message: &str, no_verify: bool) -> AppResult> { + let (reworded, hooks) = commit::reword_reporting(path, oid, message)?; + Ok(ran(path, reworded, &hooks, no_verify)) +} + +pub fn discard_file(path: &str, file: &str, no_verify: bool) -> AppResult> { + let restores = { + let repo = super::repo::open(path)?; + let tracked = repo.index()?.get_path(Path::new(file), 0).is_some(); + tracked && submodule::drifted(&repo, file).is_none() + }; + let clean = stage::discard_file(path, file)?; + Ok(if restores { + restored(path, clean, no_verify) + } else { + Hooked::plain(clean) + }) +} + +pub fn discard_all(path: &str, no_verify: bool) -> AppResult>> { + let restores = has_status( + path, + git2::Status::WT_MODIFIED + | git2::Status::WT_DELETED + | git2::Status::WT_TYPECHANGE + | git2::Status::WT_RENAMED, + )?; + let leftovers = stage::discard_all(path)?; + Ok(if restores { + restored(path, leftovers, no_verify) + } else { + Hooked::plain(leftovers) + }) +} + +pub fn discard_staged_file(path: &str, file: &str, no_verify: bool) -> AppResult> { + let clean = stage::discard_staged_file(path, file)?; + Ok(restored(path, clean, no_verify)) +} + +pub fn discard_staged_all(path: &str, no_verify: bool) -> AppResult>> { + let restores = has_status( + path, + git2::Status::INDEX_NEW + | git2::Status::INDEX_MODIFIED + | git2::Status::INDEX_DELETED + | git2::Status::INDEX_RENAMED + | git2::Status::INDEX_TYPECHANGE, + )?; + let leftovers = stage::discard_staged_all(path)?; + Ok(if restores { + restored(path, leftovers, no_verify) + } else { + Hooked::plain(leftovers) + }) +} + +fn has_status(path: &str, wanted: git2::Status) -> AppResult { + let repo = super::repo::open(path)?; + let mut opts = git2::StatusOptions::new(); + opts.include_untracked(false); + let statuses = repo.statuses(Some(&mut opts))?; + let found = statuses + .iter() + .any(|entry| entry.status().intersects(wanted)); + Ok(found) +} + +pub fn stash_restore_files( + path: &str, + index: usize, + paths: &[String], + no_verify: bool, +) -> AppResult>> { + let restored_paths = misc::stash_restore_files(path, index, paths)?; + Ok(if restored_paths.is_empty() { + Hooked::plain(restored_paths) + } else { + restored(path, restored_paths, no_verify) + }) +} + +pub fn clone( + url: &str, + into: &str, + branch: Option<&str>, + on_progress: impl Fn(u32) + Send, + no_verify: bool, +) -> AppResult> { + let root = remote::clone(url, into, branch, on_progress)?; + let path = root.clone(); + Ok(checked_out(&path, root, no_verify)) +} + +pub fn worktree_add( + path: &str, + request: &WorktreeAddRequest, + no_verify: bool, +) -> AppResult> { + let created = worktree::add(path, request)?; + let worktree_path = created.clone(); + Ok(checked_out(&worktree_path, created, no_verify)) +} diff --git a/apps/desktop/src-tauri/src/core/remote.rs b/apps/desktop/src-tauri/src/core/remote.rs index 8e0b1064..5fc18fcd 100644 --- a/apps/desktop/src-tauri/src/core/remote.rs +++ b/apps/desktop/src-tauri/src/core/remote.rs @@ -12,7 +12,7 @@ use git2::{ use crate::error::{AppError, AppResult}; use super::group_update::{FetchProgress, GroupUpdateControl}; -use super::hooks::{pre_push_input, PrePush, PushedRef}; +use super::hooks::{pre_push_input, PostHook, PrePush, PushedRef}; use super::types::{GeneratedKey, GroupUpdateResult, OpOutcome, RefMovement, RemoteInfo}; static CREDENTIAL_PREFS: OnceLock> = OnceLock::new(); @@ -479,6 +479,7 @@ pub fn group_update_controlled( status: "cancelled".into(), message: "Cancelled before completing the repository update".into(), changes: Vec::new(), + ..Default::default() }), Err(error) => Err(error), } @@ -495,6 +496,7 @@ fn group_update_inner( status: "skipped".into(), message: "Repository folder no longer exists".into(), changes: Vec::new(), + ..Default::default() }); } let repo = super::repo::open(path)?; @@ -502,6 +504,7 @@ fn group_update_inner( status: status.into(), message, changes: Vec::new(), + ..Default::default() }; if !pull { let names: Vec = repo.remotes()?.iter().flatten().map(String::from).collect(); @@ -710,6 +713,8 @@ fn group_update_inner( )) })?; super::submodule::follow_recorded(path, &submodules, false); + let hook_warnings = + super::hooks::run_post(&repo, &[PostHook::Merge], control.skips_hooks()); Ok(GroupUpdateResult { status: "ok".into(), message: format!("Fast-forwarded {branch_name} by {behind} commit(s)"), @@ -719,6 +724,7 @@ fn group_update_inner( new_oid: Some(new.to_string()), commits: Some(behind), }], + hook_warnings, }) }); checkout @@ -877,6 +883,7 @@ pub(super) fn fetch_progress_summary( status: status.into(), message, changes, + ..Default::default() } } @@ -924,6 +931,14 @@ fn fetched_refs(repo: &Repository) -> AppResult> { } pub fn pull(path: &str, remote_name: &str, mode: Option<&str>) -> AppResult { + pull_reporting(path, remote_name, mode).map(|(outcome, _)| outcome) +} + +pub(crate) fn pull_reporting( + path: &str, + remote_name: &str, + mode: Option<&str>, +) -> AppResult<(OpOutcome, Vec)> { fetch(path, remote_name, false, false)?; let repo = super::repo::open(path)?; @@ -955,9 +970,11 @@ pub fn pull(path: &str, remote_name: &str, mode: Option<&str>) -> AppResult 0 && behind > 0 { - return super::branch::rebase(path, &upstream_name); + return super::branch::rebase_reporting(path, &upstream_name); } - super::branch::merge(path, &upstream_name, false) + let outcome = super::branch::merge(path, &upstream_name, false)?; + let hooks = PostHook::merged(&outcome); + Ok((outcome, hooks)) } pub(super) fn pull_source( @@ -1311,7 +1328,7 @@ fn tracking_ref_matches(repo: &Repository, remote_name: &str, branch_name: &str) local.is_some() && local == tip(format!("refs/remotes/{remote_name}/{branch_name}")) } -pub fn pull_branch(path: &str, branch_name: &str) -> AppResult { +pub(crate) fn pull_branch(path: &str, branch_name: &str) -> AppResult<(OpOutcome, Vec)> { let (upstream_name, remote_name) = { let repo = super::repo::open(path)?; let branch = repo.find_branch(branch_name, git2::BranchType::Local)?; @@ -1340,7 +1357,9 @@ pub fn pull_branch(path: &str, branch_name: &str) -> AppResult { .as_deref() == Some(branch_name); if is_head { - return super::branch::merge(path, &upstream_name, false); + let outcome = super::branch::merge(path, &upstream_name, false)?; + let hooks = PostHook::merged(&outcome); + return Ok((outcome, hooks)); } let branch = repo.find_branch(branch_name, git2::BranchType::Local)?; @@ -1355,17 +1374,23 @@ pub fn pull_branch(path: &str, branch_name: &str) -> AppResult { .ok_or_else(|| AppError::other("upstream has no target"))?; if local_oid == upstream_oid { - return Ok(OpOutcome { - status: "up_to_date".into(), - message: format!("{branch_name} is already up to date"), - }); + return Ok(( + OpOutcome { + status: "up_to_date".into(), + message: format!("{branch_name} is already up to date"), + }, + Vec::new(), + )); } let (ahead, behind) = repo.graph_ahead_behind(local_oid, upstream_oid)?; if behind == 0 { - return Ok(OpOutcome { - status: "up_to_date".into(), - message: format!("{branch_name} is ahead of {upstream_name} — nothing to pull"), - }); + return Ok(( + OpOutcome { + status: "up_to_date".into(), + message: format!("{branch_name} is ahead of {upstream_name} — nothing to pull"), + }, + Vec::new(), + )); } if ahead > 0 { return Err(AppError::other(format!( @@ -1377,10 +1402,13 @@ pub fn pull_branch(path: &str, branch_name: &str) -> AppResult { upstream_oid, &format!("pull: fast-forward to {upstream_name}"), )?; - Ok(OpOutcome { - status: "fast_forward".into(), - message: format!("Fast-forwarded {branch_name} to {upstream_name}"), - }) + Ok(( + OpOutcome { + status: "fast_forward".into(), + message: format!("Fast-forwarded {branch_name} to {upstream_name}"), + }, + Vec::new(), + )) } const PR_HEAD_TMP_REF: &str = "refs/angkorgit/pr-head"; diff --git a/apps/desktop/src-tauri/src/core/types.rs b/apps/desktop/src-tauri/src/core/types.rs index 9ffcddb1..ce5c1fc0 100644 --- a/apps/desktop/src-tauri/src/core/types.rs +++ b/apps/desktop/src-tauri/src/core/types.rs @@ -307,12 +307,31 @@ pub struct GeneratedKey { pub public_key: String, } -#[derive(Serialize, Debug, Clone)] +#[derive(Serialize, Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct GroupUpdateResult { pub status: String, pub message: String, pub changes: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub hook_warnings: Vec, +} + +#[derive(Serialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct HookWarning { + pub hook: String, + pub status: Option, + pub message: String, + pub output: String, +} + +#[derive(Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct HookWarningEvent { + pub repo_path: String, + #[serde(flatten)] + pub warning: HookWarning, } #[derive(Serialize, Debug, Clone)] diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index a2f9e9d9..12032550 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -44,6 +44,7 @@ pub mod test_api { stash_create, stash_files, stash_list, stash_pop, stash_restore_files, tag_create, tag_delete, tag_list, }; + pub use crate::core::post_hooks; pub use crate::core::pull_preview::pull_preview; pub use crate::core::remote::{ add as remote_add, checkout_remote_ref, fetch, group_update, group_update_controlled, diff --git a/apps/desktop/src-tauri/tests/clone_hooks.rs b/apps/desktop/src-tauri/tests/clone_hooks.rs new file mode 100644 index 00000000..ad7fe315 --- /dev/null +++ b/apps/desktop/src-tauri/tests/clone_hooks.rs @@ -0,0 +1,115 @@ +use std::path::Path; + +use angkorgit_lib::test_api as core; + +fn shell_path(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +fn head_of(path: &Path) -> String { + git2::Repository::open(path) + .unwrap() + .head() + .unwrap() + .target() + .unwrap() + .to_string() +} + +#[test] +fn post_checkout_runs_after_clone_with_a_zero_previous_head() { + let root = std::env::temp_dir().join(format!( + "angkorgit-clone-hooks-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let home = root.join("home"); + let hooks = root.join("hooks"); + let log = root.join("post-checkout.log"); + std::fs::create_dir_all(&home).unwrap(); + let global = home.join(".gitconfig"); + std::fs::write( + &global, + format!( + "[core]\n\thooksPath = {}\n\tautocrlf = false\n[user]\n\tname = Test User\n\temail = \ + test@angkorgit.dev\n[commit]\n\tgpgsign = false\n", + shell_path(&hooks) + ), + ) + .unwrap(); + std::env::set_var("HOME", &home); + std::env::set_var("GIT_CONFIG_GLOBAL", &global); + std::env::set_var("XDG_CONFIG_HOME", home.join(".config")); + if !core::hook_runner_available() { + eprintln!("skipping: git 2.36 or newer is not on PATH"); + let _ = std::fs::remove_dir_all(&root); + return; + } + std::fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join("post-checkout"); + std::fs::write( + &hook, + format!( + "#!/bin/sh\necho \"post-checkout $*\" >> '{}'\n", + shell_path(&log) + ), + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + + let source = root.join("source"); + core::init(source.to_str().unwrap()).unwrap(); + std::fs::write(source.join("a.txt"), "one\n").unwrap(); + core::stage_all(source.to_str().unwrap()).unwrap(); + let head = core::commit(source.to_str().unwrap(), "one", false) + .unwrap() + .oid; + + let into = root.join("clone"); + let cloned = core::post_hooks::clone( + source.to_str().unwrap(), + into.to_str().unwrap(), + None, + |_| {}, + false, + ) + .unwrap(); + assert!(cloned.warnings.is_empty()); + assert_eq!(head_of(&into), head); + assert_eq!( + std::fs::read_to_string(&log).unwrap(), + format!("post-checkout {} {head} 1\n", "0".repeat(40)) + ); + + std::fs::remove_file(&log).unwrap(); + core::post_hooks::clone( + source.to_str().unwrap(), + root.join("clone-without-hooks").to_str().unwrap(), + None, + |_| {}, + true, + ) + .unwrap(); + assert!(!log.exists()); + + let empty = root.join("empty"); + core::init(empty.to_str().unwrap()).unwrap(); + core::post_hooks::clone( + empty.to_str().unwrap(), + root.join("clone-of-empty").to_str().unwrap(), + None, + |_| {}, + false, + ) + .unwrap(); + assert!(!log.exists()); + + let _ = std::fs::remove_dir_all(&root); +} diff --git a/apps/desktop/src-tauri/tests/git_engine.rs b/apps/desktop/src-tauri/tests/git_engine.rs index 80eb04ed..ebebd6e7 100644 --- a/apps/desktop/src-tauri/tests/git_engine.rs +++ b/apps/desktop/src-tauri/tests/git_engine.rs @@ -3505,6 +3505,9 @@ fn group_pull_matches_toolbar_pull_with_submodule_metadata_and_lfs_attributes() #[test] fn group_pull_matches_toolbar_pull_with_active_hooks() { + if !hooks_runnable() { + return; + } let local = TempRepo::new(); local.write("a.txt", "base\n"); commit_all(&local, "base"); @@ -3514,28 +3517,23 @@ fn group_pull_matches_toolbar_pull_with_active_hooks() { let toolbar = clone_of(&origin, &local, "toolbar-hooks"); let repo = git2::Repository::open(other.path()).unwrap(); let hooks = repo.path().join("custom-hooks"); - std::fs::create_dir_all(&hooks).unwrap(); for path in [other.path(), toolbar.path()] { core::set_config(Some(path), "core.hooksPath", hooks.to_str().unwrap(), false).unwrap(); } for name in ["post-checkout", "post-merge"] { - let hook = hooks.join(name); - std::fs::write(&hook, "#!/bin/sh\nprintf invoked > hook-ran\n").unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); - } + write_hook(&hooks, name, &format!("printf '%s' \"$*\" > {name}-ran")); } local.write("a.txt", "updated\n"); let new = commit_all(&local, "updated"); core::push(local.path(), "origin", None, false, false, true, false).unwrap(); assert_eq!(core::group_update(other.path(), true).unwrap().status, "ok"); - core::pull(toolbar.path(), "origin", Some("merge")).unwrap(); + core::post_hooks::pull(toolbar.path(), "origin", Some("merge"), false).unwrap(); assert_eq!(other.read("a.txt"), toolbar.read("a.txt")); assert_eq!(repo.head().unwrap().target().unwrap().to_string(), new); - assert!(!other.dir.join("hook-ran").exists()); - assert!(!toolbar.dir.join("hook-ran").exists()); + for pulled in [&other, &toolbar] { + assert_eq!(pulled.read("post-merge-ran"), "0"); + assert!(!pulled.dir.join("post-checkout-ran").exists()); + } std::fs::remove_dir_all(origin).unwrap(); } @@ -3612,8 +3610,8 @@ fn group_cancel_acknowledges_a_stalled_remote_without_waiting_for_the_socket() { fn group_run_registry_keeps_cancellation_on_in_flight_handles_after_finish() { let local = TempRepo::new(); let id = local.path(); - core::group_update_start(id).unwrap(); - assert!(core::group_update_start(id).is_err()); + core::group_update_start(id, false).unwrap(); + assert!(core::group_update_start(id, false).is_err()); let control = core::group_update_control(id).unwrap(); assert!(!control.is_cancelled()); core::group_update_cancel(id).unwrap(); @@ -5439,3 +5437,530 @@ fn an_amend_hook_that_switches_branch_leaves_both_branches_alone() { assert_eq!(branch_tip(&repo, "master"), base); assert_eq!(branch_tip(&repo, "other"), base); } + +const POST_HOOK_LOG: &str = ".git/post-hooks.log"; + +fn record_post_hooks(dir: &std::path::Path, log: &str) { + for name in ["post-checkout", "post-merge"] { + write_hook(dir, name, &format!("echo \"{name} $*\" >> '{log}'")); + } + write_hook( + dir, + "post-rewrite", + &format!("{{ echo \"post-rewrite $*\"; cat; }} >> '{log}'"), + ); +} + +fn post_hook_runs(repo: &TempRepo) -> Vec { + let file = repo.dir.join(POST_HOOK_LOG); + let text = std::fs::read_to_string(&file).unwrap_or_default(); + let _ = std::fs::remove_file(&file); + text.lines().map(str::to_string).collect() +} + +fn rev(repo: &TempRepo, spec: &str) -> String { + git2::Repository::open(repo.path()) + .unwrap() + .revparse_single(spec) + .unwrap() + .peel_to_commit() + .unwrap() + .id() + .to_string() +} + +fn shell_path(path: &std::path::Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +#[test] +fn post_checkout_runs_for_branch_switches_with_both_heads_and_flag_1() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + let first = commit_all(&repo, "one"); + core::branch_create(repo.path(), "other", None, false).unwrap(); + repo.write("a.txt", "two\n"); + let second = commit_all(&repo, "two"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let switched = core::post_hooks::checkout_branch(repo.path(), "other", false).unwrap(); + assert!(switched.warnings.is_empty()); + assert_eq!(repo.read("a.txt"), "one\n"); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {second} {first} 1")] + ); + + core::post_hooks::branch_create(repo.path(), "topic", None, true, false).unwrap(); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {first} {first} 1")] + ); + + core::post_hooks::branch_create(repo.path(), "quiet", None, false, false).unwrap(); + assert!(post_hook_runs(&repo).is_empty()); + + core::post_hooks::checkout_detached(repo.path(), &second, false).unwrap(); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {first} {second} 1")] + ); +} + +#[test] +fn discarding_changes_runs_post_checkout_with_flag_0_like_git_restore() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + repo.write("b.txt", "b\n"); + let head = commit_all(&repo, "one"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + let restored = vec![format!("post-checkout {head} {head} 0")]; + + repo.write("a.txt", "changed\n"); + core::post_hooks::discard_file(repo.path(), "a.txt", false).unwrap(); + assert_eq!(repo.read("a.txt"), "one\n"); + assert_eq!(post_hook_runs(&repo), restored); + + repo.write("new.txt", "untracked\n"); + core::post_hooks::discard_file(repo.path(), "new.txt", false).unwrap(); + assert!(!repo.dir.join("new.txt").exists()); + assert!(post_hook_runs(&repo).is_empty()); + + repo.write("new.txt", "untracked\n"); + core::post_hooks::discard_all(repo.path(), false).unwrap(); + assert!(post_hook_runs(&repo).is_empty()); + + repo.write("a.txt", "changed\n"); + repo.write("b.txt", "changed\n"); + core::post_hooks::discard_all(repo.path(), false).unwrap(); + assert_eq!(post_hook_runs(&repo), restored); + + repo.write("a.txt", "staged\n"); + core::stage_file(repo.path(), "a.txt").unwrap(); + core::post_hooks::discard_staged_file(repo.path(), "a.txt", false).unwrap(); + assert_eq!(post_hook_runs(&repo), restored); + + repo.write("b.txt", "staged\n"); + core::stage_file(repo.path(), "b.txt").unwrap(); + core::post_hooks::discard_staged_all(repo.path(), false).unwrap(); + assert_eq!(repo.read("b.txt"), "b\n"); + assert_eq!(post_hook_runs(&repo), restored); + + repo.write("a.txt", "stashed\n"); + core::stash_create(repo.path(), None, false, &[]).unwrap(); + core::post_hooks::stash_restore_files(repo.path(), 0, &["a.txt".to_string()], false).unwrap(); + assert_eq!(repo.read("a.txt"), "stashed\n"); + assert_eq!(post_hook_runs(&repo), restored); +} + +#[test] +fn post_merge_runs_after_a_merge_commit_and_a_fast_forward_only() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "feature", None, true).unwrap(); + repo.write("f.txt", "feature\n"); + commit_all(&repo, "feature"); + core::checkout_branch(repo.path(), "master").unwrap(); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let ff = core::post_hooks::merge(repo.path(), "feature", false, false).unwrap(); + assert_eq!(ff.value.status, "fast_forward"); + assert_eq!(post_hook_runs(&repo), vec!["post-merge 0"]); + + let again = core::post_hooks::merge(repo.path(), "feature", false, false).unwrap(); + assert_eq!(again.value.status, "up_to_date"); + assert!(post_hook_runs(&repo).is_empty()); + + core::branch_create(repo.path(), "side", None, true).unwrap(); + repo.write("s.txt", "side\n"); + commit_all(&repo, "side"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("m.txt", "master\n"); + commit_all(&repo, "master"); + let merged = core::post_hooks::merge(repo.path(), "side", false, false).unwrap(); + assert_eq!(merged.value.status, "ok"); + assert_eq!(head_commit(&repo).1, 2); + assert_eq!(post_hook_runs(&repo), vec!["post-merge 0"]); + + core::branch_create(repo.path(), "clash", None, true).unwrap(); + repo.write("a.txt", "clash\n"); + commit_all(&repo, "clash"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("a.txt", "master edit\n"); + commit_all(&repo, "master edit"); + let conflicted = core::post_hooks::merge(repo.path(), "clash", true, false).unwrap(); + assert_eq!(conflicted.value.status, "conflicts"); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn post_rewrite_after_amend_and_reword_gets_the_old_and_new_commit() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + let first = commit_all(&repo, "one"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + repo.write("a.txt", "two\n"); + core::stage_all(repo.path()).unwrap(); + let amended = core::post_hooks::amend(repo.path(), Some("one, amended"), false).unwrap(); + let new = amended.value.oid; + assert_ne!(new, first); + assert_eq!( + post_hook_runs(&repo), + vec!["post-rewrite amend".to_string(), format!("{first} {new}")] + ); + + let reworded = core::post_hooks::reword(repo.path(), &new, "one, reworded", false).unwrap(); + assert_eq!( + post_hook_runs(&repo), + vec![ + "post-rewrite amend".to_string(), + format!("{new} {}", reworded.value) + ] + ); + + repo.write("b.txt", "b\n"); + commit_all(&repo, "plain commit"); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn post_rewrite_after_rebase_lists_every_commit_once() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write("t1.txt", "t1\n"); + let t1 = commit_all(&repo, "t1"); + repo.write("t2.txt", "t2\n"); + let t2 = commit_all(&repo, "t2"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("m.txt", "m\n"); + let onto = commit_all(&repo, "m"); + core::checkout_branch(repo.path(), "topic").unwrap(); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let rebased = core::post_hooks::rebase(repo.path(), "master", false).unwrap(); + assert_eq!(rebased.value.status, "ok"); + assert_eq!(rev(&repo, "HEAD~2"), onto); + assert_eq!( + post_hook_runs(&repo), + vec![ + format!("post-checkout {t2} {onto} 1"), + "post-rewrite rebase".to_string(), + format!("{t1} {}", rev(&repo, "HEAD~1")), + format!("{t2} {}", rev(&repo, "HEAD")), + ] + ); + + let again = core::post_hooks::rebase(repo.path(), "topic", false).unwrap(); + assert_eq!(again.value.status, "ok"); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn post_rewrite_runs_once_when_a_paused_rebase_completes() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write("t1.txt", "t1\n"); + let t1 = commit_all(&repo, "t1"); + repo.write("a.txt", "topic\n"); + let t2 = commit_all(&repo, "t2"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("a.txt", "master\n"); + let onto = commit_all(&repo, "m"); + core::checkout_branch(repo.path(), "topic").unwrap(); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let paused = core::post_hooks::rebase(repo.path(), "master", false).unwrap(); + assert_eq!(paused.value.status, "conflicts"); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {t2} {onto} 1")] + ); + + core::conflict_resolve(repo.path(), "a.txt", "resolved\n").unwrap(); + let done = core::post_hooks::rebase_continue(repo.path(), false).unwrap(); + assert_eq!(done.value.status, "ok", "{}", done.value.message); + assert_eq!( + post_hook_runs(&repo), + vec![ + "post-rewrite rebase".to_string(), + format!("{t1} {}", rev(&repo, "HEAD~1")), + format!("{t2} {}", rev(&repo, "HEAD")), + ] + ); +} + +#[test] +fn interactive_rebase_maps_squashed_commits_and_leaves_out_dropped_ones() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + let base = commit_all(&repo, "base"); + repo.write("c1.txt", "c1\n"); + let c1 = commit_all(&repo, "c1"); + repo.write("c2.txt", "c2\n"); + let c2 = commit_all(&repo, "c2"); + repo.write("c3.txt", "c3\n"); + let c3 = commit_all(&repo, "c3"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let todo = vec![ + todo_entry(&c1, "pick", None), + todo_entry(&c2, "squash", Some("c1 and c2")), + todo_entry(&c3, "drop", None), + ]; + let rebased = core::post_hooks::rebase_interactive(repo.path(), &base, &todo, false).unwrap(); + let squashed = rebased.value; + assert_eq!(rev(&repo, "HEAD~1"), base); + assert_eq!( + post_hook_runs(&repo), + vec![ + format!("post-checkout {c3} {base} 1"), + "post-rewrite rebase".to_string(), + format!("{c1} {squashed}"), + format!("{c2} {squashed}"), + ] + ); +} + +#[test] +fn pull_with_rebase_runs_post_rewrite_and_never_post_merge() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let other = clone_of(&origin, &local, "pull-hooks"); + record_post_hooks(&default_hooks(&other), POST_HOOK_LOG); + + local.write("b.txt", "b\n"); + commit_all(&local, "b"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let behind = core::post_hooks::pull(other.path(), "origin", Some("rebase"), false).unwrap(); + assert_eq!(behind.value.status, "fast_forward"); + assert_eq!(post_hook_runs(&other), vec!["post-merge 0"]); + + local.write("c.txt", "c\n"); + commit_all(&local, "c"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + other.write("o.txt", "o\n"); + let mine = commit_all(&other, "o"); + let diverged = core::post_hooks::pull(other.path(), "origin", Some("rebase"), false).unwrap(); + assert_eq!(diverged.value.status, "ok", "{}", diverged.value.message); + assert_eq!(head_commit(&other).1, 1); + assert_eq!( + post_hook_runs(&other), + vec![ + format!("post-checkout {mine} {} 1", rev(&other, "origin/master")), + "post-rewrite rebase".to_string(), + format!("{mine} {}", rev(&other, "HEAD")), + ] + ); + + local.write("d.txt", "d\n"); + commit_all(&local, "d"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + other.write("p.txt", "p\n"); + commit_all(&other, "p"); + let merged = core::post_hooks::pull(other.path(), "origin", Some("merge"), false).unwrap(); + assert_eq!(merged.value.status, "ok"); + assert_eq!(post_hook_runs(&other), vec!["post-merge 0"]); + + let current = core::post_hooks::pull(other.path(), "origin", Some("merge"), false).unwrap(); + assert_eq!(current.value.status, "up_to_date"); + assert!(post_hook_runs(&other).is_empty()); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[test] +fn a_failing_post_hook_is_a_warning_and_the_operation_stands() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + let first = commit_all(&repo, "one"); + core::branch_create(repo.path(), "other", None, false).unwrap(); + repo.write("a.txt", "two\n"); + commit_all(&repo, "two"); + write_hook( + &default_hooks(&repo), + "post-checkout", + "echo checked out >&2\nexit 3", + ); + write_hook(&default_hooks(&repo), "post-merge", "echo merged\nexit 1"); + + let switched = core::post_hooks::checkout_branch(repo.path(), "other", false).unwrap(); + assert_eq!(rev(&repo, "HEAD"), first); + assert_eq!(switched.warnings.len(), 1); + let warning = &switched.warnings[0]; + assert_eq!(warning.hook, "post-checkout"); + assert_eq!(warning.status, Some(3)); + assert_eq!( + warning.message, + "The post-checkout hook failed (exit code 3)." + ); + assert_eq!(warning.output, "checked out"); + + let merged = core::post_hooks::merge(repo.path(), "master", false, false).unwrap(); + assert_eq!(merged.value.status, "fast_forward"); + assert_eq!(rev(&repo, "HEAD"), branch_tip(&repo, "master")); + assert_eq!(merged.warnings.len(), 1); + assert_eq!(merged.warnings[0].hook, "post-merge"); + assert_eq!(merged.warnings[0].status, Some(1)); + assert_eq!(merged.warnings[0].output, "merged"); +} + +#[test] +fn skipping_hooks_suppresses_every_post_hook() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, false).unwrap(); + repo.write("m.txt", "m\n"); + commit_all(&repo, "m"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + core::post_hooks::checkout_branch(repo.path(), "topic", true).unwrap(); + repo.write("t.txt", "t\n"); + commit_all(&repo, "t"); + core::post_hooks::rebase(repo.path(), "master", true).unwrap(); + repo.write("t.txt", "amended\n"); + core::stage_all(repo.path()).unwrap(); + core::post_hooks::amend(repo.path(), None, true).unwrap(); + repo.write("t.txt", "dirty\n"); + core::post_hooks::discard_file(repo.path(), "t.txt", true).unwrap(); + core::post_hooks::checkout_branch(repo.path(), "master", true).unwrap(); + let merged = core::post_hooks::merge(repo.path(), "topic", false, true).unwrap(); + assert_eq!(merged.value.status, "fast_forward"); + assert!(merged.warnings.is_empty()); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn group_pull_runs_post_merge_only_where_it_fast_forwarded() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let behind = clone_of(&origin, &local, "group-behind"); + let current = clone_of(&origin, &local, "group-current"); + let failing = clone_of(&origin, &local, "group-failing"); + local.write("a.txt", "next\n"); + let next = commit_all(&local, "next"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + core::pull(current.path(), "origin", None).unwrap(); + for repo in [&behind, ¤t] { + record_post_hooks(&default_hooks(repo), POST_HOOK_LOG); + } + write_hook( + &default_hooks(&failing), + "post-merge", + "echo install failed >&2\nexit 2", + ); + + let control = core::GroupUpdateControl::default(); + let pulled = core::group_update_controlled(behind.path(), true, &control).unwrap(); + assert_eq!(pulled.status, "ok"); + assert!(pulled.hook_warnings.is_empty()); + assert_eq!(post_hook_runs(&behind), vec!["post-merge 0"]); + + let unchanged = core::group_update_controlled(current.path(), true, &control).unwrap(); + assert_eq!(unchanged.status, "up_to_date"); + assert!(post_hook_runs(¤t).is_empty()); + + let warned = core::group_update_controlled(failing.path(), true, &control).unwrap(); + assert_eq!(warned.status, "ok"); + assert_eq!(rev(&failing, "HEAD"), next); + assert_eq!(warned.hook_warnings.len(), 1); + assert_eq!(warned.hook_warnings[0].hook, "post-merge"); + assert_eq!(warned.hook_warnings[0].status, Some(2)); + assert_eq!(warned.hook_warnings[0].output, "install failed"); + + local.write("a.txt", "last\n"); + let last = commit_all(&local, "last"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let skipping = core::GroupUpdateControl::skipping_hooks(true); + for repo in [&behind, &failing] { + let result = core::group_update_controlled(repo.path(), true, &skipping).unwrap(); + assert_eq!(result.status, "ok"); + assert!(result.hook_warnings.is_empty()); + assert_eq!(rev(repo, "HEAD"), last); + } + assert!(post_hook_runs(&behind).is_empty()); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[test] +fn worktree_add_runs_post_checkout_inside_the_new_worktree() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + let head = commit_all(&repo, "one"); + let log = repo.dir.join(POST_HOOK_LOG); + write_hook( + &default_hooks(&repo), + "post-checkout", + &format!( + "echo \"post-checkout $*\" >> '{}'\ntouch post-checkout-ran-here", + shell_path(&log) + ), + ); + let (dir, _cleanup) = worktree_target(&repo, "post-checkout"); + + let added = core::post_hooks::worktree_add( + repo.path(), + &core::WorktreeAddRequest { + directory: dir.to_string_lossy().to_string(), + branch: "wt".to_string(), + create_branch: true, + base: None, + }, + false, + ) + .unwrap(); + assert!(added.warnings.is_empty()); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {ZERO_OID} {head} 1")] + ); + assert!(dir.join("post-checkout-ran-here").exists()); + assert!(!repo.dir.join("post-checkout-ran-here").exists()); +} diff --git a/apps/desktop/src/app/App.tsx b/apps/desktop/src/app/App.tsx index fd0951d1..fa7456d3 100644 --- a/apps/desktop/src/app/App.tsx +++ b/apps/desktop/src/app/App.tsx @@ -6,6 +6,7 @@ import { Spinner, TooltipProvider } from '@angkorgit/design-system'; import { SplashScreen } from './SplashScreen'; import { ConfirmHost } from '@/components/confirm'; import { HookFailureHost } from '@/components/hookFailure'; +import { HookWarningHost } from '@/components/hookWarnings'; import { ProfilePromptHost } from '@/components/profilePrompt'; import { ErrorBoundary } from '@/components/ErrorBoundary'; import { WelcomePage } from '@/features/repository/WelcomePage'; @@ -192,6 +193,7 @@ export function App() { + = { commit: { outcome: 'Nothing was committed. Your message is still in the commit box.', @@ -35,6 +42,33 @@ const COPY: Record = { }, }; +function HookOutput({ output }: { output: string }) { + return output ? ( +
+      {output}
+    
+ ) : ( +

The hook printed nothing.

+ ); +} + +function CopyOutputButton({ output }: { output: string }) { + const copy = () => { + void navigator.clipboard.writeText(output).then( + () => toast.success('Copied the hook output'), + () => toast.error('Could not copy the hook output'), + ); + }; + return ( + + ); +} + export function HookFailedDialog({ failure, onRetry, @@ -45,12 +79,6 @@ export function HookFailedDialog({ onClose: () => void; }) { const output = useMemo(() => cleanCliOutput(failure?.output ?? ''), [failure?.output]); - const copy = () => { - void navigator.clipboard.writeText(output).then( - () => toast.success('Copied the hook output'), - () => toast.error('Could not copy the hook output'), - ); - }; const text = COPY[failure?.operation ?? 'commit']; return ( !next && onClose()}> @@ -61,20 +89,9 @@ export function HookFailedDialog({ {failure?.message} {text.outcome} - {output ? ( -
-            {output}
-          
- ) : ( -

The hook printed nothing.

- )} + - +
); } + +export function HookWarningDialog({ warning, onClose }: { warning: HookWarningView | null; onClose: () => void }) { + const output = useMemo(() => cleanCliOutput(warning?.output ?? ''), [warning?.output]); + return ( + !next && onClose()}> + + + The {warning?.hook ?? 'post-checkout'} hook failed + + {warning?.message} Nothing was undone in {warning?.repoName}: git ignores the exit code of this hook. + + + + + + + + + + ); +} diff --git a/apps/desktop/src/components/Toolbar.tsx b/apps/desktop/src/components/Toolbar.tsx index 20807aab..83e1916a 100644 --- a/apps/desktop/src/components/Toolbar.tsx +++ b/apps/desktop/src/components/Toolbar.tsx @@ -227,6 +227,8 @@ function RepoSwitcher() { ); } +const PULL_HOOKS = ['post-merge', 'post-rewrite', 'post-checkout']; + const STATE_LABELS: Record = { rebase: 'Rebase in progress', merge: 'Merge in progress', @@ -670,6 +672,13 @@ export function Toolbar({ onRefresh }: { onRefresh: () => Promise }) { void run('Pull (rebase)', () => ipc.pull(repo.path, remote, 'rebase'))}> Pull with rebase + {repoHooks.some((name) => PULL_HOOKS.includes(name)) && ( + void run('Pull without hooks', () => ipc.pull(repo.path, remote, undefined, true))} + > + Pull without hooks + + )} {remotes.length > 1 && ( <> diff --git a/apps/desktop/src/components/hookWarnings.tsx b/apps/desktop/src/components/hookWarnings.tsx new file mode 100644 index 00000000..f7edca81 --- /dev/null +++ b/apps/desktop/src/components/hookWarnings.tsx @@ -0,0 +1,50 @@ +import { useEffect } from 'react'; +import { create } from 'zustand'; +import { toast } from 'sonner'; +import type { HookWarningEvent } from '@angkorgit/core'; +import { listen } from '@/core/ipc'; +import { basename } from '@/shared/utils'; +import { HookWarningDialog } from './HookFailedDialog'; + +const useHookWarnings = create<{ open: HookWarningEvent | null }>(() => ({ open: null })); + +const AFTER_OPERATION_TOAST_MS = 600; + +export function reportHookWarning(warning: HookWarningEvent): void { + window.setTimeout(() => showHookWarning(warning), AFTER_OPERATION_TOAST_MS); +} + +function showHookWarning(warning: HookWarningEvent): void { + const repoName = basename(warning.repoPath); + if (warning.status === null) { + toast.warning(`The ${warning.hook} hook did not run`, { description: warning.message, duration: 12000 }); + return; + } + toast.warning(warning.message, { + description: `Nothing was undone in ${repoName}.`, + duration: 12000, + action: { label: 'Show output', onClick: () => useHookWarnings.setState({ open: warning }) }, + }); +} + +export function HookWarningHost() { + const open = useHookWarnings((s) => s.open); + useEffect(() => { + let cancelled = false; + let unlisten: (() => void) | undefined; + void listen('hook-warning', (payload) => reportHookWarning(payload as HookWarningEvent)).then((stop) => { + if (cancelled) stop(); + else unlisten = stop; + }); + return () => { + cancelled = true; + unlisten?.(); + }; + }, []); + return ( + useHookWarnings.setState({ open: null })} + /> + ); +} diff --git a/apps/desktop/src/core/ipc.ts b/apps/desktop/src/core/ipc.ts index 4905b0f4..f8f00b9d 100644 --- a/apps/desktop/src/core/ipc.ts +++ b/apps/desktop/src/core/ipc.ts @@ -28,6 +28,7 @@ import type { TagInfo, WorktreeAddRequest, WorktreeInfo, + HookWarningEvent, } from '@angkorgit/core'; import type { FileBlame } from '@angkorgit/core'; let demo = null as unknown as typeof import('./demo'); @@ -116,8 +117,19 @@ export async function fullscreenState(): Promise { .catch(() => false); } +const demoListeners = new Map void>>(); + +function demoEmit(event: string, payload: unknown): void { + for (const handler of demoListeners.get(event) ?? []) handler(payload); +} + export async function listen(event: string, handler: (payload: unknown) => void): Promise<() => void> { - if (!isTauri()) return () => {}; + if (!isTauri()) { + const handlers = demoListeners.get(event) ?? new Set(); + handlers.add(handler); + demoListeners.set(event, handlers); + return () => handlers.delete(handler); + } const { listen } = await import('@tauri-apps/api/event'); const unlisten = await listen(event, (e) => handler(e.payload)); return unlisten; @@ -157,6 +169,46 @@ function demoHooksDelay(): number { } } +const DEMO_POST_HOOK_OUTPUT: Record = { + 'post-checkout': [ + 'Installing dependencies for the checked-out branch…', + '\u001b[31mnpm ERR!\u001b[39m network request to registry.npmjs.org failed', + 'husky - post-checkout script failed (code 1)', + ], + 'post-merge': [ + 'Installing dependencies after the merge…', + '\u001b[31mnpm ERR!\u001b[39m network request to registry.npmjs.org failed', + 'husky - post-merge script failed (code 1)', + ], +}; + +const DEMO_POST_HOOKS = 'angkorgit-demo-post-hooks'; + +function demoPostHooks(): 'pass' | 'fail' | null { + try { + const value = localStorage.getItem(DEMO_POST_HOOKS); + return value === 'pass' || value === 'fail' ? value : null; + } catch { + return null; + } +} + +function demoPostHookWarning(path: string, hook: string): HookWarningEvent { + return { + repoPath: path, + hook, + status: 1, + message: `The ${hook} hook failed (exit code 1).`, + output: (DEMO_POST_HOOK_OUTPUT[hook] ?? []).join('\n'), + }; +} + +function demoRunPostHook(path: string, hook: string, noVerify = false): void { + if (demoPostHooks() === 'fail' && !noVerify) demoEmit('hook-warning', demoPostHookWarning(path, hook)); +} + +const demoGroupRunsSkippingHooks = new Set(); + const DEMO_PUSH_REJECTED = 'angkorgit-demo-push-rejected'; const DEMO_CHECKOUT = 'angkorgit-demo-checkout'; @@ -436,7 +488,12 @@ export const ipc = { return invoke('commit_amend', { path, message, noVerify }); }, async repoHooks(path: string): Promise { - if (!isTauri()) return demoHooks() ? ['pre-commit', 'pre-push'] : []; + if (!isTauri()) { + return [ + ...(demoHooks() ? ['pre-commit', 'pre-push'] : []), + ...(demoPostHooks() ? ['post-checkout', 'post-merge'] : []), + ]; + } return invoke('repo_hooks', { path }); }, async reword(path: string, oid: string, message: string): Promise { @@ -522,6 +579,7 @@ export const ipc = { async checkout(path: string, name: string): Promise { if (!isTauri()) { if (demoCheckoutMovesHead()) demo.demoCheckout(name); + demoRunPostHook(path, 'post-checkout'); return; } return invoke('branch_checkout', { path, name }); @@ -614,21 +672,37 @@ export const ipc = { } return invoke('remote_fetch', { path, remote, tags, prune }); }, - async groupStart(runId: string): Promise { - if (!isTauri()) return; - return invoke('repository_group_start', { runId }); + async groupStart(runId: string, noVerify = false): Promise { + if (!isTauri()) { + if (noVerify) demoGroupRunsSkippingHooks.add(runId); + return; + } + return invoke('repository_group_start', { runId, noVerify }); }, async groupCancel(runId: string): Promise { if (!isTauri()) return []; return invoke('repository_group_cancel', { runId }); }, async groupFinish(runId: string): Promise { - if (!isTauri()) return; + if (!isTauri()) { + demoGroupRunsSkippingHooks.delete(runId); + return; + } return invoke('repository_group_finish', { runId }); }, async groupUpdate(path: string, pull: boolean, runId: string): Promise { if (!isTauri()) { await delay(400); + if (pull && demoPostHooks()) { + const skipping = demoGroupRunsSkippingHooks.has(runId); + const warning = demoPostHooks() === 'fail' && !skipping ? demoPostHookWarning(path, 'post-merge') : null; + return { + status: 'ok', + message: 'Fast-forwarded main by 2 commit(s) (demo)', + changes: [{ name: 'main', oldOid: 'a1b2c3d4e5f6', newOid: 'f6e5d4c3b2a1', commits: 2 }], + hookWarnings: warning ? [{ hook: warning.hook, status: warning.status, message: warning.message, output: warning.output }] : [], + }; + } return { status: 'up_to_date', message: pull ? 'main is already up to date (demo)' : 'Fetched origin; no refs moved (demo)', changes: [] }; } return invoke('repository_group_update', { path, pull, runId }); @@ -637,12 +711,14 @@ export const ipc = { if (!isTauri()) return demo.demoPullPreview(demoPullScenario(), remote); return invoke('pull_preview', { path, remote }); }, - async pull(path: string, remote: string, mode?: 'merge' | 'rebase'): Promise { + async pull(path: string, remote: string, mode?: 'merge' | 'rebase', noVerify = false): Promise { if (!isTauri()) { await delay(400); - return { status: 'ok', message: 'Already up to date (demo)' }; + if (!demoPostHooks()) return { status: 'ok', message: 'Already up to date (demo)' }; + demoRunPostHook(path, 'post-merge', noVerify); + return { status: 'fast_forward', message: `Fast-forwarded main to ${remote}/main (demo)` }; } - return invoke('remote_pull', { path, remote, mode: mode ?? null }); + return invoke('remote_pull', { path, remote, mode: mode ?? null, noVerify }); }, async push( path: string, diff --git a/apps/desktop/src/features/commit/WorkingCopyPanel.tsx b/apps/desktop/src/features/commit/WorkingCopyPanel.tsx index 9e898360..6ba653b3 100644 --- a/apps/desktop/src/features/commit/WorkingCopyPanel.tsx +++ b/apps/desktop/src/features/commit/WorkingCopyPanel.tsx @@ -72,6 +72,10 @@ function statusBadge(kind: string | null) { const COMMIT_HOOKS = ['pre-commit', 'commit-msg']; +function hookList(names: string[]): string { + return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : (names[0] ?? ''); +} + function submoduleDrift(file: FileStatus, staged: boolean): string | null { if (staged || !file.submodule) return null; return `Submodule checked out at ${file.submodule.checkedOut.slice(0, 7)}, this repository records ${file.submodule.recorded.slice(0, 7)}`; @@ -354,7 +358,10 @@ export function WorkingCopyPanel() { const statusVersion = useRepo((s) => s.statusVersion); const statusReady = status !== null; const repoHooks = useRepoHooks(path); - const commitHooks = useMemo(() => repoHooks.filter((name) => COMMIT_HOOKS.includes(name)), [repoHooks]); + const commitHooks = useMemo( + () => repoHooks.filter((name) => COMMIT_HOOKS.includes(name) || (amend && name === 'post-rewrite')), + [repoHooks, amend], + ); const skipHooks = useCommitWork((s) => !!s.skipHooks[path]); const setSkipHooks = (skip: boolean) => useCommitWork.getState().setSkipHooks(path, skip); const [indexPaths, setIndexPaths] = useState(null); @@ -1484,7 +1491,9 @@ export function WorkingCopyPanel() { Amend {commitHooks.length > 0 && ( - + - + open && repoHooks.refresh()}>