use std::collections::HashSet;
use std::path::Path;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use git2::{Commit, ObjectType, Oid, Sort, Tree, TreeWalkMode, TreeWalkResult};
use crate::error::CoreError;
use crate::secrets::scanner::{ALLOWLIST_FILE, Allowlist, LeakFinding, scan_text};
use crate::store::trailers::{Scope, Trailers, message_summary};
use crate::store::{CommitId, Store, git_error, utc_datetime};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryFinding {
pub commit: CommitId,
pub finding: LeakFinding,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogEntry {
pub id: CommitId,
pub time: SystemTime,
pub author_name: String,
pub author_email: String,
pub summary: String,
pub trailers: Trailers,
}
impl LogEntry {
pub fn time_rfc3339(&self) -> String {
utc_datetime(self.time).to_string()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LogFilter {
pub entity: Option<String>,
pub scope: Option<Scope>,
pub limit: Option<usize>,
pub before: Option<CommitId>,
}
pub fn entity_paths(entity: &str) -> Vec<String> {
match entity.split_once('/') {
Some(("server", id)) => vec![format!("servers/{id}.toml")],
Some(("skill", id)) => vec![format!("skills/{id}"), format!("skill-meta/{id}.toml")],
Some(("project", id)) => vec![format!("projects/{id}")],
Some(("machine", id)) => vec![
format!("machines/{id}.toml"),
format!("machines/{id}.applied.toml"),
],
None if matches!(entity, "secrets" | "clients" | "settings" | "sources") => {
vec![format!("{entity}.toml")]
}
_ => Vec::new(),
}
.into_iter()
.filter(|path| !path.split('/').any(|part| part.is_empty() || part == ".."))
.collect()
}
impl Store<'_> {
pub fn commit_count(&self) -> Result<usize, CoreError> {
let mut walk = self.repo.revwalk().map_err(git_error)?;
walk.push_head().map_err(git_error)?;
let mut count = 0;
for oid in walk {
oid.map_err(git_error)?;
count += 1;
}
Ok(count)
}
pub fn log(&self, filter: &LogFilter) -> Result<Vec<LogEntry>, CoreError> {
let mut walk = self.repo.revwalk().map_err(git_error)?;
walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
.map_err(git_error)?;
walk.push_head().map_err(git_error)?;
let paths = filter
.entity
.as_deref()
.map(entity_paths)
.unwrap_or_default();
let mut entries = Vec::new();
let mut past_cursor = filter.before.is_none();
for oid in walk {
if filter.limit.is_some_and(|limit| entries.len() >= limit) {
break;
}
let oid = oid.map_err(git_error)?;
if !past_cursor {
past_cursor = filter.before.as_ref() == Some(&CommitId::from_oid(oid));
continue;
}
let commit = self.repo.find_commit(oid).map_err(git_error)?;
let message = String::from_utf8_lossy(commit.message_bytes());
let trailers = Trailers::parse(&message);
if filter
.scope
.as_ref()
.is_some_and(|scope| trailers.scope.as_ref() != Some(scope))
{
continue;
}
if let Some(entity) = &filter.entity
&& !trailers.entities.contains(entity)
&& !touches(&commit, &paths)?
{
continue;
}
entries.push(log_entry(&commit, trailers));
}
Ok(entries)
}
pub fn entry(&self, id: &CommitId) -> Result<(LogEntry, String), CoreError> {
let oid = Oid::from_str(id.as_str()).map_err(git_error)?;
let commit = self.repo.find_commit(oid).map_err(git_error)?;
let message = String::from_utf8_lossy(commit.message_bytes()).into_owned();
let trailers = Trailers::parse(&message);
Ok((log_entry(&commit, trailers), message))
}
pub fn scan_history(&self) -> Result<Vec<HistoryFinding>, CoreError> {
let allow = Allowlist::parse(&self.read_to_string(ALLOWLIST_FILE)?.unwrap_or_default());
let mut walk = self.repo.revwalk().map_err(git_error)?;
walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
.map_err(git_error)?;
walk.push_head().map_err(git_error)?;
let mut seen = HashSet::new();
let mut findings = Vec::new();
for oid in walk {
let commit = self
.repo
.find_commit(oid.map_err(git_error)?)
.map_err(git_error)?;
let id = CommitId::from_oid(commit.id());
let mut found = scan_text(
"commit message",
commit.message_bytes(),
false,
&self.secrets,
&allow,
);
let mut blobs = Vec::new();
commit
.tree()
.map_err(git_error)?
.walk(TreeWalkMode::PreOrder, |root, entry| {
if entry.kind() == Some(ObjectType::Blob) && seen.insert(entry.id()) {
let name = String::from_utf8_lossy(entry.name_bytes());
blobs.push((format!("{root}{name}"), entry.id()));
}
TreeWalkResult::Ok
})
.map_err(git_error)?;
for (path, blob) in blobs {
let blob = self.repo.find_blob(blob).map_err(git_error)?;
found.extend(scan_text(
&path,
blob.content(),
path.ends_with(".toml"),
&self.secrets,
&allow,
));
}
findings.extend(found.into_iter().map(|finding| HistoryFinding {
commit: id.clone(),
finding,
}));
}
Ok(findings)
}
}
pub(crate) fn touches(commit: &Commit<'_>, paths: &[String]) -> Result<bool, CoreError> {
if paths.is_empty() {
return Ok(false);
}
let tree = commit.tree().map_err(git_error)?;
let parent_tree = match commit.parent(0) {
Ok(parent) => Some(parent.tree().map_err(git_error)?),
Err(_) => None,
};
Ok(paths
.iter()
.any(|path| entry_id(Some(&tree), path) != entry_id(parent_tree.as_ref(), path)))
}
fn entry_id(tree: Option<&Tree<'_>>, path: &str) -> Option<Oid> {
tree?.get_path(Path::new(path)).ok().map(|entry| entry.id())
}
pub(crate) fn commit_time(commit: &Commit<'_>) -> SystemTime {
let seconds = commit.time().seconds();
match u64::try_from(seconds) {
Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds),
Err(_) => UNIX_EPOCH,
}
}
fn log_entry(commit: &Commit<'_>, trailers: Trailers) -> LogEntry {
let message = String::from_utf8_lossy(commit.message_bytes());
let author = commit.author();
LogEntry {
id: CommitId::from_oid(commit.id()),
time: commit_time(commit),
author_name: String::from_utf8_lossy(author.name_bytes()).into_owned(),
author_email: String::from_utf8_lossy(author.email_bytes()).into_owned(),
summary: message_summary(&message).to_owned(),
trailers,
}
}