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//! - `runtime/hooks` - Git hooks installation and removal (boundary module)
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//! - `runtime/wrapper` - Agent phase git wrapper for safe concurrent execution (boundary module)
17//! - [`branch`] - Branch detection and default branch resolution
18//! - `rebase` - Rebase operations with fault tolerance
19
20#![deny(unsafe_code)]
21
22/// Convert git2 errors to `std::io` errors for consistent error handling.
23#[cfg(any(test, feature = "test-utils"))]
24#[must_use]
25pub fn git2_to_io_error(err: &git2::Error) -> std::io::Error {
26    git2_to_io_error_impl(err)
27}
28
29#[cfg(not(any(test, feature = "test-utils")))]
30pub(crate) fn git2_to_io_error(err: &git2::Error) -> std::io::Error {
31    git2_to_io_error_impl(err)
32}
33
34fn git2_to_io_error_impl(err: &git2::Error) -> std::io::Error {
35    // Fall back to mapping git2 error codes to a best-effort io::ErrorKind.
36    let kind = match err.code() {
37        git2::ErrorCode::NotFound | git2::ErrorCode::UnbornBranch => std::io::ErrorKind::NotFound,
38        git2::ErrorCode::Exists => std::io::ErrorKind::AlreadyExists,
39        git2::ErrorCode::Auth | git2::ErrorCode::Certificate => {
40            std::io::ErrorKind::PermissionDenied
41        }
42        git2::ErrorCode::Invalid => std::io::ErrorKind::InvalidInput,
43        git2::ErrorCode::Eof => std::io::ErrorKind::UnexpectedEof,
44        _ => std::io::ErrorKind::Other,
45    };
46
47    std::io::Error::new(kind, err.to_string())
48}
49
50pub mod branch;
51pub mod cleanup;
52pub mod config_state;
53pub(crate) mod domain;
54pub mod hooks;
55pub mod hooks_dir;
56pub mod identity;
57pub mod install;
58pub mod lock;
59pub mod marker;
60pub mod path_wrapper;
61pub mod phase;
62/// Runtime module containing OS-boundary code (std::fs, std::process, std::env, Mutex).
63/// This module is exempt from functional Rust dylint rules.
64pub mod phase_state;
65pub mod rebase;
66mod repo;
67mod review_baseline;
68pub mod runtime;
69pub mod runtime_identity;
70pub mod script;
71mod start_commit;
72pub mod uninstall;
73pub mod verify;
74pub mod worktree;
75pub mod wrapper;
76
77#[cfg(any(test, feature = "test-utils"))]
78pub mod rebase_checkpoint;
79
80#[cfg(any(test, feature = "test-utils"))]
81pub mod rebase_state_machine;
82
83/// # Errors
84///
85/// Returns an error if the git repository cannot be found or hooks directory cannot be determined.
86pub fn get_hooks_dir() -> std::io::Result<std::path::PathBuf> {
87    repo::get_hooks_dir_from(std::path::Path::new("."))
88}
89
90pub(crate) fn get_hooks_dir_in_repo(
91    repo_root: &std::path::Path,
92) -> std::io::Result<std::path::PathBuf> {
93    repo::get_hooks_dir_from(repo_root)
94}
95
96#[cfg(any(test, feature = "test-utils"))]
97pub use branch::get_default_branch_at;
98pub use branch::{get_default_branch, is_main_or_master_branch};
99#[cfg(any(test, feature = "test-utils"))]
100pub use hooks::{file_contains_marker_with_workspace, verify_hook_integrity_with_workspace};
101pub use hooks::{
102    install_hooks_in_repo, reinstall_hooks_if_tampered, uninstall_hooks, uninstall_hooks_in_repo,
103    uninstall_hooks_silent_in_hooks_dir, verify_hooks_removed,
104};
105pub use hooks::{HOOK_MARKER, RALPH_HOOK_NAMES};
106pub use rebase::{
107    abort_rebase, continue_rebase, get_conflict_markers_for_file, get_conflicted_files,
108    rebase_in_progress, rebase_onto, RebaseResult,
109};
110
111// Types that are part of the public API but not used in binary
112#[cfg(any(test, feature = "test-utils"))]
113pub use rebase::{CleanupResult, ConcurrentOperation};
114
115#[cfg(any(test, feature = "test-utils"))]
116pub use rebase::{
117    attempt_automatic_recovery, cleanup_stale_rebase_state, detect_concurrent_git_operations,
118    is_dirty_tree_cli, rebase_in_progress_cli, validate_rebase_preconditions,
119    verify_rebase_completed,
120};
121
122pub use rebase::RebaseErrorKind;
123
124#[cfg(any(test, feature = "test-utils"))]
125pub use rebase_checkpoint::RebasePhase;
126
127#[cfg(any(test, feature = "test-utils"))]
128pub use rebase_state_machine::{RebaseLock, RebaseStateMachine};
129pub use repo::{
130    ensure_local_excludes, get_git_diff_for_review_with_workspace, get_git_diff_from_start,
131    get_git_diff_from_start_with_workspace, get_repo_root, git_add_all, git_add_all_in_repo,
132    git_add_specific_in_repo, git_commit, git_commit_in_repo, git_diff, git_diff_from,
133    git_diff_in_repo, git_snapshot, git_snapshot_in_repo, parse_git_status_paths, require_git_repo,
134    resolve_protection_scope, resolve_protection_scope_from, CommitResultFallback,
135    DiffReviewContent, DiffTruncationLevel, ProtectionScope,
136};
137
138#[cfg(any(test, feature = "test-utils"))]
139pub use review_baseline::load_review_baseline_with_workspace;
140pub use review_baseline::update_review_baseline_with_workspace;
141pub use review_baseline::{
142    get_baseline_summary, get_review_baseline_info, load_review_baseline, update_review_baseline,
143    ReviewBaseline,
144};
145#[cfg(any(test, feature = "test-utils"))]
146pub use start_commit::load_start_point_with_workspace;
147pub use start_commit::{
148    get_current_head_oid, get_current_head_oid_at, get_start_commit_summary, git_oid_to_git2_oid,
149    load_start_point, reset_start_commit, save_start_commit, save_start_commit_with_workspace,
150    StartPoint,
151};
152pub use wrapper::{
153    capture_head_oid, cleanup_agent_phase_protections_silent_at, cleanup_agent_phase_silent,
154    cleanup_agent_phase_silent_at, cleanup_orphaned_marker, cleanup_orphaned_wrapper_at,
155    clear_agent_phase_global_state, detect_unauthorized_commit, disable_git_wrapper,
156    end_agent_phase, end_agent_phase_in_repo, ensure_agent_phase_protections, start_agent_phase,
157    start_agent_phase_in_repo, try_remove_ralph_dir, verify_ralph_dir_removed,
158    verify_wrapper_cleaned, GitHelpers, ProtectionCheckResult,
159};
160
161// Workspace-aware variants (used by tests and by code paths that must operate
162// without requiring a real git repository).
163pub use wrapper::{
164    cleanup_orphaned_marker_with_workspace, create_marker_with_workspace,
165    marker_exists_with_workspace, remove_marker_with_workspace,
166};
167
168#[cfg(any(test, feature = "test-utils"))]
169pub use runtime::agent_phase_test_lock;
170#[cfg(any(test, feature = "test-utils"))]
171pub use wrapper::{get_agent_phase_paths_for_test, set_agent_phase_paths_for_test};
172
173// Re-export checkpoint and recovery action for tests only
174#[cfg(any(test, feature = "test-utils"))]
175pub use rebase_checkpoint::RebaseCheckpoint;
176
177#[cfg(any(test, feature = "test-utils"))]
178pub use rebase_state_machine::RecoveryAction;
179
180// Re-export rebase lock functions for tests only
181#[cfg(any(test, feature = "test-utils"))]
182pub use lock::{acquire_rebase_lock, release_rebase_lock};
183
184#[cfg(test)]
185mod tests;