use anyhow::{bail, Result};
use serde::Serialize;
use std::path::Path;
#[derive(Serialize)]
pub struct CommitFile {
pub path: String,
pub old_path: Option<String>,
pub status: String,
pub additions: Option<usize>,
pub deletions: Option<usize>,
}
#[derive(Serialize)]
pub struct GitCommitDetails {
pub sha: String,
pub message: String,
pub author: String,
pub committer: String,
pub author_email: String,
pub committer_email: String,
pub time: i64,
pub parents: Vec<String>,
pub files: Vec<CommitFile>,
pub additions: usize,
pub deletions: usize,
pub truncated: bool,
}
fn oid(sha: &str) -> Result<git2::Oid> {
if sha.len() != 40 || !sha.bytes().all(|byte| byte.is_ascii_hexdigit()) {
bail!("Invalid full commit ID");
}
Ok(git2::Oid::from_str(sha)?)
}
fn trees<'a>(
repo: &'a git2::Repository,
sha: &str,
) -> Result<(Option<git2::Tree<'a>>, git2::Tree<'a>)> {
let commit = repo.find_commit(oid(sha)?)?;
let parent = if commit.parent_count() > 0 {
Some(commit.parent(0)?.tree()?)
} else {
None
};
Ok((parent, commit.tree()?))
}
pub fn commit_details(root: &Path, sha: &str, path: Option<&str>) -> Result<GitCommitDetails> {
if let Some(path) = path {
super::validate_file_path(path)?;
}
let repo =
git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
let commit = repo.find_commit(oid(sha)?)?;
let (parent, tree) = trees(&repo, sha)?;
let mut diff = repo.diff_tree_to_tree(parent.as_ref(), Some(&tree), None)?;
diff.find_similar(None)?;
let (files, additions, deletions, truncated) = commit_files(&diff, path.map(Path::new))?;
let author = commit.author().name().unwrap_or_default().to_owned();
let committer = commit.committer().name().unwrap_or_default().to_owned();
let author_email = commit.author().email().unwrap_or_default().to_owned();
let committer_email = commit.committer().email().unwrap_or_default().to_owned();
Ok(GitCommitDetails {
sha: commit.id().to_string(),
message: commit.message().unwrap_or_default().into(),
author,
committer,
author_email,
committer_email,
time: commit.time().seconds(),
parents: commit.parent_ids().map(|id| id.to_string()).collect(),
files,
additions,
deletions,
truncated,
})
}
fn commit_files(
diff: &git2::Diff<'_>,
scope: Option<&Path>,
) -> Result<(Vec<CommitFile>, usize, usize, bool)> {
const FILE_LIMIT: usize = 1000;
let mut additions = 0;
let mut deletions = 0;
let mut truncated = false;
let mut files = Vec::new();
for (index, delta) in diff.deltas().enumerate() {
if let Some(scope) = scope {
if ![delta.old_file().path(), delta.new_file().path()]
.into_iter()
.flatten()
.any(|path| path.starts_with(scope))
{
continue;
}
}
if files.len() == FILE_LIMIT {
truncated = true;
if scope.is_none() {
break;
}
}
let patch = git2::Patch::from_diff(diff, index)?;
let lines = patch
.as_ref()
.filter(|patch| {
let delta = patch.delta();
!delta.old_file().is_binary() && !delta.new_file().is_binary()
})
.map(|patch| patch.line_stats())
.transpose()?;
if let Some((_, added, deleted)) = lines {
additions += added;
deletions += deleted;
}
if truncated {
continue;
}
let path = delta
.new_file()
.path()
.or(delta.old_file().path())
.map(|path| path.to_string_lossy().into_owned())
.unwrap_or_default();
let old_path = delta
.old_file()
.path()
.map(|path| path.to_string_lossy().into_owned())
.filter(|old| old != &path);
files.push(CommitFile {
path,
old_path,
additions: lines.map(|(_, added, _)| added),
deletions: lines.map(|(_, _, deleted)| deleted),
status: match delta.status() {
git2::Delta::Added => "added",
git2::Delta::Deleted => "deleted",
git2::Delta::Renamed => "renamed",
_ => "modified",
}
.into(),
});
}
if scope.is_none() {
let stats = diff.stats()?;
additions = stats.insertions();
deletions = stats.deletions();
}
Ok((files, additions, deletions, truncated))
}
#[derive(Serialize)]
pub struct GitCommitFileView {
pub content: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub unchanged_text: Option<String>,
}
fn commit_diff(root: &Path, sha: &str, path: &str) -> Result<GitCommitFileView> {
super::validate_file_path(path)?;
let repo =
git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
let (parent, tree) = trees(&repo, sha)?;
let mut options = git2::DiffOptions::new();
options.context_lines(super::DIFF_CONTEXT_LINES);
let mut diff = repo.diff_tree_to_tree(parent.as_ref(), Some(&tree), Some(&mut options))?;
diff.find_similar(None)?;
let content = super::render_diff_for_path(&diff, Some(path))?;
let unchanged_text = match diff
.deltas()
.find(|delta| super::matches_diff_path(delta, Path::new(path)))
{
Some(delta) => unchanged_blob_text(&repo, &delta)?,
None => None,
};
Ok(GitCommitFileView {
content,
unchanged_text,
})
}
fn unchanged_blob_text(
repo: &git2::Repository,
delta: &git2::DiffDelta<'_>,
) -> Result<Option<String>> {
use git2::FileMode::{Blob, BlobExecutable, BlobGroupWritable};
let before = delta.old_file();
let after = delta.new_file();
if before.id() != after.id()
|| !matches!(before.mode(), Blob | BlobExecutable | BlobGroupWritable)
|| !matches!(after.mode(), Blob | BlobExecutable | BlobGroupWritable)
|| delta.flags().contains(git2::DiffFlags::BINARY)
{
return Ok(None);
}
let blob = repo.find_blob(after.id())?;
if blob.size() > super::MAX_DIFF_BYTES || blob.is_binary() {
return Ok(None);
}
Ok(std::str::from_utf8(blob.content()).ok().map(str::to_owned))
}
pub fn commit_file_view(
root: &Path,
sha: &str,
path: &str,
view: Option<&str>,
) -> Result<GitCommitFileView> {
if view.is_none() {
return commit_diff(root, sha, path);
}
super::validate_file_path(path)?;
let repo =
git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
let tree = repo.find_commit(oid(sha)?)?.tree()?;
let content = match view {
Some("revision") => {
let entry = tree.get_path(Path::new(path))?;
let blob = repo.find_blob(entry.id())?;
if blob.size() > 2 * 1024 * 1024 {
bail!("File exceeds the preview limit");
}
if blob.is_binary() {
bail!("Binary files cannot be previewed as text");
}
std::str::from_utf8(blob.content())?.to_owned()
}
Some("working") => {
let mut options = git2::DiffOptions::new();
options
.context_lines(super::DIFF_CONTEXT_LINES)
.include_untracked(true)
.show_untracked_content(true);
let diff = repo.diff_tree_to_workdir_with_index(Some(&tree), Some(&mut options))?;
super::render_diff_for_path(&diff, Some(path))?
}
_ => bail!("Unsupported commit file view"),
};
Ok(GitCommitFileView {
content,
unchanged_text: None,
})
}
#[derive(Serialize)]
pub struct GitHistoryPage {
pub commits: Vec<super::GitCommit>,
pub has_more: bool,
}
pub fn commit_history(root: &Path, sha: &str, offset: usize) -> Result<GitHistoryPage> {
if offset > 100_000 {
bail!("History offset exceeds the preview limit");
}
let repo =
git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
let commit = repo.find_commit(oid(sha)?)?;
let walk = super::history_walk(&repo, commit.id())?;
let mut commits = Vec::new();
for id in walk.skip(offset).take(11) {
commits.push(super::summarize_commit(&repo.find_commit(id?)?));
}
let has_more = commits.len() > 10;
commits.truncate(10);
Ok(GitHistoryPage { commits, has_more })
}
#[cfg(test)]
mod tests;