use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::Read;
use std::num::NonZeroUsize;
use std::os::fd::OwnedFd;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(unix)]
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use bstr::ByteSlice;
use rustix::fs::{FileType, Mode, OFlags};
use rustix::io::Errno;
use crate::domain::{
ChangedFile, CommitBaseline, CommitMessage, CommitPage, CommitSummary, DiffDocument,
DiffTarget, FileDocument, FileRevision, LocalBranch, ObjectId, RepoPath, RepositoryRoot,
SearchHit, TextFileDocument, TreeEntry, WorktreeChange, WorktreeDiffKind,
};
use crate::git::parse::{
parse_changed_files, parse_commits, parse_file_paths, parse_grep_matches, parse_patch,
parse_status, parse_tree_entries,
};
use crate::git::{CommandOutput, GitCommand, GitError, GitRunner, OutputCompleteness};
const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
const FILE_READ_WITH_TRUNCATION_SENTINEL: u64 = MAX_FILE_BYTES as u64 + 1;
const REVISION_NOT_FOUND_EXIT_CODE: i32 = 1;
const GREP_NO_MATCH_EXIT_CODE: i32 = 1;
const OBJECT_NOT_FOUND_EXIT_CODE: i32 = 128;
const DIFF_DIFFERENCES_EXIT_CODE: i32 = 1;
#[derive(Clone, Copy)]
enum SourceRetention {
DisplayOnly,
RetainExact,
}
impl SourceRetention {
const fn retains_exact_source(self) -> bool {
matches!(self, Self::RetainExact)
}
}
#[derive(Debug)]
pub struct GitService<R> {
runner: R,
root: RepositoryRoot,
worktree: OwnedFd,
retain_exact_source: AtomicBool,
}
impl<R: GitRunner> GitService<R> {
pub fn discover(runner: R, start: &Path) -> Result<Self, GitError> {
let start = start.canonicalize().map_err(|source| GitError::Io {
operation: "resolve repository path",
source,
})?;
if !start.is_dir() {
return Err(GitError::Unsupported(format!(
"repository path is not a directory: {}",
start.display()
)));
}
let output = runner.run(None, &GitCommand::Discover { start })?;
ensure_complete(&output, "discover repository")?;
ensure_success(&output, "discover repository")?;
let raw = output
.stdout()
.strip_suffix(b"\n")
.unwrap_or(output.stdout());
if raw.is_empty() {
return Err(GitError::parse(
"repository root",
"Git returned an empty path",
));
}
#[cfg(unix)]
let path = std::path::PathBuf::from(OsString::from_vec(raw.to_vec()));
let root = RepositoryRoot::new(path)
.map_err(|detail| GitError::parse("repository root", detail.to_string()))?;
let bare = runner.run(Some(&root), &GitCommand::IsBare)?;
ensure_complete(&bare, "check bare repository")?;
ensure_success(&bare, "check bare repository")?;
if trim_newline(bare.stdout()) == b"true" {
return Err(GitError::Unsupported(format!(
"bare repositories are not supported by ChronoGit v{}",
env!("CARGO_PKG_VERSION")
)));
}
let worktree = rustix::fs::open(
root.as_path(),
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|source| filesystem_error("open repository root", source))?;
Ok(Self {
runner,
root,
worktree,
retain_exact_source: AtomicBool::new(false),
})
}
pub(crate) fn enable_exact_source(&self) {
self.retain_exact_source.store(true, Ordering::Relaxed);
}
#[must_use]
pub fn root(&self) -> &RepositoryRoot {
&self.root
}
pub fn local_branches(&self) -> Result<Vec<LocalBranch>, GitError> {
let output = self
.runner
.run(Some(&self.root), &GitCommand::LocalBranches)?;
ensure_complete(&output, "list local branches")?;
ensure_success(&output, "list local branches")?;
if output.stdout().is_empty() {
return Ok(Vec::new());
}
let records = output
.stdout()
.strip_suffix(b"\n")
.ok_or_else(|| GitError::parse("local branches", "missing record terminator"))?;
records
.split(|byte| *byte == b'\n')
.map(|record| {
let (marker, reference) = record
.split_once_str(b"\0")
.ok_or_else(|| GitError::parse("local branches", "missing branch name"))?;
if !matches!(marker, b"*" | b" ") {
return Err(GitError::parse("local branches", "invalid current marker"));
}
LocalBranch::from_ref(reference, marker == b"*")
.ok_or_else(|| GitError::parse("local branches", "invalid local reference"))
})
.collect()
}
pub fn switch_branch(&self, branch: &LocalBranch) -> Result<(), GitError> {
let output = self.runner.run(
Some(&self.root),
&GitCommand::SwitchBranch {
branch: branch.clone(),
},
)?;
ensure_success(&output, "switch branch")?;
ensure_complete(&output, "switch branch")
}
pub fn changes(&self) -> Result<Vec<WorktreeChange>, GitError> {
let output = self.runner.run(Some(&self.root), &GitCommand::Status)?;
ensure_complete(&output, "read worktree status")?;
ensure_success(&output, "read worktree status")?;
parse_status(output.stdout())
}
pub fn commits(&self, page: CommitPage) -> Result<Vec<CommitSummary>, GitError> {
let head = self.runner.run(Some(&self.root), &GitCommand::HasHead)?;
ensure_complete(&head, "check HEAD")?;
if !head.success() && head.code() == Some(REVISION_NOT_FOUND_EXIT_CODE) {
return Ok(Vec::new());
}
ensure_success(&head, "check HEAD")?;
let output = self
.runner
.run(Some(&self.root), &GitCommand::Commits { page })?;
ensure_complete(&output, "read commit history")?;
ensure_success(&output, "read commit history")?;
parse_commits(output.stdout())
}
pub fn search_files(&self, query: &str) -> Result<Vec<SearchHit>, GitError> {
let mut files = self
.repository_files()?
.into_iter()
.map(SearchHit::file)
.collect::<Vec<_>>();
let case_sensitive = query.chars().any(char::is_uppercase);
let folded_query = (!case_sensitive).then(|| query.to_lowercase());
files.retain(|hit| {
let path = hit.path().display();
if case_sensitive {
path.contains(query)
} else {
path.to_lowercase()
.contains(folded_query.as_deref().unwrap_or_default())
}
});
Ok(files)
}
pub fn repository_files(&self) -> Result<Vec<RepoPath>, GitError> {
let output = self
.runner
.run(Some(&self.root), &GitCommand::RepositoryFiles)?;
ensure_complete(&output, "list repository files")?;
ensure_success(&output, "list repository files")?;
parse_file_paths(output.stdout()).map(|hits| {
hits.into_iter()
.map(|hit| hit.path().clone())
.collect::<Vec<_>>()
})
}
pub fn search_content(&self, query: &str) -> Result<Vec<SearchHit>, GitError> {
if query.is_empty() {
return Ok(Vec::new());
}
let output = self.runner.run(
Some(&self.root),
&GitCommand::Grep {
query: query.to_owned(),
},
)?;
ensure_complete(&output, "search repository content")?;
if !output.success()
&& output.code() == Some(GREP_NO_MATCH_EXIT_CODE)
&& output.stderr().is_empty()
{
return Ok(Vec::new());
}
ensure_success(&output, "search repository content")?;
parse_grep_matches(output.stdout())
}
pub fn file_history(
&self,
path: &RepoPath,
limit: NonZeroUsize,
) -> Result<Vec<CommitSummary>, GitError> {
let output = self.runner.run(
Some(&self.root),
&GitCommand::FileHistory {
path: path.clone(),
limit,
},
)?;
ensure_complete(&output, "read file history")?;
ensure_success(&output, "read file history")?;
parse_commits(output.stdout())
}
pub fn file_content(&self, path: &RepoPath) -> Result<FileDocument, GitError> {
let (mut file, size) = match open_current_file(&self.worktree, path)? {
CurrentFile::Regular { file, size } => (file, size),
CurrentFile::Symlink { target } => return Ok(FileDocument::Symlink { target }),
CurrentFile::Unavailable { summary } => {
return Ok(FileDocument::Unavailable { summary });
}
};
let mut bytes = Vec::with_capacity(size.min(MAX_FILE_BYTES));
file.by_ref()
.take(FILE_READ_WITH_TRUNCATION_SENTINEL)
.read_to_end(&mut bytes)
.map_err(|source| GitError::Io {
operation: "read working tree file",
source,
})?;
let truncated = bytes.len() > MAX_FILE_BYTES;
bytes.truncate(MAX_FILE_BYTES);
let completeness = OutputCompleteness::from_truncated(truncated);
let retention = if self.retain_exact_source.load(Ordering::Relaxed) {
SourceRetention::RetainExact
} else {
SourceRetention::DisplayOnly
};
Ok(decode_file_document(&bytes, completeness, path, retention))
}
pub fn source_file(
&self,
revision: &FileRevision,
path: &RepoPath,
) -> Result<FileDocument, GitError> {
let revision = match revision {
FileRevision::WorkingTree => return self.file_content(path),
FileRevision::Commit(revision) => revision,
};
let command = GitCommand::RevisionFile {
revision: revision.clone(),
path: path.clone(),
};
let output = self.runner.run(Some(&self.root), &command)?;
if output.stderr_truncated() {
return Err(GitError::OutputLimit {
operation: command.kind(),
});
}
if !output.success()
&& !output.stdout_truncated()
&& output.code() == Some(OBJECT_NOT_FOUND_EXIT_CODE)
&& output.stdout().is_empty()
{
return Ok(FileDocument::Unavailable {
summary: format!(
"File does not exist in {}: {}",
FileRevision::Commit(revision.clone()).display(),
path.display()
),
});
}
if !output.success() && !output.stdout_truncated() {
ensure_success(&output, command.kind())?;
}
let completeness = OutputCompleteness::from_truncated(output.stdout_truncated());
let retention = if self.retain_exact_source.load(Ordering::Relaxed) {
SourceRetention::RetainExact
} else {
SourceRetention::DisplayOnly
};
Ok(decode_file_document(
output.stdout(),
completeness,
path,
retention,
))
}
pub fn commit_message(&self, commit: &ObjectId) -> Result<CommitMessage, GitError> {
let output = self.runner.run(
Some(&self.root),
&GitCommand::CommitMessage {
commit: commit.clone(),
},
)?;
ensure_complete(&output, "read commit message")?;
ensure_success(&output, "read commit message")?;
Ok(CommitMessage::new(
output.stdout().to_str_lossy().into_owned(),
))
}
pub fn changed_files(
&self,
commit: &ObjectId,
baseline: &CommitBaseline,
) -> Result<Vec<ChangedFile>, GitError> {
let output = self.runner.run(
Some(&self.root),
&GitCommand::ChangedFiles {
commit: commit.clone(),
baseline: baseline.clone(),
},
)?;
ensure_complete(&output, "read changed files")?;
ensure_success(&output, "read changed files")?;
parse_changed_files(output.stdout())
}
pub fn diff(&self, target: &DiffTarget) -> Result<DiffDocument, GitError> {
let command = match target {
DiffTarget::Worktree {
path,
kind: WorktreeDiffKind::Untracked,
} => GitCommand::UntrackedDiff { path: path.clone() },
DiffTarget::Worktree { path, .. } => GitCommand::WorktreeDiff { path: path.clone() },
DiffTarget::Commit {
commit,
baseline,
path,
} => GitCommand::CommitDiff {
commit: commit.clone(),
baseline: baseline.clone(),
path: path.clone(),
},
};
let output = self.runner.run(Some(&self.root), &command)?;
if output.stderr_truncated() {
return Err(GitError::OutputLimit {
operation: command.kind(),
});
}
let allowed_no_index_difference = matches!(command, GitCommand::UntrackedDiff { .. })
&& output.code() == Some(DIFF_DIFFERENCES_EXIT_CODE)
&& output.stderr().is_empty();
if !output.success() && !allowed_no_index_difference && !output.stdout_truncated() {
return Err(command_failed(&output, command.kind()));
}
Ok(parse_patch(
output.stdout(),
OutputCompleteness::from_truncated(output.stdout_truncated()),
))
}
pub fn tree_entries(&self, treeish: &ObjectId) -> Result<Vec<TreeEntry>, GitError> {
let output = self.runner.run(
Some(&self.root),
&GitCommand::TreeEntries {
treeish: treeish.clone(),
},
)?;
ensure_complete(&output, "read tree entries")?;
ensure_success(&output, "read tree entries")?;
parse_tree_entries(output.stdout())
}
}
fn decode_file_document(
bytes: &[u8],
completeness: OutputCompleteness,
path: &RepoPath,
retention: SourceRetention,
) -> FileDocument {
if bytes.contains(&0) {
return FileDocument::Binary {
summary: format!("Binary file: {}", path.display()),
};
}
let text = bytes.to_str_lossy();
let lines = text.lines().map(ToOwned::to_owned).collect();
let text = if completeness.is_truncated() {
TextFileDocument::truncated(lines)
} else if retention.retains_exact_source() && matches!(&text, std::borrow::Cow::Borrowed(_)) {
TextFileDocument::exact(text.into_owned())
} else {
TextFileDocument::display_only(lines)
};
FileDocument::Text(text)
}
enum CurrentFile {
Regular { file: File, size: usize },
Symlink { target: String },
Unavailable { summary: String },
}
fn open_current_file(worktree: &OwnedFd, path: &RepoPath) -> Result<CurrentFile, GitError> {
let directory_flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
let mut directory = rustix::io::dup(worktree)
.map_err(|source| filesystem_error("duplicate repository root", source))?;
let mut components = path.as_bytes().split(|byte| *byte == b'/');
let final_component = components
.next_back()
.ok_or_else(|| GitError::parse("working tree path", "path is empty"))?;
for component in components {
let name = OsStr::from_bytes(component);
directory = match rustix::fs::openat(&directory, name, directory_flags, Mode::empty()) {
Ok(descriptor) => descriptor,
Err(Errno::NOENT) => {
return Ok(CurrentFile::Unavailable {
summary: format!(
"File does not exist in the current working tree: {}",
path.display()
),
});
}
Err(Errno::LOOP | Errno::NOTDIR) => {
return Ok(CurrentFile::Unavailable {
summary: format!(
"Path contains a symbolic link or non-directory component: {}",
path.display()
),
});
}
Err(source) => {
return Err(filesystem_error(
"open working tree directory component",
source,
));
}
};
}
let final_name = OsStr::from_bytes(final_component);
let descriptor = match rustix::fs::openat(
&directory,
final_name,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(descriptor) => descriptor,
Err(Errno::LOOP) => {
let target = rustix::fs::readlinkat(&directory, final_name, Vec::new())
.map_err(|source| filesystem_error("read working tree symlink", source))?;
let target = OsString::from_vec(target.as_bytes().to_vec());
return Ok(CurrentFile::Symlink {
target: format!("symlink → {}", target.to_string_lossy()),
});
}
Err(Errno::NOENT) => {
return Ok(CurrentFile::Unavailable {
summary: format!(
"File does not exist in the current working tree: {}",
path.display()
),
});
}
Err(Errno::NOTDIR) => {
return Ok(CurrentFile::Unavailable {
summary: format!("Not a regular working-tree file: {}", path.display()),
});
}
Err(source) => return Err(filesystem_error("open working tree file", source)),
};
let metadata = rustix::fs::fstat(&descriptor)
.map_err(|source| filesystem_error("read working tree file metadata", source))?;
if !FileType::from_raw_mode(metadata.st_mode).is_file() {
return Ok(CurrentFile::Unavailable {
summary: format!("Not a regular working-tree file: {}", path.display()),
});
}
Ok(CurrentFile::Regular {
file: File::from(descriptor),
size: usize::try_from(metadata.st_size).unwrap_or(usize::MAX),
})
}
fn filesystem_error(operation: &'static str, source: Errno) -> GitError {
GitError::Io {
operation,
source: source.into(),
}
}
fn ensure_success(output: &CommandOutput, operation: &'static str) -> Result<(), GitError> {
if output.success() {
Ok(())
} else {
Err(command_failed(output, operation))
}
}
fn ensure_complete(output: &CommandOutput, operation: &'static str) -> Result<(), GitError> {
if output.stdout_truncated() || output.stderr_truncated() {
Err(GitError::OutputLimit { operation })
} else {
Ok(())
}
}
fn command_failed(output: &CommandOutput, operation: &'static str) -> GitError {
GitError::CommandFailed {
operation,
code: output.code(),
stderr: output.stderr().to_str_lossy().into_owned(),
}
}
fn trim_newline(mut value: &[u8]) -> &[u8] {
while value
.last()
.is_some_and(|byte| matches!(byte, b'\n' | b'\r'))
{
value = &value[..value.len() - 1];
}
value
}