Skip to main content

ralph_workflow/git_helpers/
mod.rs

1//! Git Helper Functions
2//!
3//! Provides git hooks management, a git wrapper for blocking commits during the
4//! agent phase, and basic repository utilities.
5//!
6//! Core git operations use libgit2 directly. Agent-phase defense-in-depth may also
7//! install a temporary PATH wrapper that intercepts the git CLI when available.
8//!
9//! # Module Structure
10//!
11//! - `hooks` - Git hooks installation and removal
12//! - [`identity`] - Git identity resolution with comprehensive fallback chain
13//! - `repo` - Basic git repository operations (add, commit, snapshot)
14//! - `start_commit` - Starting commit tracking for incremental diffs
15//! - `review_baseline` - Per-review-cycle baseline tracking
16//! - `wrapper` - Agent phase git wrapper for safe concurrent execution
17//! - [`branch`] - Branch detection and default branch resolution
18//! - `rebase` - Rebase operations with fault tolerance
19
20#![deny(unsafe_code)]
21
22use std::io;
23
24/// Convert git2 errors to `std::io` errors for consistent error handling.
25#[cfg(any(test, feature = "test-utils"))]
26#[must_use]
27pub fn git2_to_io_error(err: &git2::Error) -> io::Error {
28    git2_to_io_error_impl(err)
29}
30
31#[cfg(not(any(test, feature = "test-utils")))]
32pub(crate) fn git2_to_io_error(err: &git2::Error) -> io::Error {
33    git2_to_io_error_impl(err)
34}
35
36fn git2_to_io_error_impl(err: &git2::Error) -> io::Error {
37    // Fall back to mapping git2 error codes to a best-effort io::ErrorKind.
38    let kind = match err.code() {
39        git2::ErrorCode::NotFound | git2::ErrorCode::UnbornBranch => io::ErrorKind::NotFound,
40        git2::ErrorCode::Exists => io::ErrorKind::AlreadyExists,
41        git2::ErrorCode::Auth | git2::ErrorCode::Certificate => io::ErrorKind::PermissionDenied,
42        git2::ErrorCode::Invalid => io::ErrorKind::InvalidInput,
43        git2::ErrorCode::Eof => io::ErrorKind::UnexpectedEof,
44        _ => io::ErrorKind::Other,
45    };
46
47    io::Error::new(kind, err.to_string())
48}
49
50pub mod branch;
51#[cfg(any(test, feature = "test-utils"))]
52pub mod hooks;
53#[cfg(not(any(test, feature = "test-utils")))]
54mod hooks;
55pub mod identity;
56mod rebase;
57
58#[cfg(any(test, feature = "test-utils"))]
59pub mod rebase_checkpoint;
60
61#[cfg(any(test, feature = "test-utils"))]
62pub mod rebase_state_machine;
63
64mod repo;
65
66/// # Errors
67///
68/// Returns an error if the git repository cannot be found or hooks directory cannot be determined.
69pub fn get_hooks_dir() -> io::Result<std::path::PathBuf> {
70    repo::get_hooks_dir_from(std::path::Path::new("."))
71}
72
73pub(crate) fn get_hooks_dir_in_repo(repo_root: &std::path::Path) -> io::Result<std::path::PathBuf> {
74    repo::get_hooks_dir_from(repo_root)
75}
76mod review_baseline;
77mod start_commit;
78mod wrapper;
79
80#[cfg(any(test, feature = "test-utils"))]
81pub use branch::get_default_branch_at;
82pub use branch::{get_default_branch, is_main_or_master_branch};
83#[cfg(any(test, feature = "test-utils"))]
84pub use hooks::{file_contains_marker_with_workspace, verify_hook_integrity_with_workspace};
85pub use hooks::{
86    install_hooks_in_repo, reinstall_hooks_if_tampered, uninstall_hooks, uninstall_hooks_in_repo,
87    uninstall_hooks_silent_in_hooks_dir, verify_hooks_removed,
88};
89pub use hooks::{HOOK_MARKER, RALPH_HOOK_NAMES};
90pub use rebase::{
91    abort_rebase, continue_rebase, get_conflict_markers_for_file, get_conflicted_files,
92    rebase_in_progress, rebase_onto, RebaseResult,
93};
94
95// Types that are part of the public API but not used in binary
96#[cfg(any(test, feature = "test-utils"))]
97pub use rebase::{CleanupResult, ConcurrentOperation};
98
99#[cfg(any(test, feature = "test-utils"))]
100pub use rebase::{
101    attempt_automatic_recovery, cleanup_stale_rebase_state, detect_concurrent_git_operations,
102    is_dirty_tree_cli, rebase_in_progress_cli, validate_rebase_preconditions,
103    verify_rebase_completed,
104};
105
106pub use rebase::RebaseErrorKind;
107
108#[cfg(any(test, feature = "test-utils"))]
109pub use rebase_checkpoint::RebasePhase;
110
111#[cfg(any(test, feature = "test-utils"))]
112pub use rebase_state_machine::{RebaseLock, RebaseStateMachine};
113pub use repo::{
114    ensure_local_excludes, get_git_diff_for_review_with_workspace, get_git_diff_from_start,
115    get_git_diff_from_start_with_workspace, get_repo_root, git_add_all, git_add_all_in_repo,
116    git_add_specific_in_repo, git_commit, git_commit_in_repo, git_diff, git_diff_from,
117    git_diff_in_repo, git_snapshot, git_snapshot_in_repo, parse_git_status_paths, require_git_repo,
118    resolve_protection_scope, resolve_protection_scope_from, CommitResultFallback,
119    DiffReviewContent, DiffTruncationLevel, ProtectionScope,
120};
121
122#[cfg(any(test, feature = "test-utils"))]
123pub use review_baseline::load_review_baseline_with_workspace;
124pub use review_baseline::update_review_baseline_with_workspace;
125pub use review_baseline::{
126    get_baseline_summary, get_review_baseline_info, load_review_baseline, update_review_baseline,
127    ReviewBaseline,
128};
129#[cfg(any(test, feature = "test-utils"))]
130pub use start_commit::load_start_point_with_workspace;
131pub use start_commit::{
132    get_current_head_oid, get_current_head_oid_at, get_start_commit_summary, load_start_point,
133    reset_start_commit, save_start_commit, save_start_commit_with_workspace, StartPoint,
134};
135pub use wrapper::{
136    capture_head_oid, cleanup_agent_phase_protections_silent_at, cleanup_agent_phase_silent,
137    cleanup_agent_phase_silent_at, cleanup_orphaned_marker, cleanup_orphaned_wrapper_at,
138    clear_agent_phase_global_state, detect_unauthorized_commit, disable_git_wrapper,
139    end_agent_phase, end_agent_phase_in_repo, ensure_agent_phase_protections, start_agent_phase,
140    start_agent_phase_in_repo, try_remove_ralph_dir, verify_ralph_dir_removed,
141    verify_wrapper_cleaned, GitHelpers, ProtectionCheckResult,
142};
143
144// Workspace-aware variants (used by tests and by code paths that must operate
145// without requiring a real git repository).
146pub use wrapper::{
147    cleanup_orphaned_marker_with_workspace, create_marker_with_workspace,
148    marker_exists_with_workspace, remove_marker_with_workspace,
149};
150
151#[cfg(any(test, feature = "test-utils"))]
152pub use wrapper::{
153    agent_phase_test_lock, get_agent_phase_paths_for_test, set_agent_phase_paths_for_test,
154};
155
156// Re-export checkpoint and recovery action for tests only
157#[cfg(any(test, feature = "test-utils"))]
158pub use rebase_checkpoint::RebaseCheckpoint;
159
160#[cfg(any(test, feature = "test-utils"))]
161pub use rebase_state_machine::RecoveryAction;
162
163#[cfg(test)]
164mod tests;