use std::collections::HashMap;
use std::path::{Path, PathBuf};
use gitpoulpi_core::domain::{
finish_hits, usable_terms, Blame, BlameContent, BlameLine, Blob, BlobBody, BlobBytes,
BlobContent, BlobSource, GrepHit, LfsPointer, Oid, RepoRef, MAX_GREP_FILE_BYTES,
MAX_TEXT_BLOB_BYTES,
};
use gitpoulpi_core::{Error, Result};
use crate::process::{run, run_bytes, run_lenient, run_z_fields};
pub fn read_blob(repo: &RepoRef, path: &Path, source: &BlobSource) -> Result<Blob> {
let rel = repo_relative(path)?;
let (size, content, image) = match source {
BlobSource::WorkingTree => {
let full = repo.root.join(&rel);
let size = std::fs::metadata(&full)
.map_err(|e| Error::Backend(format!("{rel}: {e}")))?
.len();
if size > MAX_TEXT_BLOB_BYTES {
(size, BlobContent::TooLarge, None)
} else {
let raw =
std::fs::read(&full).map_err(|e| Error::Backend(format!("{rel}: {e}")))?;
let content = BlobContent::from_bytes(&raw);
let image = Blob::image_of(&content, &raw);
(size, content, image)
}
}
BlobSource::Index => read_object(repo, &format!(":{rel}"))?,
BlobSource::Commit(oid) => read_object(repo, &format!("{}:{rel}", oid.to_hex()))?,
BlobSource::Stage(n) => read_object(repo, &stage_spec(*n, &rel)?)?,
};
Ok(Blob {
path: PathBuf::from(rel),
source: source.clone(),
size,
content,
image,
})
}
fn read_object(
repo: &RepoRef,
spec: &str,
) -> Result<(u64, BlobContent, Option<gitpoulpi_core::domain::ImageInfo>)> {
let size: u64 = run(&repo.root, &["cat-file", "-s", spec])?
.trim()
.parse()
.map_err(|e| Error::Backend(format!("git cat-file -s {spec} gave no size: {e}")))?;
if size > MAX_TEXT_BLOB_BYTES {
return Ok((size, BlobContent::TooLarge, None));
}
let raw = run_bytes(&repo.root, &["cat-file", "blob", spec])?;
let content = BlobContent::from_bytes(&raw);
let image = Blob::image_of(&content, &raw);
Ok((size, content, image))
}
fn stage_spec(stage: u8, rel: &str) -> Result<String> {
if (1..=3).contains(&stage) {
Ok(format!(":{stage}:{rel}"))
} else {
Err(Error::Backend(format!("{rel} has no stage {stage}")))
}
}
pub fn read_blob_bytes(
repo: &RepoRef,
path: &Path,
source: &BlobSource,
max: u64,
) -> Result<BlobBytes> {
let rel = repo_relative(path)?;
let spec = match source {
BlobSource::WorkingTree => String::new(),
BlobSource::Index => format!(":{rel}"),
BlobSource::Commit(oid) => format!("{}:{rel}", oid.to_hex()),
BlobSource::Stage(n) => stage_spec(*n, &rel)?,
};
let size = if let BlobSource::WorkingTree = source {
std::fs::metadata(repo.root.join(&rel))
.map_err(|e| Error::Backend(format!("{rel}: {e}")))?
.len()
} else {
run(&repo.root, &["cat-file", "-s", &spec])?
.trim()
.parse()
.map_err(|e| Error::Backend(format!("git cat-file -s {spec} gave no size: {e}")))?
};
let body = if size > max {
BlobBody::TooLarge
} else {
let raw = if let BlobSource::WorkingTree = source {
std::fs::read(repo.root.join(&rel))
.map_err(|e| Error::Backend(format!("{rel}: {e}")))?
} else {
run_bytes(&repo.root, &["cat-file", "blob", &spec])?
};
body_of(repo, raw, max)
};
Ok(BlobBytes {
path: PathBuf::from(rel),
source: source.clone(),
size,
body,
})
}
pub fn body_of(repo: &RepoRef, raw: Vec<u8>, max: u64) -> BlobBody {
match LfsPointer::parse(&raw) {
Some(pointer) => {
let object = lfs_local_object(repo, &pointer, max);
BlobBody::Lfs { pointer, object }
}
None => BlobBody::Bytes(raw),
}
}
pub fn lfs_local_object(repo: &RepoRef, pointer: &LfsPointer, max: u64) -> Option<Vec<u8>> {
let oid = pointer.oid.as_str();
if oid.len() < 4 || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let common = run(&repo.root, &["rev-parse", "--git-common-dir"]).ok()?;
let common = repo.root.join(common.trim());
let configured = run_lenient(&repo.root, &["config", "--get", "lfs.storage"])
.ok()
.filter(|(ok, _)| *ok)
.map(|(_, v)| v.trim().to_string())
.filter(|v| !v.is_empty());
let storage = match configured {
Some(p) => common.join(p),
None => common.join("lfs"),
};
let file = storage
.join("objects")
.join(&oid[0..2])
.join(&oid[2..4])
.join(oid);
if std::fs::metadata(&file).ok()?.len() > max {
return None;
}
std::fs::read(file).ok()
}
pub fn blame(repo: &RepoRef, path: &Path, at: Oid) -> Result<Blame> {
let rel = repo_relative(path)?;
let blob = read_blob(repo, path, &BlobSource::Commit(at))?;
let lines = match &blob.content {
BlobContent::Text { lines, .. } => lines.clone(),
BlobContent::Binary => {
return Ok(Blame {
path: blob.path,
at,
size: blob.size,
content: BlameContent::Binary,
})
}
BlobContent::TooLarge => {
return Ok(Blame {
path: blob.path,
at,
size: blob.size,
content: BlameContent::TooLarge,
})
}
BlobContent::LfsPointer(pointer) => {
return Ok(Blame {
path: blob.path,
at,
size: blob.size,
content: BlameContent::LfsPointer(pointer.clone()),
})
}
};
let rev = at.to_hex();
let raw = run_bytes(
&repo.root,
&[
"blame",
"--line-porcelain",
"--no-textconv",
"--no-ext-diff",
&rev,
"--",
&rel,
],
)?;
let raw = String::from_utf8_lossy(&raw);
let entries = parse_line_porcelain(&raw);
if entries.len() < lines.len() {
return Err(Error::Backend(format!(
"git blame returned {} lines for {rel}, but the file at {rev} has {}",
entries.len(),
lines.len()
)));
}
let out = lines
.into_iter()
.zip(entries)
.map(|(content, entry)| BlameLine {
commit: entry.commit,
author_name: entry.author_name,
author_email: entry.author_email,
timestamp: entry.timestamp,
committer_time: entry.committer_time,
summary: entry.summary,
final_line: entry.final_line,
orig_line: entry.orig_line,
orig_path: PathBuf::from(entry.filename),
previous: entry.previous,
content,
})
.collect();
Ok(Blame {
path: blob.path,
at,
size: blob.size,
content: BlameContent::Lines(out),
})
}
struct PorcelainEntry {
commit: Oid,
author_name: String,
author_email: String,
timestamp: i64,
committer_time: i64,
summary: String,
final_line: u32,
orig_line: u32,
filename: String,
previous: Option<(Oid, PathBuf)>,
}
fn parse_line_porcelain(raw: &str) -> Vec<PorcelainEntry> {
let mut out = Vec::new();
let mut current: Option<PorcelainEntry> = None;
let mut summaries: HashMap<Oid, String> = HashMap::new();
for line in raw.lines() {
if line.starts_with('\t') {
if let Some(mut entry) = current.take() {
if entry.summary.is_empty() {
entry.summary = summaries.get(&entry.commit).cloned().unwrap_or_default();
} else {
summaries.insert(entry.commit, entry.summary.clone());
}
out.push(entry);
}
continue;
}
if let Some(entry) = current.as_mut() {
if let Some(rest) = line.strip_prefix("author-mail ") {
entry.author_email = rest.trim().trim_matches(['<', '>']).to_string();
} else if let Some(rest) = line.strip_prefix("author-time ") {
entry.timestamp = rest.trim().parse().unwrap_or_default();
} else if let Some(rest) = line.strip_prefix("author ") {
entry.author_name = rest.to_string();
} else if let Some(rest) = line.strip_prefix("summary ") {
entry.summary = rest.to_string();
} else if let Some(rest) = line.strip_prefix("committer-time ") {
entry.committer_time = rest.trim().parse().unwrap_or_default();
} else if let Some(rest) = line.strip_prefix("filename ") {
entry.filename = unquote_c(rest);
} else if let Some(rest) = line.strip_prefix("previous ") {
if let Some((sha, path)) = rest.split_once(' ') {
entry.previous =
Oid::from_hex(sha).map(|oid| (oid, PathBuf::from(unquote_c(path))));
}
}
continue;
}
let mut fields = line.split(' ');
let Some(commit) = fields.next().and_then(Oid::from_hex) else {
continue;
};
let Some(orig_line) = fields.next().and_then(|f| f.parse().ok()) else {
continue;
};
let Some(final_line) = fields.next().and_then(|f| f.parse().ok()) else {
continue;
};
current = Some(PorcelainEntry {
commit,
author_name: String::new(),
author_email: String::new(),
timestamp: 0,
committer_time: 0,
summary: String::new(),
final_line,
orig_line,
filename: String::new(),
previous: None,
});
}
out
}
fn unquote_c(raw: &str) -> String {
let Some(inner) = raw.strip_prefix('"').and_then(|r| r.strip_suffix('"')) else {
return raw.to_string();
};
let bytes = inner.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'\\' || i + 1 >= bytes.len() {
out.push(bytes[i]);
i += 1;
continue;
}
i += 1;
match bytes[i] {
b'n' => out.push(b'\n'),
b't' => out.push(b'\t'),
b'r' => out.push(b'\r'),
c @ b'0'..=b'7' => {
let mut value = u32::from(c - b'0');
let mut taken = 1;
while taken < 3 && i + 1 < bytes.len() && (b'0'..=b'7').contains(&bytes[i + 1]) {
i += 1;
value = value * 8 + u32::from(bytes[i] - b'0');
taken += 1;
}
out.push(value as u8);
}
other => out.push(other),
}
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
pub(crate) fn repo_relative(path: &Path) -> Result<String> {
let text = path
.to_str()
.ok_or_else(|| Error::Backend(format!("path {} is not valid utf-8", path.display())))?;
Ok(text.replace('\\', "/").trim_start_matches("./").to_string())
}
pub fn list_tree(repo: &RepoRef, at: Oid) -> Result<Vec<PathBuf>> {
let spec = format!("{}^{{tree}}", at.to_hex());
let fields = run_z_fields(
&repo.root,
&["ls-tree", "-r", "-z", "--name-only", "--full-tree", &spec],
)?;
Ok(fields.into_iter().map(PathBuf::from).collect())
}
pub fn grep_tree(
repo: &RepoRef,
at: Oid,
terms: &[String],
max_hits: usize,
) -> Result<Vec<GrepHit>> {
let rev = at.to_hex();
run(
&repo.root,
&["rev-parse", "--verify", &format!("{rev}^{{commit}}")],
)?;
let terms = usable_terms(terms);
if terms.is_empty() || max_hits == 0 {
return Ok(Vec::new());
}
let listing = run_bytes(
&repo.root,
&["ls-tree", "-r", "-l", "-z", "--full-tree", &rev],
)?;
let mut excluded: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut small: std::collections::HashSet<String> = std::collections::HashSet::new();
for record in listing.split(|b| *b == 0).filter(|r| !r.is_empty()) {
let record = String::from_utf8_lossy(record);
let Some((meta, path)) = record.split_once('\t') else {
continue;
};
let fields: Vec<&str> = meta.split_whitespace().collect();
let (mode, size) = (fields.first().copied(), fields.get(3).copied());
if mode == Some("120000") {
excluded.insert(path.to_string());
} else if let Some(size) = size.and_then(|s| s.parse::<u64>().ok()) {
if size > MAX_GREP_FILE_BYTES {
excluded.insert(path.to_string());
} else if size < gitpoulpi_core::domain::LFS_POINTER_MAX_BYTES as u64 {
small.insert(path.to_string());
}
}
}
let prefix = format!("{rev}:");
let max_count = max_hits.to_string();
let mut hits: Vec<GrepHit> = Vec::new();
for term in &terms {
let out = crate::process::run_lenient_bytes(
&repo.root,
&[
"grep",
"-n",
"-F",
"-I",
"--no-color",
"-z",
"--max-count",
&max_count,
"-e",
term,
&rev,
"--",
],
)?;
for record in out.split(|b| *b == b'\n') {
let mut parts = record.splitn(3, |b| *b == 0);
let (Some(path), Some(line), Some(text)) = (parts.next(), parts.next(), parts.next())
else {
continue;
};
let path = String::from_utf8_lossy(path);
let Some(path) = path.strip_prefix(&prefix) else {
continue;
};
let Ok(line) = String::from_utf8_lossy(line).parse::<u32>() else {
continue;
};
if excluded.contains(path) {
continue;
}
hits.push(GrepHit {
term: term.clone(),
path: path.to_string(),
line,
text: gitpoulpi_core::domain::hit_text(&String::from_utf8_lossy(text)),
});
}
}
let mut pointer_free: std::collections::HashMap<String, bool> =
std::collections::HashMap::new();
let mut kept = Vec::with_capacity(hits.len());
for hit in hits {
if small.contains(&hit.path) {
let searchable = match pointer_free.get(&hit.path) {
Some(known) => *known,
None => {
let raw = run_bytes(&repo.root, &["show", &format!("{rev}:{}", hit.path)])?;
let ok = LfsPointer::parse(&raw).is_none();
pointer_free.insert(hit.path.clone(), ok);
ok
}
};
if !searchable {
continue;
}
}
kept.push(hit);
}
Ok(finish_hits(kept, &terms, max_hits))
}