thoughts_tool/git/
utils.rs

1use crate::error::ThoughtsError;
2use anyhow::Result;
3use git2::Repository;
4use std::path::{Path, PathBuf};
5use tracing::debug;
6
7/// Get the current repository path, starting from current directory
8pub fn get_current_repo() -> Result<PathBuf> {
9    let current_dir = std::env::current_dir()?;
10    find_repo_root(&current_dir)
11}
12
13/// Find the repository root from a given path
14pub fn find_repo_root(start_path: &Path) -> Result<PathBuf> {
15    let repo = Repository::discover(start_path).map_err(|_| ThoughtsError::NotInGitRepo)?;
16
17    let workdir = repo
18        .workdir()
19        .ok_or_else(|| anyhow::anyhow!("Repository has no working directory"))?;
20
21    Ok(workdir.to_path_buf())
22}
23
24/// Check if a directory is a git worktree
25pub fn is_worktree(repo_path: &Path) -> Result<bool> {
26    let _repo = Repository::open(repo_path)?;
27
28    // Check if this is a linked worktree by examining the .git file
29    let git_path = repo_path.join(".git");
30    if git_path.is_file() {
31        // If .git is a file, it's a worktree
32        debug!("Found .git file, this is a worktree");
33        return Ok(true);
34    }
35
36    Ok(false)
37}
38
39/// Get the main repository path for a worktree
40pub fn get_main_repo_for_worktree(worktree_path: &Path) -> Result<PathBuf> {
41    let _repo = Repository::open(worktree_path)?;
42
43    // For a worktree, we need to find the main repository
44    // The .git file in a worktree contains: "gitdir: /path/to/main/.git/worktrees/name"
45    let git_file = worktree_path.join(".git");
46    if git_file.is_file() {
47        let contents = std::fs::read_to_string(&git_file)?;
48        if let Some(gitdir_line) = contents.lines().find(|l| l.starts_with("gitdir:")) {
49            let gitdir = gitdir_line.trim_start_matches("gitdir:").trim();
50            let gitdir_path = PathBuf::from(gitdir);
51
52            // Navigate from .git/worktrees/name to the main repo
53            if let Some(parent) = gitdir_path.parent()
54                && let Some(parent_parent) = parent.parent()
55                && parent_parent.ends_with(".git")
56                && let Some(main_repo) = parent_parent.parent()
57            {
58                debug!("Found main repo at: {:?}", main_repo);
59                return Ok(main_repo.to_path_buf());
60            }
61        }
62    }
63
64    // If we can't determine it from the .git file, fall back to the current repo
65    Ok(worktree_path.to_path_buf())
66}
67
68/// Check if a path is a git repository
69pub fn is_git_repo(path: &Path) -> bool {
70    Repository::open(path).is_ok()
71}
72
73/// Initialize a new git repository
74#[allow(dead_code)]
75// TODO(2): Plan initialization architecture for consumer vs source repos
76pub fn init_repo(path: &Path) -> Result<Repository> {
77    Ok(Repository::init(path)?)
78}
79
80/// Get the remote URL for a git repository
81pub fn get_remote_url(repo_path: &Path) -> Result<String> {
82    let repo = Repository::open(repo_path)
83        .map_err(|e| anyhow::anyhow!("Failed to open git repository at {:?}: {}", repo_path, e))?;
84
85    let remote = repo
86        .find_remote("origin")
87        .map_err(|_| anyhow::anyhow!("No 'origin' remote found"))?;
88
89    remote
90        .url()
91        .ok_or_else(|| anyhow::anyhow!("Remote 'origin' has no URL"))
92        .map(|s| s.to_string())
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    use tempfile::TempDir;
99
100    #[test]
101    fn test_is_git_repo() {
102        let temp_dir = TempDir::new().unwrap();
103        let repo_path = temp_dir.path();
104
105        assert!(!is_git_repo(repo_path));
106
107        Repository::init(repo_path).unwrap();
108        assert!(is_git_repo(repo_path));
109    }
110}