thoughts_tool/git/
utils.rs1use crate::error::ThoughtsError;
2use anyhow::Result;
3use git2::Repository;
4use std::path::{Path, PathBuf};
5use tracing::debug;
6
7pub fn get_current_repo() -> Result<PathBuf> {
9 let current_dir = std::env::current_dir()?;
10 find_repo_root(¤t_dir)
11}
12
13pub 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
24pub fn is_worktree(repo_path: &Path) -> Result<bool> {
26 let _repo = Repository::open(repo_path)?;
27
28 let git_path = repo_path.join(".git");
30 if git_path.is_file() {
31 debug!("Found .git file, this is a worktree");
33 return Ok(true);
34 }
35
36 Ok(false)
37}
38
39pub fn get_main_repo_for_worktree(worktree_path: &Path) -> Result<PathBuf> {
41 let _repo = Repository::open(worktree_path)?;
42
43 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 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 Ok(worktree_path.to_path_buf())
66}
67
68pub fn is_git_repo(path: &Path) -> bool {
70 Repository::open(path).is_ok()
71}
72
73#[allow(dead_code)]
75pub fn init_repo(path: &Path) -> Result<Repository> {
77 Ok(Repository::init(path)?)
78}
79
80pub 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}