1use std::collections::HashSet;
6use std::path::Path;
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9use git2::{Commit, ObjectType, Oid, Sort, Tree, TreeWalkMode, TreeWalkResult};
10
11use crate::error::CoreError;
12use crate::secrets::scanner::{ALLOWLIST_FILE, Allowlist, LeakFinding, scan_text};
13use crate::store::trailers::{Scope, Trailers, message_summary};
14use crate::store::{CommitId, Store, git_error, utc_datetime};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct HistoryFinding {
19 pub commit: CommitId,
21 pub finding: LeakFinding,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct LogEntry {
27 pub id: CommitId,
28 pub time: SystemTime,
30 pub author_name: String,
31 pub author_email: String,
32 pub summary: String,
34 pub trailers: Trailers,
35}
36
37impl LogEntry {
38 pub fn time_rfc3339(&self) -> String {
40 utc_datetime(self.time).to_string()
41 }
42}
43
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct LogFilter {
47 pub entity: Option<String>,
50 pub scope: Option<Scope>,
52 pub limit: Option<usize>,
54 pub before: Option<CommitId>,
58}
59
60pub fn entity_paths(entity: &str) -> Vec<String> {
63 match entity.split_once('/') {
64 Some(("server", id)) => vec![format!("servers/{id}.toml")],
65 Some(("skill", id)) => vec![format!("skills/{id}"), format!("skill-meta/{id}.toml")],
66 Some(("project", id)) => vec![format!("projects/{id}")],
67 Some(("machine", id)) => vec![
68 format!("machines/{id}.toml"),
69 format!("machines/{id}.applied.toml"),
70 ],
71 None if matches!(entity, "secrets" | "clients" | "settings" | "sources") => {
72 vec![format!("{entity}.toml")]
73 }
74 _ => Vec::new(),
75 }
76 .into_iter()
77 .filter(|path| !path.split('/').any(|part| part.is_empty() || part == ".."))
78 .collect()
79}
80
81impl Store<'_> {
82 pub fn commit_count(&self) -> Result<usize, CoreError> {
84 let mut walk = self.repo.revwalk().map_err(git_error)?;
85 walk.push_head().map_err(git_error)?;
86 let mut count = 0;
87 for oid in walk {
88 oid.map_err(git_error)?;
89 count += 1;
90 }
91 Ok(count)
92 }
93
94 pub fn log(&self, filter: &LogFilter) -> Result<Vec<LogEntry>, CoreError> {
96 let mut walk = self.repo.revwalk().map_err(git_error)?;
97 walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
98 .map_err(git_error)?;
99 walk.push_head().map_err(git_error)?;
100 let paths = filter
101 .entity
102 .as_deref()
103 .map(entity_paths)
104 .unwrap_or_default();
105
106 let mut entries = Vec::new();
107 let mut past_cursor = filter.before.is_none();
108 for oid in walk {
109 if filter.limit.is_some_and(|limit| entries.len() >= limit) {
110 break;
111 }
112 let oid = oid.map_err(git_error)?;
113 if !past_cursor {
114 past_cursor = filter.before.as_ref() == Some(&CommitId::from_oid(oid));
116 continue;
117 }
118 let commit = self.repo.find_commit(oid).map_err(git_error)?;
119 let message = String::from_utf8_lossy(commit.message_bytes());
120 let trailers = Trailers::parse(&message);
121 if filter
122 .scope
123 .as_ref()
124 .is_some_and(|scope| trailers.scope.as_ref() != Some(scope))
125 {
126 continue;
127 }
128 if let Some(entity) = &filter.entity
129 && !trailers.entities.contains(entity)
130 && !touches(&commit, &paths)?
131 {
132 continue;
133 }
134 entries.push(log_entry(&commit, trailers));
135 }
136 Ok(entries)
137 }
138
139 pub fn entry(&self, id: &CommitId) -> Result<(LogEntry, String), CoreError> {
141 let oid = Oid::from_str(id.as_str()).map_err(git_error)?;
142 let commit = self.repo.find_commit(oid).map_err(git_error)?;
143 let message = String::from_utf8_lossy(commit.message_bytes()).into_owned();
144 let trailers = Trailers::parse(&message);
145 Ok((log_entry(&commit, trailers), message))
146 }
147
148 pub fn scan_history(&self) -> Result<Vec<HistoryFinding>, CoreError> {
154 let allow = Allowlist::parse(&self.read_to_string(ALLOWLIST_FILE)?.unwrap_or_default());
155 let mut walk = self.repo.revwalk().map_err(git_error)?;
156 walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
157 .map_err(git_error)?;
158 walk.push_head().map_err(git_error)?;
159 let mut seen = HashSet::new();
160 let mut findings = Vec::new();
161 for oid in walk {
162 let commit = self
163 .repo
164 .find_commit(oid.map_err(git_error)?)
165 .map_err(git_error)?;
166 let id = CommitId::from_oid(commit.id());
167 let mut found = scan_text(
168 "commit message",
169 commit.message_bytes(),
170 false,
171 &self.secrets,
172 &allow,
173 );
174 let mut blobs = Vec::new();
175 commit
176 .tree()
177 .map_err(git_error)?
178 .walk(TreeWalkMode::PreOrder, |root, entry| {
179 if entry.kind() == Some(ObjectType::Blob) && seen.insert(entry.id()) {
180 let name = String::from_utf8_lossy(entry.name_bytes());
181 blobs.push((format!("{root}{name}"), entry.id()));
182 }
183 TreeWalkResult::Ok
184 })
185 .map_err(git_error)?;
186 for (path, blob) in blobs {
187 let blob = self.repo.find_blob(blob).map_err(git_error)?;
188 found.extend(scan_text(
189 &path,
190 blob.content(),
191 path.ends_with(".toml"),
192 &self.secrets,
193 &allow,
194 ));
195 }
196 findings.extend(found.into_iter().map(|finding| HistoryFinding {
197 commit: id.clone(),
198 finding,
199 }));
200 }
201 Ok(findings)
202 }
203}
204
205pub(crate) fn touches(commit: &Commit<'_>, paths: &[String]) -> Result<bool, CoreError> {
207 if paths.is_empty() {
208 return Ok(false);
209 }
210 let tree = commit.tree().map_err(git_error)?;
211 let parent_tree = match commit.parent(0) {
212 Ok(parent) => Some(parent.tree().map_err(git_error)?),
213 Err(_) => None,
214 };
215 Ok(paths
216 .iter()
217 .any(|path| entry_id(Some(&tree), path) != entry_id(parent_tree.as_ref(), path)))
218}
219
220fn entry_id(tree: Option<&Tree<'_>>, path: &str) -> Option<Oid> {
221 tree?.get_path(Path::new(path)).ok().map(|entry| entry.id())
222}
223
224pub(crate) fn commit_time(commit: &Commit<'_>) -> SystemTime {
225 let seconds = commit.time().seconds();
226 match u64::try_from(seconds) {
227 Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds),
228 Err(_) => UNIX_EPOCH,
229 }
230}
231
232fn log_entry(commit: &Commit<'_>, trailers: Trailers) -> LogEntry {
233 let message = String::from_utf8_lossy(commit.message_bytes());
234 let author = commit.author();
235 LogEntry {
236 id: CommitId::from_oid(commit.id()),
237 time: commit_time(commit),
238 author_name: String::from_utf8_lossy(author.name_bytes()).into_owned(),
239 author_email: String::from_utf8_lossy(author.email_bytes()).into_owned(),
240 summary: message_summary(&message).to_owned(),
241 trailers,
242 }
243}