Skip to main content

hyprstream_core/git/
ops.rs

1//! Low-level git operations on &git2::Repository
2//!
3//! These are the shared implementations behind both RegistryService handlers
4//! and CheckpointManager. Each function takes &Repository and parameters,
5//! performing a single git operation.
6
7use anyhow::{anyhow, Result};
8use git2::Repository;
9use std::path::Path;
10
11use hyprstream_rpc_std::registry_client::{DetailedStatusInfo, FileChangeType, FileStatusInfo};
12
13// === Commit Operations ===
14
15/// Commit staged changes with default signature
16pub fn commit_index(repo: &Repository, message: &str) -> Result<git2::Oid> {
17    let mut index = repo.index()?;
18    let tree_id = index.write_tree()?;
19    let tree = repo.find_tree(tree_id)?;
20
21    let sig = repo
22        .signature()
23        .map_err(|e| anyhow!("Failed to create signature: {}", e))?;
24    let parent = repo.head()?.peel_to_commit()?;
25
26    let oid = repo.commit(Some("HEAD"), &sig, &sig, message, &tree, &[&parent])?;
27    Ok(oid)
28}
29
30/// Commit with explicit author
31pub fn commit_with_author(
32    repo: &Repository,
33    message: &str,
34    name: &str,
35    email: &str,
36) -> Result<git2::Oid> {
37    let mut index = repo.index()?;
38    let tree_id = index.write_tree()?;
39    let tree = repo.find_tree(tree_id)?;
40
41    let head = repo.head()?;
42    let parent_commit = head.peel_to_commit()?;
43
44    let author = git2::Signature::now(name, email)?;
45    let committer = git2::Signature::now(name, email)?;
46
47    let oid = repo.commit(
48        Some("HEAD"),
49        &author,
50        &committer,
51        message,
52        &tree,
53        &[&parent_commit],
54    )?;
55
56    Ok(oid)
57}
58
59/// Amend HEAD commit with staged changes
60pub fn amend_head(repo: &Repository, message: &str) -> Result<git2::Oid> {
61    let mut index = repo.index()?;
62    let tree_id = index.write_tree()?;
63    let tree = repo.find_tree(tree_id)?;
64
65    let head = repo.head()?;
66    let commit_to_amend = head.peel_to_commit()?;
67
68    let new_oid = commit_to_amend.amend(
69        Some("HEAD"),
70        None, // Keep author
71        None, // Keep committer
72        None, // Keep encoding
73        Some(message),
74        Some(&tree),
75    )?;
76
77    Ok(new_oid)
78}
79
80// === Staging Operations ===
81
82/// Stage all tracked modified files (git add -u)
83pub fn stage_all(repo: &Repository) -> Result<()> {
84    let mut index = repo.index()?;
85    index.update_all(["*"].iter(), None)?;
86    index.write()?;
87    Ok(())
88}
89
90/// Stage all files including untracked (git add -A)
91pub fn stage_all_with_untracked(repo: &Repository) -> Result<()> {
92    let mut index = repo.index()?;
93    index.add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)?;
94    index.write()?;
95    Ok(())
96}
97
98/// Stage specific files by relative path
99pub fn stage_files(repo: &Repository, files: &[&str]) -> Result<()> {
100    let mut index = repo.index()?;
101    for file in files {
102        index.add_path(Path::new(file))?;
103    }
104    index.write()?;
105    Ok(())
106}
107
108// === Tag Operations ===
109
110/// List all tags
111pub fn list_tags(repo: &Repository) -> Result<Vec<String>> {
112    let tags = repo.tag_names(None)?;
113    let result: Vec<String> = tags
114        .iter()
115        .filter_map(|t| t.map(std::borrow::ToOwned::to_owned))
116        .collect();
117    Ok(result)
118}
119
120/// Create lightweight tag
121///
122/// If `target` is None, tags HEAD. If `force` is true, overwrites existing tags.
123pub fn create_tag(repo: &Repository, name: &str, target: Option<&str>, force: bool) -> Result<()> {
124    let target_oid = if let Some(target_spec) = target {
125        repo.revparse_single(target_spec)?.id()
126    } else {
127        repo.head()?
128            .target()
129            .ok_or_else(|| anyhow!("HEAD has no target"))?
130    };
131
132    let commit = repo.find_commit(target_oid)?;
133    repo.tag_lightweight(name, commit.as_object(), force)?;
134
135    Ok(())
136}
137
138/// Delete a tag
139pub fn delete_tag(repo: &Repository, name: &str) -> Result<()> {
140    repo.tag_delete(name)
141        .map_err(|e| anyhow!("Failed to delete tag '{}': {}", name, e))?;
142    Ok(())
143}
144
145// === Status ===
146
147/// Detailed status with per-file change info, ahead/behind, merge state
148pub fn detailed_status(repo: &Repository) -> Result<DetailedStatusInfo> {
149    let repo_path = repo.workdir().unwrap_or_else(|| repo.path()).to_path_buf();
150
151    // Get branch name
152    let branch = repo
153        .head()
154        .ok()
155        .and_then(|h| h.shorthand().map(std::borrow::ToOwned::to_owned))
156        .unwrap_or_default();
157
158    // Get HEAD OID
159    let head_oid = repo
160        .head()
161        .ok()
162        .and_then(|h| h.target().map(|o| o.to_string()))
163        .unwrap_or_default();
164
165    // Check for merge/rebase in progress
166    let merge_in_progress = repo.find_reference("MERGE_HEAD").is_ok();
167    let rebase_in_progress = repo_path.join(".git/rebase-merge").exists()
168        || repo_path.join(".git/rebase-apply").exists();
169
170    // Get statuses
171    let statuses = repo.statuses(None)?;
172
173    let mut files = Vec::new();
174    for entry in statuses.iter() {
175        if let Some(path) = entry.path() {
176            let status = entry.status();
177
178            // Index status
179            let index_status = if status.contains(git2::Status::INDEX_NEW) {
180                FileChangeType::Added
181            } else if status.contains(git2::Status::INDEX_MODIFIED) {
182                FileChangeType::Modified
183            } else if status.contains(git2::Status::INDEX_DELETED) {
184                FileChangeType::Deleted
185            } else if status.contains(git2::Status::INDEX_RENAMED) {
186                FileChangeType::Renamed
187            } else if status.contains(git2::Status::INDEX_TYPECHANGE) {
188                FileChangeType::TypeChanged
189            } else {
190                FileChangeType::None
191            };
192
193            // Worktree status
194            let worktree_status = if status.contains(git2::Status::WT_NEW) {
195                FileChangeType::Untracked
196            } else if status.contains(git2::Status::WT_MODIFIED) {
197                FileChangeType::Modified
198            } else if status.contains(git2::Status::WT_DELETED) {
199                FileChangeType::Deleted
200            } else if status.contains(git2::Status::WT_RENAMED) {
201                FileChangeType::Renamed
202            } else if status.contains(git2::Status::WT_TYPECHANGE) {
203                FileChangeType::TypeChanged
204            } else if status.contains(git2::Status::CONFLICTED) {
205                FileChangeType::Conflicted
206            } else {
207                FileChangeType::None
208            };
209
210            files.push(FileStatusInfo {
211                path: path.to_owned(),
212                index_status,
213                worktree_status,
214            });
215        }
216    }
217
218    // Get ahead/behind (simplified - assume origin/{branch})
219    let (ahead, behind) = if let Ok(head_ref) = repo.head() {
220        if let Some(branch_name) = head_ref.shorthand() {
221            let upstream_name = format!("origin/{}", branch_name);
222            if let Ok(upstream) = repo.revparse_single(&upstream_name) {
223                if let (Ok(local), Ok(remote)) =
224                    (head_ref.peel_to_commit(), upstream.peel_to_commit())
225                {
226                    repo.graph_ahead_behind(local.id(), remote.id())
227                        .unwrap_or((0, 0))
228                } else {
229                    (0, 0)
230                }
231            } else {
232                (0, 0)
233            }
234        } else {
235            (0, 0)
236        }
237    } else {
238        (0, 0)
239    };
240
241    Ok(DetailedStatusInfo {
242        branch,
243        head_oid,
244        merge_in_progress,
245        rebase_in_progress,
246        files,
247        ahead: ahead as u32,
248        behind: behind as u32,
249    })
250}
251
252// === Merge Operations ===
253
254/// Merge a source branch into the current branch
255pub fn merge(repo: &Repository, source: &str, message: Option<&str>) -> Result<git2::Oid> {
256    let source_ref = repo.revparse_single(source)?;
257    let source_commit = source_ref.peel_to_commit()?;
258
259    let annotated = repo.find_annotated_commit(source_commit.id())?;
260    let (analysis, _) = repo.merge_analysis(&[&annotated])?;
261
262    if analysis.is_up_to_date() {
263        return Ok(source_commit.id());
264    }
265
266    if analysis.is_fast_forward() {
267        let refname = format!("refs/heads/{}", repo.head()?.shorthand().unwrap_or("HEAD"));
268        repo.reference(
269            &refname,
270            source_commit.id(),
271            true,
272            &format!("Fast-forward to {}", source),
273        )?;
274        repo.set_head(&refname)?;
275        repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
276        return Ok(source_commit.id());
277    }
278
279    // Normal merge
280    repo.merge(&[&annotated], None, None)?;
281
282    let mut index = repo.index()?;
283    if index.has_conflicts() {
284        return Err(anyhow!(
285            "Merge conflicts detected. Resolve and use continueMerge."
286        ));
287    }
288
289    let tree_id = index.write_tree()?;
290    let tree = repo.find_tree(tree_id)?;
291    let sig = repo.signature()?;
292    let head = repo.head()?.peel_to_commit()?;
293
294    let merge_msg = message.map(String::from).unwrap_or_else(|| {
295        format!(
296            "Merge '{}' into {}",
297            source,
298            head.summary().unwrap_or("HEAD")
299        )
300    });
301
302    let oid = repo.commit(
303        Some("HEAD"),
304        &sig,
305        &sig,
306        &merge_msg,
307        &tree,
308        &[&head, &source_commit],
309    )?;
310
311    repo.cleanup_state()?;
312    Ok(oid)
313}
314
315/// Abort merge: reset to ORIG_HEAD, cleanup state
316pub fn abort_merge(repo: &Repository) -> Result<()> {
317    let orig_head = repo
318        .refname_to_id("ORIG_HEAD")
319        .map_err(|_| anyhow!("No merge in progress (ORIG_HEAD not found)"))?;
320
321    let commit = repo.find_commit(orig_head)?;
322    repo.reset(commit.as_object(), git2::ResetType::Hard, None)?;
323    repo.cleanup_state()?;
324
325    Ok(())
326}
327
328/// Continue merge: check no conflicts, create merge commit, cleanup
329pub fn continue_merge(repo: &Repository, message: Option<&str>) -> Result<git2::Oid> {
330    let mut index = repo.index()?;
331
332    if index.has_conflicts() {
333        return Err(anyhow!(
334            "Conflicts still present. Resolve all conflicts before continuing."
335        ));
336    }
337
338    let tree_id = index.write_tree()?;
339    let tree = repo.find_tree(tree_id)?;
340    let sig = repo.signature()?;
341
342    let head = repo.head()?.peel_to_commit()?;
343    let merge_head = repo
344        .find_reference("MERGE_HEAD")
345        .map_err(|_| anyhow!("No merge in progress (MERGE_HEAD not found)"))?
346        .peel_to_commit()?;
347
348    let commit_message = message.map(String::from).unwrap_or_else(|| {
349        format!(
350            "Merge branch '{}'",
351            merge_head.summary().unwrap_or("unknown")
352        )
353    });
354
355    let oid = repo.commit(
356        Some("HEAD"),
357        &sig,
358        &sig,
359        &commit_message,
360        &tree,
361        &[&head, &merge_head],
362    )?;
363
364    repo.cleanup_state()?;
365
366    Ok(oid)
367}
368
369/// Quit merge: cleanup state only
370pub fn quit_merge(repo: &Repository) -> Result<()> {
371    repo.cleanup_state()?;
372    Ok(())
373}
374
375// === Remote Operations ===
376
377/// Fetch from remote with optional refspec
378pub fn fetch(repo: &Repository, remote_name: &str, refspec: Option<&str>) -> Result<()> {
379    let mut remote = repo
380        .find_remote(remote_name)
381        .map_err(|e| anyhow!("Failed to find remote '{}': {}", remote_name, e))?;
382
383    let refspecs: Vec<&str> = match refspec {
384        Some(r) => vec![r],
385        None => vec![],
386    };
387
388    remote
389        .fetch(&refspecs, None, None)
390        .map_err(|e| anyhow!("Failed to fetch from {}: {}", remote_name, e))?;
391
392    Ok(())
393}
394
395/// Push to remote
396pub fn push(repo: &Repository, remote_name: &str, refspec: &str, force: bool) -> Result<()> {
397    let mut remote = repo
398        .find_remote(remote_name)
399        .map_err(|e| anyhow!("Failed to find remote '{}': {}", remote_name, e))?;
400
401    let mut push_options = git2::PushOptions::new();
402
403    let push_refspec = if force {
404        format!("+{}", refspec)
405    } else {
406        refspec.to_owned()
407    };
408
409    remote
410        .push(&[&push_refspec], Some(&mut push_options))
411        .map_err(|e| anyhow!("Failed to push to {}: {}", remote_name, e))?;
412
413    Ok(())
414}
415
416// === Branch ===
417
418/// Ensure branch exists, creating from HEAD if needed; switch to it
419pub fn ensure_branch(repo: &Repository, name: &str) -> Result<()> {
420    let branch_ref = format!("refs/heads/{}", name);
421    if repo.find_reference(&branch_ref).is_ok() {
422        repo.set_head(&branch_ref)?;
423        repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
424    } else {
425        let head = repo.head()?.peel_to_commit()?;
426        repo.branch(name, &head, false)?;
427        repo.set_head(&branch_ref)?;
428    }
429    Ok(())
430}
431
432// === Utility ===
433
434// NOTE: `cow_copy` moved to `hyprstream-inference` (`worktree_ext`) with its only
435// caller, the training checkpoint path (Wave B decomposition).
436
437/// Sanitize a string for use as a Git tag name
438pub fn sanitize_tag_name(name: &str) -> String {
439    name.chars()
440        .map(|c| match c {
441            ' ' | '\t' | '\n' => '-',
442            '/' | '\\' | ':' | '?' | '*' | '"' | '<' | '>' | '|' | '[' | ']' => '_',
443            _ if c.is_control() => '_',
444            _ => c,
445        })
446        .collect::<String>()
447        .trim_matches(|c| c == '-' || c == '_' || c == '.')
448        .to_lowercase()
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454
455    #[test]
456    fn test_sanitize_tag_name() {
457        assert_eq!(sanitize_tag_name("checkpoint-v1"), "checkpoint-v1");
458        assert_eq!(sanitize_tag_name("My Adapter Name"), "my-adapter-name");
459        assert_eq!(sanitize_tag_name("test/branch:name"), "test_branch_name");
460        assert_eq!(sanitize_tag_name("  trim  "), "trim");
461        assert_eq!(sanitize_tag_name("Upper CASE"), "upper-case");
462    }
463}