Skip to main content

features_cli/
git_helper.rs

1use anyhow::{Context, Result};
2use git2::Repository;
3use std::collections::HashMap;
4use std::path::Path;
5
6use crate::models::Change;
7
8/// Get the repository URL from git config.
9/// Tries to get the remote origin URL, returns None if not found.
10pub fn get_repository_url(repo_path: &Path) -> Option<String> {
11    let repo = Repository::discover(repo_path).ok()?;
12
13    // Try to get the remote origin URL
14    if let Ok(remote) = repo.find_remote("origin")
15        && let Some(url) = remote.url()
16    {
17        return Some(url.to_string());
18    }
19
20    None
21}
22
23fn format_timestamp(time: git2::Time) -> String {
24    let timestamp = time.seconds();
25    let datetime = chrono::DateTime::from_timestamp(timestamp, 0)
26        .unwrap_or_else(|| chrono::DateTime::from_timestamp(0, 0).unwrap());
27    datetime.format("%Y-%m-%d %H:%M:%S").to_string()
28}
29
30/// The commit history of a repository, indexed for lookups by path and by commit.
31#[derive(Default)]
32pub struct CommitHistory {
33    /// Changes for each repo-relative directory, in the order they were walked
34    pub changes_by_path: HashMap<String, Vec<Change>>,
35    /// Paths affected by each commit, by commit hash
36    pub affected_paths: HashMap<String, Vec<String>>,
37}
38
39/// Get all commits for all paths in the repository at once.
40/// This is much more efficient than calling get_commits_for_path for each path individually.
41pub fn get_all_commits_by_path(repo_path: &Path) -> Result<CommitHistory> {
42    let repo = Repository::discover(repo_path).with_context(|| {
43        format!(
44            "failed to discover git repository at `{}`",
45            repo_path.display()
46        )
47    })?;
48
49    let mut revwalk = repo.revwalk()?;
50    revwalk.push_head()?;
51    revwalk.set_sorting(git2::Sort::TIME)?;
52
53    let mut history = CommitHistory::default();
54
55    for oid in revwalk {
56        let oid = oid?;
57        let commit = repo.find_commit(oid)?;
58        let author = commit.author();
59        let message = commit.message().unwrap_or("").to_string();
60
61        // Split message into title and description
62        let lines: Vec<&str> = message.lines().collect();
63        let title = lines.first().unwrap_or(&"").to_string();
64        let description = if lines.len() > 1 {
65            lines[1..].join("\n").trim().to_string()
66        } else {
67            String::new()
68        };
69
70        let change = Change {
71            title,
72            author_name: author.name().unwrap_or("").to_string(),
73            author_email: author.email().unwrap_or("").to_string(),
74            description,
75            date: format_timestamp(commit.time()),
76            hash: format!("{}", oid),
77        };
78
79        // Get all paths affected by this commit
80        let affected_paths = get_affected_paths(&repo, &commit)?;
81
82        // For each affected file path, add the change to all ancestor directories
83        // This matches the behavior of commit_affects_path which uses starts_with
84        for file_path in &affected_paths {
85            let path_obj = Path::new(file_path);
86
87            // Add to all ancestor directories (not the file itself, only dirs)
88            for ancestor in path_obj.ancestors().skip(1) {
89                if ancestor == Path::new("") {
90                    break;
91                }
92                let ancestor_str = ancestor.to_string_lossy().to_string();
93
94                // Commits arrive one at a time, so this commit can only be the last
95                // entry. If it's there, all higher ancestors already have it as well.
96                let changes_list = history.changes_by_path.entry(ancestor_str).or_default();
97                if changes_list.last().is_some_and(|c| c.hash == change.hash) {
98                    break;
99                }
100                changes_list.push(change.clone());
101            }
102        }
103
104        history.affected_paths.insert(change.hash, affected_paths);
105    }
106
107    Ok(history)
108}
109
110/// Get all paths affected by a commit
111fn get_affected_paths(repo: &Repository, commit: &git2::Commit) -> Result<Vec<String>> {
112    let mut paths = Vec::new();
113
114    // For the first commit (no parents), get all files in the tree
115    if commit.parent_count() == 0 {
116        let tree = commit.tree()?;
117        collect_tree_paths(repo, &tree, "", &mut paths)?;
118        return Ok(paths);
119    }
120
121    // For commits with parents, check the diff
122    let tree = commit.tree()?;
123    let parent = commit.parent(0)?;
124    let parent_tree = parent.tree()?;
125
126    let diff = repo.diff_tree_to_tree(Some(&parent_tree), Some(&tree), None)?;
127
128    diff.foreach(
129        &mut |delta, _| {
130            let new_path = delta.new_file().path().and_then(|p| p.to_str());
131            if let Some(path_str) = new_path {
132                paths.push(path_str.to_string());
133            }
134            if let Some(path_str) = delta.old_file().path().and_then(|p| p.to_str())
135                && new_path != Some(path_str)
136                && !paths.iter().any(|p| p == path_str)
137            {
138                paths.push(path_str.to_string());
139            }
140            true
141        },
142        None,
143        None,
144        None,
145    )?;
146
147    Ok(paths)
148}
149
150/// Recursively collect all paths in a tree
151fn collect_tree_paths(
152    repo: &Repository,
153    tree: &git2::Tree,
154    prefix: &str,
155    paths: &mut Vec<String>,
156) -> Result<()> {
157    for entry in tree.iter() {
158        if let Some(name) = entry.name() {
159            let path = if prefix.is_empty() {
160                name.to_string()
161            } else {
162                format!("{}/{}", prefix, name)
163            };
164
165            paths.push(path.clone());
166
167            if entry.kind() == Some(git2::ObjectType::Tree)
168                && let Ok(subtree) = entry.to_object(repo).and_then(|obj| obj.peel_to_tree())
169            {
170                collect_tree_paths(repo, &subtree, &path, paths)?;
171            }
172        }
173    }
174    Ok(())
175}