features_cli/
git_helper.rs1use anyhow::{Context, Result};
2use git2::Repository;
3use std::collections::HashMap;
4use std::path::Path;
5
6use crate::models::Change;
7
8pub fn get_repository_url(repo_path: &Path) -> Option<String> {
11 let repo = Repository::discover(repo_path).ok()?;
12
13 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#[derive(Default)]
32pub struct CommitHistory {
33 pub changes_by_path: HashMap<String, Vec<Change>>,
35 pub affected_paths: HashMap<String, Vec<String>>,
37}
38
39pub 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 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 let affected_paths = get_affected_paths(&repo, &commit)?;
81
82 for file_path in &affected_paths {
85 let path_obj = Path::new(file_path);
86
87 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 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
110fn get_affected_paths(repo: &Repository, commit: &git2::Commit) -> Result<Vec<String>> {
112 let mut paths = Vec::new();
113
114 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 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
150fn 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}