use chrono::{DateTime, Utc};
use git2::build::{CheckoutBuilder, TreeUpdateBuilder};
use git2::{
Delta, DiffFindOptions, DiffFormat, DiffOptions, FileMode, Oid, Repository, Signature, Sort,
};
use serde::Serialize;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use crate::error::AppError;
use crate::order;
use crate::seek::SeekFilter;
use crate::validate;
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TreeNode {
File {
name: String,
},
Directory {
name: String,
children: Vec<TreeNode>,
},
}
impl TreeNode {
fn name(&self) -> &str {
match self {
Self::File { name } | Self::Directory { name, .. } => name,
}
}
}
#[derive(Debug, Default)]
pub struct FileCounts {
pub files: usize,
pub directories: usize,
}
#[derive(Debug, Clone, Copy)]
pub enum OrderPosition {
At(usize),
Unlisted,
}
#[derive(Debug)]
pub struct FileRead {
pub content: String,
pub position: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathKind {
File,
Directory,
Missing,
}
#[derive(Debug, Clone, Copy)]
pub enum DateKind {
Created,
Updated,
}
#[derive(Debug, Clone, Copy)]
pub struct DateFilter {
pub from: Option<DateTime<Utc>>,
pub to: Option<DateTime<Utc>>,
pub kind: DateKind,
}
impl DateFilter {
fn matches(&self, date: DateTime<Utc>) -> bool {
if let Some(from) = self.from {
if date < from {
return false;
}
}
if let Some(to) = self.to {
if date >= to {
return false;
}
}
true
}
}
#[derive(Debug, Clone, Copy)]
pub struct OrderOptions {
pub implicit_default_index: Option<i64>,
}
type OrderRank = (i64, bool);
#[derive(Debug, Serialize)]
pub struct CommitAuthor {
pub name: String,
pub email: String,
}
#[derive(Debug, Serialize)]
pub struct CommitSummary {
pub sha: String,
pub message: String,
pub author: CommitAuthor,
pub committed_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub statistics: Option<CommitStatistics>,
}
#[derive(Debug, Serialize)]
pub struct CommitStatistics {
pub insertions: usize,
pub deletions: usize,
pub files_changed: usize,
}
#[derive(Debug, Serialize)]
pub struct CommitDetail {
pub sha: String,
pub message: String,
pub author: CommitAuthor,
pub committed_at: DateTime<Utc>,
pub files: Vec<CommitFileDetail>,
pub statistics: CommitStatistics,
}
#[derive(Debug, Serialize)]
pub struct CommitFileDetail {
pub path: String,
pub change: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub from_path: Option<String>,
pub content: String,
pub diff: String,
}
#[derive(Debug, Clone)]
pub enum FileChange {
Created {
path: String,
content: String,
},
Updated {
path: String,
content: String,
},
Deleted {
path: String,
},
Moved {
from_path: String,
to_path: String,
content: String,
},
}
struct DeltaRecord {
status: Delta,
old_oid: Oid,
new_oid: Oid,
old_path: Option<PathBuf>,
new_path: Option<PathBuf>,
}
struct GitUtils;
impl GitUtils {
fn git_signature<'a>(
author_name: &'a str,
author_email: &'a str,
) -> Result<Signature<'a>, AppError> {
if author_name.trim().is_empty() {
return Err(AppError::InvalidOperation {
reason: "author.name must not be empty".to_string(),
});
}
if author_email.trim().is_empty() {
return Err(AppError::InvalidOperation {
reason: "author.email must not be empty".to_string(),
});
}
tracing::trace!(author_name = %author_name, author_email = %author_email, "creating git signature");
Signature::now(author_name, author_email).map_err(AppError::Git)
}
fn timestamp_from_git_time(git_time: git2::Time) -> DateTime<Utc> {
DateTime::from_timestamp(git_time.seconds(), 0).unwrap_or(DateTime::UNIX_EPOCH)
}
fn open_tenant_repo(repo_path: &Path, tenant_id: &str) -> Result<Repository, AppError> {
let not_found = || {
tracing::debug!(tenant_id = %tenant_id, "tenant repository not found");
AppError::TenantNotFound {
tenant_id: tenant_id.to_string(),
}
};
if !repo_path.exists() {
return Err(not_found());
}
tracing::trace!(tenant_id = %tenant_id, path = %repo_path.display(), "opening tenant repository");
let repo = match Repository::open(repo_path) {
Ok(repo) => repo,
Err(err) if err.code() == git2::ErrorCode::NotFound => return Err(not_found()),
Err(err) => return Err(AppError::Git(err)),
};
if let Err(err) = repo.head() {
if err.code() == git2::ErrorCode::UnbornBranch {
return Err(not_found());
}
}
Ok(repo)
}
fn open_or_init_repo(
repo_path: &Path,
author_name: &str,
author_email: &str,
) -> Result<Repository, AppError> {
if repo_path.join(".git").exists() {
tracing::trace!(path = %repo_path.display(), "opening existing repository");
return Repository::open(repo_path).map_err(AppError::Git);
}
tracing::info!(path = %repo_path.display(), "initialising new tenant repository");
let signature = Self::git_signature(author_name, author_email)?;
if repo_path.exists() {
Self::init_with_root_commit(repo_path, &signature)?;
} else {
GitStaging::create(repo_path, |staging| {
Self::init_with_root_commit(staging, &signature)
})?;
}
Repository::open(repo_path).map_err(AppError::Git)
}
fn init_with_root_commit(path: &Path, signature: &Signature) -> Result<(), AppError> {
let repo = Repository::init(path)?;
tracing::trace!(path = %path.display(), "writing empty tree for root commit");
let empty_tree_id = repo.treebuilder(None)?.write()?;
let empty_tree = repo.find_tree(empty_tree_id)?;
let root_oid = repo.commit(
Some("HEAD"),
signature,
signature,
"chore: initialize",
&empty_tree,
&[],
)?;
tracing::debug!(path = %path.display(), sha = %root_oid, "root commit created");
Ok(())
}
fn blob_content_from_tree(
repo: &Repository,
tree: &git2::Tree<'_>,
file_path: &str,
) -> Result<String, AppError> {
tracing::trace!(path = %file_path, "reading blob from tree");
let tree_entry =
tree.get_path(Path::new(file_path))
.map_err(|_err| AppError::FileNotFound {
path: file_path.to_string(),
})?;
let blob = repo.find_blob(tree_entry.id())?;
tracing::trace!(path = %file_path, blob_id = %tree_entry.id(), size = blob.size(), "blob found");
std::str::from_utf8(blob.content())
.map(|text| text.to_string())
.map_err(|_err| AppError::InvalidUtf8 {
path: file_path.to_string(),
})
}
fn blob_oid_in_tree(tree: &git2::Tree<'_>, file_path: &str) -> Option<Oid> {
let tree_entry = tree.get_path(Path::new(file_path)).ok()?;
if tree_entry.kind() != Some(git2::ObjectType::Blob) {
return None;
}
Some(tree_entry.id())
}
fn windowed_blob_content(
repo: &Repository,
oid: Oid,
file_path: &str,
seek: &SeekFilter,
) -> Result<String, AppError> {
if seek.is_noop() {
let blob = repo.find_blob(oid)?;
return std::str::from_utf8(blob.content())
.map(|text| text.to_string())
.map_err(|_err| AppError::InvalidUtf8 {
path: file_path.to_string(),
});
}
let odb = repo.odb()?;
let window = match odb.reader(oid) {
Ok((reader, _size, _object_type)) => {
tracing::trace!(path = %file_path, blob_id = %oid, "seek-reading blob via odb stream");
seek.apply_reader(std::io::BufReader::new(reader), file_path)
}
Err(_stream_unsupported) => {
tracing::trace!(path = %file_path, blob_id = %oid, "seek-reading blob in memory (streaming unsupported)");
let blob = repo.find_blob(oid)?;
seek.apply_reader(std::io::Cursor::new(blob.content()), file_path)
}
};
window
}
fn subtree_blob_paths(
repo: &Repository,
tree: &git2::Tree<'_>,
dir_path: &str,
) -> Result<Vec<(String, Oid)>, AppError> {
let tree_entry =
tree.get_path(Path::new(dir_path))
.map_err(|_err| AppError::FileNotFound {
path: dir_path.to_string(),
})?;
let subtree = repo
.find_tree(tree_entry.id())
.map_err(|_err| AppError::FileNotFound {
path: dir_path.to_string(),
})?;
let mut blobs: Vec<(String, Oid)> = Vec::new();
subtree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
if entry.kind() == Some(git2::ObjectType::Blob) {
if let Ok(name) = entry.name() {
blobs.push((format!("{}/{}{}", dir_path, root, name), entry.id()));
}
}
git2::TreeWalkResult::Ok
})?;
tracing::trace!(path = %dir_path, file_count = blobs.len(), "collected subtree blobs");
Ok(blobs)
}
fn path_string(path: Option<&Path>) -> String {
path.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default()
}
fn build_tree(
flat: Vec<String>,
stubs: Vec<String>,
max_depth: Option<usize>,
) -> Vec<TreeNode> {
enum NodeBuilder {
File,
Dir(BTreeMap<String, NodeBuilder>),
}
fn insert(
dir: &mut BTreeMap<String, NodeBuilder>,
components: &[&str],
max_depth: Option<usize>,
current_depth: usize,
) {
match components {
[] => {}
[name] => {
dir.insert(name.to_string(), NodeBuilder::File);
}
[name, rest @ ..] => {
if let Some(max) = max_depth {
if current_depth >= max {
dir.entry(name.to_string())
.or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
return;
}
}
let child = dir
.entry(name.to_string())
.or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
if let NodeBuilder::Dir(children) = child {
insert(children, rest, max_depth, current_depth + 1);
}
}
}
}
fn insert_stub(dir: &mut BTreeMap<String, NodeBuilder>, components: &[&str]) {
match components {
[] => {}
[name] => {
dir.entry(name.to_string())
.or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
}
[name, rest @ ..] => {
let child = dir
.entry(name.to_string())
.or_insert_with(|| NodeBuilder::Dir(BTreeMap::new()));
if let NodeBuilder::Dir(children) = child {
insert_stub(children, rest);
}
}
}
}
fn convert(name: String, node: NodeBuilder) -> TreeNode {
match node {
NodeBuilder::File => TreeNode::File { name },
NodeBuilder::Dir(children) => {
let mut dirs: Vec<TreeNode> = Vec::new();
let mut files: Vec<TreeNode> = Vec::new();
for (child_name, child_node) in children {
match child_node {
NodeBuilder::Dir(_) => dirs.push(convert(child_name, child_node)),
NodeBuilder::File => files.push(convert(child_name, child_node)),
}
}
TreeNode::Directory {
name,
children: dirs.into_iter().chain(files).collect(),
}
}
}
}
let mut root: BTreeMap<String, NodeBuilder> = BTreeMap::new();
for path in flat {
let components: Vec<&str> = path.split('/').collect();
insert(&mut root, &components, max_depth, 1);
}
for stub_path in stubs {
let components: Vec<&str> = stub_path.split('/').collect();
insert_stub(&mut root, &components);
}
let mut dirs: Vec<TreeNode> = Vec::new();
let mut files: Vec<TreeNode> = Vec::new();
for (name, node) in root {
match node {
NodeBuilder::Dir(_) => dirs.push(convert(name, node)),
NodeBuilder::File => files.push(convert(name, node)),
}
}
dirs.into_iter().chain(files).collect()
}
}
struct WorkingTree<'a> {
root: &'a Path,
enabled: bool,
}
impl<'a> WorkingTree<'a> {
fn new(root: &'a Path, enabled: bool) -> Self {
Self { root, enabled }
}
fn write(&self, relative_path: impl AsRef<Path>, content: &[u8]) -> Result<(), AppError> {
if !self.enabled {
return Ok(());
}
let absolute_path = self.root.join(relative_path);
if let Some(parent_dir) = absolute_path.parent() {
std::fs::create_dir_all(parent_dir)?;
}
std::fs::write(&absolute_path, content)?;
Ok(())
}
fn remove_file(&self, relative_path: impl AsRef<Path>) -> Result<(), AppError> {
if !self.enabled {
return Ok(());
}
match std::fs::remove_file(self.root.join(relative_path)) {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(AppError::Io(err)),
}
}
fn remove_directory(&self, relative_path: impl AsRef<Path>) -> Result<(), AppError> {
if !self.enabled {
return Ok(());
}
match std::fs::remove_dir_all(self.root.join(relative_path)) {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(AppError::Io(err)),
}
}
}
pub struct GitLocks;
impl GitLocks {
pub fn cleanup_stale_index_lock(repo_path: &Path) -> Result<(), AppError> {
const STALE_LOCK_THRESHOLD_SECS: u64 = 30;
let lock_path = repo_path.join(".git").join("index.lock");
let metadata = match std::fs::metadata(&lock_path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(err) => return Err(AppError::Io(err)),
};
let modified_time = metadata.modified()?;
let lock_age = std::time::SystemTime::now()
.duration_since(modified_time)
.unwrap_or_default();
if lock_age.as_secs() > STALE_LOCK_THRESHOLD_SECS {
tracing::warn!(
"Removing stale git lock file at {:?} (age: {}s)",
lock_path,
lock_age.as_secs()
);
if let Err(err) = std::fs::remove_file(&lock_path) {
if err.kind() != std::io::ErrorKind::NotFound {
return Err(AppError::Io(err));
}
}
}
Ok(())
}
pub fn cleanup_all_stale_locks(repos_root: &Path) {
let collections_dir = match std::fs::read_dir(repos_root) {
Ok(d) => d,
Err(_) => return,
};
for collection_entry_result in collections_dir {
let Ok(collection_entry) = collection_entry_result else {
continue;
};
let collection_path = collection_entry.path();
if !collection_path.is_dir() {
continue;
}
let tenants_dir = match std::fs::read_dir(&collection_path) {
Ok(d) => d,
Err(_) => continue,
};
for tenant_entry_result in tenants_dir {
let Ok(tenant_entry) = tenant_entry_result else {
continue;
};
let lock_path = tenant_entry.path().join(".git").join("index.lock");
if lock_path.exists() {
tracing::warn!(
"Removing stale git lock file found on startup: {:?}",
lock_path
);
if let Err(remove_err) = std::fs::remove_file(&lock_path) {
tracing::error!(
"Failed to remove stale lock {:?}: {}",
lock_path,
remove_err
);
}
}
}
}
}
}
const STAGING_CREATING: &str = "creating";
const STAGING_DELETING: &str = "deleting";
static STAGING_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub struct GitStaging;
impl GitStaging {
fn sibling(repo_path: &Path, purpose: &str) -> Result<PathBuf, AppError> {
let (Some(parent), Some(name)) = (
repo_path.parent(),
repo_path.file_name().and_then(|name| name.to_str()),
) else {
return Err(AppError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("not a tenant repository path: {}", repo_path.display()),
)));
};
let sequence = STAGING_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(parent.join(format!(".{}.{}-{}", name, purpose, sequence)))
}
fn is_staging_name(name: &str) -> bool {
let Some((tenant, suffix)) = name
.strip_prefix('.')
.and_then(|rest| rest.rsplit_once('.'))
else {
return false;
};
let Some((purpose, sequence)) = suffix.split_once('-') else {
return false;
};
validate::tenant_id(tenant).is_ok()
&& (purpose == STAGING_CREATING || purpose == STAGING_DELETING)
&& !sequence.is_empty()
&& sequence.bytes().all(|byte| byte.is_ascii_digit())
}
fn discard(path: &Path) {
match std::fs::remove_dir_all(path) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => {
tracing::warn!(
path = %path.display(),
err = %err,
"cannot remove staging directory, it is cleared at the next start"
);
}
}
}
pub fn create<T>(
repo_path: &Path,
build: impl FnOnce(&Path) -> Result<T, AppError>,
) -> Result<T, AppError> {
let staging = Self::sibling(repo_path, STAGING_CREATING)?;
if let Some(parent) = staging.parent() {
std::fs::create_dir_all(parent)?;
}
Self::discard(&staging);
std::fs::create_dir(&staging)?;
let outcome = build(&staging).and_then(|value| {
std::fs::rename(&staging, repo_path)?;
Ok(value)
});
if outcome.is_err() {
Self::discard(&staging);
}
outcome
}
pub fn remove(repo_path: &Path) -> Result<(), AppError> {
let trash = Self::sibling(repo_path, STAGING_DELETING)?;
Self::discard(&trash);
std::fs::rename(repo_path, &trash)?;
Self::discard(&trash);
Ok(())
}
pub fn cleanup_abandoned(repos_root: &Path) {
let Ok(collections) = std::fs::read_dir(repos_root) else {
return;
};
for collection_entry in collections.flatten() {
let collection_path = collection_entry.path();
if !collection_path.is_dir() {
continue;
}
let Ok(tenants) = std::fs::read_dir(&collection_path) else {
continue;
};
for tenant_entry in tenants.flatten() {
let name = tenant_entry.file_name();
if !name.to_str().is_some_and(Self::is_staging_name) {
continue;
}
let path = tenant_entry.path();
tracing::warn!(
path = %path.display(),
"removing tenant staging directory abandoned by a previous process"
);
Self::discard(&path);
}
}
}
}
#[derive(Debug, Default)]
pub struct MaintenanceReport {
pub packed_objects: usize,
pub loose_objects_removed: usize,
pub old_packs_removed: usize,
}
pub struct GitMaintenance;
impl GitMaintenance {
pub fn run(
repo_path: &Path,
destructive_prune: bool,
checkout_files: bool,
) -> Result<MaintenanceReport, AppError> {
if !repo_path.join(".git").exists() {
tracing::debug!(path = %repo_path.display(), "repository gone, skipping maintenance");
return Ok(MaintenanceReport::default());
}
let repo = Repository::open(repo_path)?;
Self::expire_reflogs(&repo);
let loose_objects = Self::enumerate_loose_objects(repo_path)?;
let packs_before = Self::enumerate_pack_stems(repo_path)?;
tracing::debug!(
path = %repo_path.display(),
loose_objects = loose_objects.len(),
packs = packs_before.len(),
destructive_prune = destructive_prune,
"running repository maintenance"
);
let report = if loose_objects.is_empty() && packs_before.len() <= 1 {
MaintenanceReport::default()
} else {
Self::repack(
&repo,
repo_path,
destructive_prune,
&loose_objects,
&packs_before,
)?
};
if checkout_files {
GitLocks::cleanup_stale_index_lock(repo_path)?;
let head_tree = repo.head()?.peel_to_commit()?.tree()?;
let mut index = repo.index()?;
index.read_tree(&head_tree)?;
index.write()?;
}
Ok(report)
}
fn repack(
repo: &Repository,
repo_path: &Path,
destructive_prune: bool,
loose_objects: &[(Oid, PathBuf)],
packs_before: &HashSet<PathBuf>,
) -> Result<MaintenanceReport, AppError> {
let odb = repo.odb()?;
let mut pack_builder = repo.packbuilder()?;
if destructive_prune {
Self::insert_reachable_objects(repo, &mut pack_builder)?;
} else {
odb.foreach(|oid| pack_builder.insert_object(*oid, None).is_ok())?;
}
let mut pack_writer = odb.packwriter()?;
pack_builder.foreach(|chunk| {
use std::io::Write;
pack_writer.write_all(chunk).is_ok()
})?;
pack_writer.commit()?;
let mut report = MaintenanceReport {
packed_objects: pack_builder.object_count(),
..Default::default()
};
for (_, loose_path) in loose_objects {
let _ = std::fs::remove_file(loose_path);
}
report.loose_objects_removed = loose_objects.len();
let fanout_dirs: HashSet<PathBuf> = loose_objects
.iter()
.filter_map(|(_, loose_path)| loose_path.parent().map(PathBuf::from))
.collect();
for fanout_dir in fanout_dirs {
let _ = std::fs::remove_dir(fanout_dir);
}
let packs_after = Self::enumerate_pack_stems(repo_path)?;
let new_pack_appeared = packs_after.difference(packs_before).next().is_some();
if new_pack_appeared {
for stem in packs_before {
for extension in ["pack", "idx", "rev", "mtimes", "keep", "bitmap"] {
let _ = std::fs::remove_file(stem.with_extension(extension));
}
report.old_packs_removed += 1;
}
}
Ok(report)
}
fn insert_reachable_objects(
repo: &Repository,
pack_builder: &mut git2::PackBuilder<'_>,
) -> Result<(), AppError> {
let mut revwalk = repo.revwalk()?;
revwalk.push_head()?;
for reference in repo.references()?.flatten() {
if let Ok(name) = reference.name() {
let _ = revwalk.push_ref(name);
}
if let Some(oid) = reference.target() {
if let Ok(object) = repo.find_object(oid, None) {
if object.kind() == Some(git2::ObjectType::Tag) {
let _ = pack_builder.insert_object(oid, None);
}
}
}
}
pack_builder.insert_walk(&mut revwalk)?;
Ok(())
}
fn expire_reflogs(repo: &Repository) {
let branch_ref_name = repo
.head()
.ok()
.and_then(|head_ref| head_ref.name().ok().map(str::to_owned));
let _ = repo.reflog_delete("HEAD");
if let Some(name) = branch_ref_name {
tracing::trace!(reference = %name, "expiring reflog");
let _ = repo.reflog_delete(&name);
}
}
pub fn pack_count(repo_path: &Path) -> usize {
Self::enumerate_pack_stems(repo_path)
.map(|stems| stems.len())
.unwrap_or(0)
}
fn enumerate_pack_stems(repo_path: &Path) -> Result<HashSet<PathBuf>, AppError> {
let pack_dir = repo_path.join(".git").join("objects").join("pack");
let mut stems: HashSet<PathBuf> = HashSet::new();
let entries = match std::fs::read_dir(&pack_dir) {
Ok(entries) => entries,
Err(_) => return Ok(stems),
};
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|extension| extension.to_str()) == Some("pack") {
stems.insert(path.with_extension(""));
}
}
Ok(stems)
}
fn enumerate_loose_objects(repo_path: &Path) -> Result<Vec<(Oid, PathBuf)>, AppError> {
let objects_dir = repo_path.join(".git").join("objects");
let mut loose_objects: Vec<(Oid, PathBuf)> = Vec::new();
let fanout_entries = match std::fs::read_dir(&objects_dir) {
Ok(entries) => entries,
Err(_) => return Ok(loose_objects),
};
for fanout_entry in fanout_entries.flatten() {
let fanout_name = fanout_entry.file_name();
let Some(prefix) = fanout_name.to_str() else {
continue;
};
if prefix.len() != 2 || !prefix.bytes().all(|byte| byte.is_ascii_hexdigit()) {
continue;
}
let Ok(object_entries) = std::fs::read_dir(fanout_entry.path()) else {
continue;
};
for object_entry in object_entries.flatten() {
let object_name = object_entry.file_name();
let Some(suffix) = object_name.to_str() else {
continue;
};
if let Ok(oid) = Oid::from_str(&format!("{}{}", prefix, suffix)) {
loose_objects.push((oid, object_entry.path()));
}
}
}
Ok(loose_objects)
}
}
pub struct GitFiles;
impl GitFiles {
#[allow(clippy::too_many_arguments)]
pub fn list_files(
repo_path: &Path,
tenant_id: &str,
path_prefix: Option<&str>,
maximum_depth: Option<usize>,
include_hidden_files: bool,
file_name_starts_with: Option<&[String]>,
date_filter: Option<DateFilter>,
order_options: Option<OrderOptions>,
page: usize,
per_page: usize,
) -> Result<(Vec<TreeNode>, bool), AppError> {
tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, file_name_starts_with = ?file_name_starts_with, date_filter = ?date_filter, order_options = ?order_options, page = page, per_page = per_page, "listing files");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_commit = repo.head()?.peel_to_commit()?;
tracing::trace!(tenant_id = %tenant_id, head_sha = %head_commit.id(), "resolved HEAD for file listing");
let head_tree = head_commit.tree()?;
let walk_tree: git2::Tree<'_> = match path_prefix.filter(|p| !p.is_empty()) {
Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
Ok(entry) => match repo.find_tree(entry.id()) {
Ok(tree) => tree,
Err(_) => return Ok((vec![], false)),
},
Err(_) => return Ok((vec![], false)),
},
None => head_tree,
};
if let Some(needles) = file_name_starts_with {
return Self::search_by_file_name(
&repo,
&walk_tree,
path_prefix,
needles,
maximum_depth,
include_hidden_files,
date_filter,
order_options,
page,
per_page,
);
}
if let Some(date_filter) = date_filter {
return Self::list_with_date_filter(
&repo,
&walk_tree,
path_prefix,
maximum_depth,
include_hidden_files,
date_filter,
order_options,
page,
per_page,
);
}
let mut root_dirs: Vec<(String, Oid)> = Vec::new();
let mut root_files: Vec<String> = Vec::new();
for entry in walk_tree.iter() {
let Ok(name) = entry.name() else {
continue;
};
if !include_hidden_files && name.starts_with('.') {
continue;
}
match entry.kind() {
Some(git2::ObjectType::Tree) => root_dirs.push((name.to_string(), entry.id())),
Some(git2::ObjectType::Blob) if name != order::ORDER_FILE_NAME => {
root_files.push(name.to_string())
}
_ => {}
}
}
root_dirs.sort_by(|left, right| left.0.cmp(&right.0));
root_files.sort();
let total = root_dirs.len() + root_files.len();
let offset = ((page - 1) * per_page).min(total);
let has_more = total > offset + per_page;
enum RootEntry {
Directory(String, Oid),
File(String),
}
let mut root_entries: Vec<RootEntry> = root_dirs
.into_iter()
.map(|(name, oid)| RootEntry::Directory(name, oid))
.chain(root_files.into_iter().map(RootEntry::File))
.collect();
if let Some(order_options) = order_options {
if let Some(order) = GitOrder::stored_order(&repo, &walk_tree, "") {
let ranks = Self::order_ranks(&order);
root_entries.sort_by_key(|root_entry| {
let name = match root_entry {
RootEntry::Directory(name, _oid) => name.as_str(),
RootEntry::File(name) => name.as_str(),
};
Self::order_rank(&ranks, name, &order_options)
});
}
}
let page_entries: Vec<RootEntry> = root_entries
.into_iter()
.skip(offset)
.take(per_page)
.collect();
let mut nodes: Vec<TreeNode> = Vec::with_capacity(page_entries.len());
for root_entry in page_entries {
match root_entry {
RootEntry::File(name) => nodes.push(TreeNode::File { name }),
RootEntry::Directory(name, oid) => {
if maximum_depth == Some(1) {
nodes.push(TreeNode::Directory {
name,
children: Vec::new(),
});
continue;
}
let subtree = repo.find_tree(oid)?;
let subtree_max_depth = maximum_depth.map(|max| max - 1);
let children =
Self::collect_subtree(&subtree, subtree_max_depth, include_hidden_files)?;
nodes.push(TreeNode::Directory { name, children });
}
}
}
if let Some(order_options) = order_options {
for node in nodes.iter_mut() {
if let TreeNode::Directory { name, children } = node {
Self::apply_order(&repo, &walk_tree, name, children, &order_options);
}
}
}
tracing::debug!(tenant_id = %tenant_id, page = page, returned = nodes.len(), has_more = has_more, "file listing complete");
Ok((nodes, has_more))
}
fn order_ranks(order: &[String]) -> HashMap<&str, i64> {
let mut ranks: HashMap<&str, i64> = HashMap::with_capacity(order.len());
for (position, entry) in order.iter().enumerate() {
ranks
.entry(order::entry_name(entry))
.or_insert(position as i64);
}
ranks
}
fn order_rank(
ranks: &HashMap<&str, i64>,
name: &str,
order_options: &OrderOptions,
) -> OrderRank {
match ranks.get(name) {
Some(position) => (*position, true),
None => (
order_options.implicit_default_index.unwrap_or(i64::MAX),
false,
),
}
}
fn apply_order(
repo: &Repository,
base_tree: &git2::Tree<'_>,
directory: &str,
nodes: &mut [TreeNode],
order_options: &OrderOptions,
) {
if nodes.is_empty() {
return;
}
if let Some(order) = GitOrder::stored_order(repo, base_tree, directory) {
let ranks = Self::order_ranks(&order);
nodes.sort_by_key(|node| Self::order_rank(&ranks, node.name(), order_options));
}
for node in nodes.iter_mut() {
if let TreeNode::Directory { name, children } = node {
let child_directory = if directory.is_empty() {
name.clone()
} else {
format!("{}/{}", directory, name)
};
Self::apply_order(repo, base_tree, &child_directory, children, order_options);
}
}
}
fn collect_subtree(
subtree: &git2::Tree<'_>,
max_depth: Option<usize>,
include_hidden_files: bool,
) -> Result<Vec<TreeNode>, AppError> {
let mut flat: Vec<String> = Vec::new();
let mut dir_stubs: Vec<String> = Vec::new();
subtree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
return if entry.kind() == Some(git2::ObjectType::Tree) {
git2::TreeWalkResult::Skip
} else {
git2::TreeWalkResult::Ok
};
}
let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;
if entry.kind() == Some(git2::ObjectType::Tree) {
if let Some(max) = max_depth {
if entry_depth >= max {
let name = entry.name().unwrap_or("");
dir_stubs.push(format!("{}{}", root, name));
return git2::TreeWalkResult::Skip;
}
}
return git2::TreeWalkResult::Ok;
}
if entry.kind() != Some(git2::ObjectType::Blob) {
return git2::TreeWalkResult::Ok;
}
let name = entry.name().unwrap_or("");
if name == order::ORDER_FILE_NAME {
return git2::TreeWalkResult::Ok;
}
flat.push(format!("{}{}", root, name));
git2::TreeWalkResult::Ok
})?;
Ok(GitUtils::build_tree(flat, dir_stubs, max_depth))
}
#[allow(clippy::too_many_arguments)]
fn search_by_file_name(
repo: &Repository,
walk_tree: &git2::Tree<'_>,
path_prefix: Option<&str>,
needles: &[String],
maximum_depth: Option<usize>,
include_hidden_files: bool,
date_filter: Option<DateFilter>,
order_options: Option<OrderOptions>,
page: usize,
per_page: usize,
) -> Result<(Vec<TreeNode>, bool), AppError> {
let needles: Vec<String> = needles.iter().map(|needle| needle.to_lowercase()).collect();
let mut flat: Vec<String> = Vec::new();
let mut dir_stubs: Vec<String> = Vec::new();
let mut inside_matched: Option<String> = None;
walk_tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
if let Some(prefix) = &inside_matched {
if !root.starts_with(prefix.as_str()) {
inside_matched = None;
}
}
if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
return if entry.kind() == Some(git2::ObjectType::Tree) {
git2::TreeWalkResult::Skip
} else {
git2::TreeWalkResult::Ok
};
}
let Ok(name) = entry.name() else {
return git2::TreeWalkResult::Ok;
};
let full_path = format!("{}{}", root, name);
let in_matched = inside_matched.is_some();
let lower_name = name.to_lowercase();
let self_matches = needles.iter().any(|needle| lower_name.starts_with(needle));
match entry.kind() {
Some(git2::ObjectType::Tree) => {
let matched = in_matched || self_matches;
if let Some(max) = maximum_depth {
let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;
if entry_depth >= max {
if matched {
dir_stubs.push(full_path);
}
return git2::TreeWalkResult::Skip;
}
}
if self_matches && !in_matched {
inside_matched = Some(format!("{}/", full_path));
dir_stubs.push(full_path);
}
}
Some(git2::ObjectType::Blob)
if name != order::ORDER_FILE_NAME && (in_matched || self_matches) =>
{
flat.push(full_path);
}
_ => {}
}
git2::TreeWalkResult::Ok
})?;
let (flat, dir_stubs) = match date_filter {
Some(date_filter) => (
Self::retain_by_date(repo, path_prefix, flat, date_filter)?,
Vec::new(),
),
None => (flat, dir_stubs),
};
let mut tree = GitUtils::build_tree(flat, dir_stubs, None);
if let Some(order_options) = order_options {
Self::apply_order(repo, walk_tree, "", &mut tree, &order_options);
}
let total = tree.len();
let offset = ((page - 1) * per_page).min(total);
let has_more = total > offset + per_page;
let nodes: Vec<TreeNode> = tree.into_iter().skip(offset).take(per_page).collect();
Ok((nodes, has_more))
}
#[allow(clippy::too_many_arguments)]
fn list_with_date_filter(
repo: &Repository,
walk_tree: &git2::Tree<'_>,
path_prefix: Option<&str>,
maximum_depth: Option<usize>,
include_hidden_files: bool,
date_filter: DateFilter,
order_options: Option<OrderOptions>,
page: usize,
per_page: usize,
) -> Result<(Vec<TreeNode>, bool), AppError> {
let flat = Self::collect_flat_files(walk_tree, maximum_depth, include_hidden_files)?;
let matched = Self::retain_by_date(repo, path_prefix, flat, date_filter)?;
let mut tree = GitUtils::build_tree(matched, Vec::new(), None);
if let Some(order_options) = order_options {
Self::apply_order(repo, walk_tree, "", &mut tree, &order_options);
}
let total = tree.len();
let offset = ((page - 1) * per_page).min(total);
let has_more = total > offset + per_page;
let nodes: Vec<TreeNode> = tree.into_iter().skip(offset).take(per_page).collect();
Ok((nodes, has_more))
}
fn collect_flat_files(
tree: &git2::Tree<'_>,
max_depth: Option<usize>,
include_hidden_files: bool,
) -> Result<Vec<String>, AppError> {
let mut flat: Vec<String> = Vec::new();
tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
return if entry.kind() == Some(git2::ObjectType::Tree) {
git2::TreeWalkResult::Skip
} else {
git2::TreeWalkResult::Ok
};
}
if entry.kind() == Some(git2::ObjectType::Tree) {
if let Some(max) = max_depth {
let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;
if entry_depth >= max {
return git2::TreeWalkResult::Skip;
}
}
return git2::TreeWalkResult::Ok;
}
if entry.kind() == Some(git2::ObjectType::Blob) {
let name = entry.name().unwrap_or("");
if name != order::ORDER_FILE_NAME {
flat.push(format!("{}{}", root, name));
}
}
git2::TreeWalkResult::Ok
})?;
Ok(flat)
}
fn retain_by_date(
repo: &Repository,
path_prefix: Option<&str>,
flat: Vec<String>,
date_filter: DateFilter,
) -> Result<Vec<String>, AppError> {
let to_full = |leaf: &str| -> String {
match path_prefix {
Some(prefix) if !prefix.is_empty() => format!("{}/{}", prefix, leaf),
_ => leaf.to_string(),
}
};
let full_paths: HashSet<String> = flat.iter().map(|leaf| to_full(leaf)).collect();
if full_paths.is_empty() {
return Ok(Vec::new());
}
let dates = Self::file_dates(repo, &full_paths, date_filter.kind)?;
Ok(flat
.into_iter()
.filter(|leaf| {
dates
.get(&to_full(leaf))
.is_some_and(|date| date_filter.matches(*date))
})
.collect())
}
fn file_dates(
repo: &Repository,
paths: &HashSet<String>,
kind: DateKind,
) -> Result<HashMap<String, DateTime<Utc>>, AppError> {
let mut dates: HashMap<String, DateTime<Utc>> = HashMap::new();
let mut revwalk = repo.revwalk()?;
revwalk.push_head()?;
revwalk.set_sorting(Sort::TIME | Sort::TOPOLOGICAL)?;
for oid_result in revwalk {
if matches!(kind, DateKind::Updated) && dates.len() == paths.len() {
break;
}
let Ok(oid) = oid_result else {
continue;
};
let Ok(commit) = repo.find_commit(oid) else {
continue;
};
let Ok(commit_tree) = commit.tree() else {
continue;
};
let parent_tree = commit.parent(0).and_then(|parent| parent.tree()).ok();
let mut diff_options = DiffOptions::new();
diff_options.include_untracked(false);
let diff = match repo.diff_tree_to_tree(
parent_tree.as_ref(),
Some(&commit_tree),
Some(&mut diff_options),
) {
Ok(diff) => diff,
Err(_) => continue,
};
let commit_time = GitUtils::timestamp_from_git_time(commit.time());
for delta in diff.deltas() {
let Some(path) = delta
.new_file()
.path()
.or_else(|| delta.old_file().path())
.map(|path| path.to_string_lossy().into_owned())
else {
continue;
};
if !paths.contains(&path) {
continue;
}
match kind {
DateKind::Updated => {
dates.entry(path).or_insert(commit_time);
}
DateKind::Created => {
if delta.status() == Delta::Added {
dates.insert(path, commit_time);
}
}
}
}
}
Ok(dates)
}
pub fn count_files(
repo_path: &Path,
tenant_id: &str,
path_prefix: Option<&str>,
maximum_depth: Option<usize>,
include_hidden_files: bool,
restrict_file_extensions: Option<&[String]>,
) -> Result<FileCounts, AppError> {
tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, maximum_depth = ?maximum_depth, include_hidden_files = include_hidden_files, restrict_file_extensions = ?restrict_file_extensions, "counting files");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_commit = repo.head()?.peel_to_commit()?;
tracing::trace!(tenant_id = %tenant_id, head_sha = %head_commit.id(), "resolved HEAD for file counting");
let head_tree = head_commit.tree()?;
let walk_tree: git2::Tree<'_> = match path_prefix.filter(|p| !p.is_empty()) {
Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
Ok(entry) => match repo.find_tree(entry.id()) {
Ok(tree) => tree,
Err(_) => return Ok(FileCounts::default()),
},
Err(_) => return Ok(FileCounts::default()),
},
None => head_tree,
};
let mut counts = FileCounts::default();
walk_tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
return if entry.kind() == Some(git2::ObjectType::Tree) {
git2::TreeWalkResult::Skip
} else {
git2::TreeWalkResult::Ok
};
}
match entry.kind() {
Some(git2::ObjectType::Tree) => {
counts.directories += 1;
if let Some(max) = maximum_depth {
let entry_depth = root.chars().filter(|c| *c == '/').count() + 1;
if entry_depth >= max {
return git2::TreeWalkResult::Skip;
}
}
}
Some(git2::ObjectType::Blob)
if entry
.name()
.is_ok_and(|name| name == order::ORDER_FILE_NAME) => {}
Some(git2::ObjectType::Blob) => {
let counted = match restrict_file_extensions {
None => true,
Some(allowed) => entry
.name()
.ok()
.and_then(|name| Path::new(name).extension())
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
allowed
.iter()
.any(|entry| entry.eq_ignore_ascii_case(extension))
}),
};
if counted {
counts.files += 1;
}
}
_ => {}
}
git2::TreeWalkResult::Ok
})?;
tracing::debug!(tenant_id = %tenant_id, files = counts.files, directories = counts.directories, "file counting complete");
Ok(counts)
}
pub fn read_file(
repo_path: &Path,
tenant_id: &str,
file_path: &str,
seek: &SeekFilter,
) -> Result<FileRead, AppError> {
tracing::debug!(tenant_id = %tenant_id, path = %file_path, "reading file");
if order::is_order_file(file_path) {
return Err(AppError::FileNotFound {
path: file_path.to_string(),
});
}
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_commit = repo.head()?.peel_to_commit()?;
tracing::trace!(tenant_id = %tenant_id, path = %file_path, head_sha = %head_commit.id(), "resolved HEAD for read");
let head_tree = head_commit.tree()?;
let blob_oid = GitUtils::blob_oid_in_tree(&head_tree, file_path).ok_or_else(|| {
AppError::FileNotFound {
path: file_path.to_string(),
}
})?;
let content = GitUtils::windowed_blob_content(&repo, blob_oid, file_path, seek)?;
let (directory, name) = order::split_parent(file_path);
let position = GitOrder::entry_position(&repo, &head_tree, directory, name);
Ok(FileRead { content, position })
}
pub fn batch_read_files(
repo_path: &Path,
tenant_id: &str,
file_reads: &[(String, SeekFilter)],
) -> Result<Vec<Option<String>>, AppError> {
tracing::debug!(tenant_id = %tenant_id, count = file_reads.len(), "batch reading files");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_commit = repo.head()?.peel_to_commit()?;
tracing::trace!(tenant_id = %tenant_id, head_sha = %head_commit.id(), "resolved HEAD for batch read");
let head_tree = head_commit.tree()?;
file_reads
.iter()
.map(|(file_path, seek)| {
if order::is_order_file(file_path) {
return Ok(None);
}
match GitUtils::blob_oid_in_tree(&head_tree, file_path) {
None => Ok(None),
Some(blob_oid) => {
GitUtils::windowed_blob_content(&repo, blob_oid, file_path, seek).map(Some)
}
}
})
.collect()
}
pub fn list_all_file_paths(
repo_path: &Path,
tenant_id: &str,
path_prefix: Option<&str>,
include_hidden_files: bool,
) -> Result<(String, Vec<String>), AppError> {
tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, include_hidden_files = include_hidden_files, "listing all file paths");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_commit = repo.head()?.peel_to_commit()?;
let head_sha = head_commit.id().to_string();
let head_tree = head_commit.tree()?;
let prefix = path_prefix.filter(|prefix| !prefix.is_empty());
let walk_tree: git2::Tree<'_> = match prefix {
Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
Ok(entry) => match repo.find_tree(entry.id()) {
Ok(tree) => tree,
Err(_not_a_directory) => return Ok((head_sha, Vec::new())),
},
Err(_absent) => return Ok((head_sha, Vec::new())),
},
None => head_tree,
};
let flat = Self::collect_flat_files(&walk_tree, None, include_hidden_files)?;
let paths = match prefix {
Some(prefix) => flat
.into_iter()
.map(|leaf| format!("{}/{}", prefix, leaf))
.collect(),
None => flat,
};
tracing::debug!(tenant_id = %tenant_id, file_count = paths.len(), head_sha = %head_sha, "collected file paths");
Ok((head_sha, paths))
}
pub fn replay_read_files(
repo_path: &Path,
tenant_id: &str,
paths: &[String],
) -> Result<Vec<Option<String>>, AppError> {
tracing::trace!(tenant_id = %tenant_id, count = paths.len(), "reading replay chunk");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_tree = repo.head()?.peel_to_commit()?.tree()?;
let contents = paths
.iter()
.map(|file_path| {
if order::is_order_file(file_path) {
return None;
}
let blob_oid = GitUtils::blob_oid_in_tree(&head_tree, file_path)?;
let blob = repo.find_blob(blob_oid).ok()?;
match std::str::from_utf8(blob.content()) {
Ok(text) => Some(text.to_string()),
Err(_not_utf8) => {
tracing::warn!(path = %file_path, "replay skipping file: content is not valid UTF-8");
None
}
}
})
.collect();
Ok(contents)
}
pub fn path_kind(repo_path: &Path, tenant_id: &str, path: &str) -> Result<PathKind, AppError> {
tracing::debug!(tenant_id = %tenant_id, path = %path, "classifying path");
if order::is_order_file(path) {
return Ok(PathKind::Missing);
}
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_commit = repo.head()?.peel_to_commit()?;
tracing::trace!(tenant_id = %tenant_id, path = %path, head_sha = %head_commit.id(), "resolved HEAD for path classification");
let head_tree = head_commit.tree()?;
let kind = match head_tree.get_path(Path::new(path)) {
Ok(entry) => match entry.kind() {
Some(git2::ObjectType::Blob) => PathKind::File,
Some(git2::ObjectType::Tree) => PathKind::Directory,
_ => PathKind::Missing,
},
Err(_absent) => PathKind::Missing,
};
tracing::debug!(tenant_id = %tenant_id, path = %path, kind = ?kind, "path classified");
Ok(kind)
}
pub fn write_file(
repo_path: &Path,
file_path: &str,
content: &str,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Option<FileChange>), AppError> {
tracing::debug!(path = %file_path, author_name = %author_name, author_email = %author_email, "writing file");
if order::is_order_file(file_path) {
return Err(AppError::InvalidOperation {
reason: format!(
"path is reserved for the file order index, write it through /order instead: {}",
file_path
),
});
}
let repo = GitUtils::open_or_init_repo(repo_path, author_name, author_email)?;
let parent_commit = repo.head()?.peel_to_commit()?;
let head_tree = parent_commit.tree()?;
let is_new_file = match head_tree.get_path(Path::new(file_path)) {
Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => {
let incoming_oid =
git2::Oid::hash_object(git2::ObjectType::Blob, content.as_bytes())?;
if entry.id() == incoming_oid {
tracing::debug!(path = %file_path, "content unchanged, skipping commit");
return Ok((parent_commit.id().to_string(), None));
}
false
}
Ok(_) => {
return Err(AppError::InvalidOperation {
reason: format!("path is a folder: {}", file_path),
})
}
Err(_) => true,
};
tracing::debug!(path = %file_path, is_new_file = is_new_file, "staging file write");
WorkingTree::new(repo_path, checkout_files).write(file_path, content.as_bytes())?;
tracing::trace!(path = %file_path, "building updated tree");
let blob_oid = repo.blob(content.as_bytes())?;
let tree_id = TreeUpdateBuilder::new()
.upsert(file_path, blob_oid, FileMode::Blob)
.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = if is_new_file {
format!("create: {}", file_path)
} else {
format!("update: {}", file_path)
};
let message = commit_message.unwrap_or(&auto_message);
tracing::trace!(path = %file_path, message = %message, "committing file write");
let commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&parent_commit],
)?;
tracing::debug!(path = %file_path, sha = %commit_oid, is_new_file = is_new_file, "file write committed");
let change = if is_new_file {
FileChange::Created {
path: file_path.to_string(),
content: content.to_string(),
}
} else {
FileChange::Updated {
path: file_path.to_string(),
content: content.to_string(),
}
};
Ok((commit_oid.to_string(), Some(change)))
}
pub fn delete_file(
repo_path: &Path,
tenant_id: &str,
file_path: &str,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Vec<FileChange>), AppError> {
tracing::debug!(tenant_id = %tenant_id, path = %file_path, author_name = %author_name, author_email = %author_email, "deleting file");
if order::is_order_file(file_path) {
return Err(AppError::FileNotFound {
path: file_path.to_string(),
});
}
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let parent_commit = repo.head()?.peel_to_commit()?;
let head_tree = parent_commit.tree()?;
match head_tree.get_path(Path::new(file_path)) {
Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => {}
_ => {
tracing::debug!(tenant_id = %tenant_id, path = %file_path, "file not found for deletion");
return Err(AppError::FileNotFound {
path: file_path.to_string(),
});
}
}
tracing::trace!(tenant_id = %tenant_id, path = %file_path, "building updated tree without path");
WorkingTree::new(repo_path, checkout_files).remove_file(file_path)?;
let mut tree_update = TreeUpdateBuilder::new();
tree_update.remove(file_path);
let mut file_changes = vec![FileChange::Deleted {
path: file_path.to_string(),
}];
let (parent_directory, leaf_name) = order::split_parent(file_path);
file_changes.extend(GitOrder::stage_entry_removed(
&repo,
repo_path,
&head_tree,
&mut tree_update,
parent_directory,
leaf_name,
checkout_files,
)?);
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("delete: {}", file_path);
let message = commit_message.unwrap_or(&auto_message);
tracing::trace!(tenant_id = %tenant_id, path = %file_path, message = %message, "committing file deletion");
let commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&parent_commit],
)?;
tracing::debug!(tenant_id = %tenant_id, path = %file_path, sha = %commit_oid, change_count = file_changes.len(), "file deletion committed");
Ok((commit_oid.to_string(), file_changes))
}
pub fn delete_directory(
repo_path: &Path,
tenant_id: &str,
dir_path: &str,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Vec<FileChange>), AppError> {
tracing::debug!(tenant_id = %tenant_id, path = %dir_path, author_name = %author_name, author_email = %author_email, "deleting directory recursively");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let parent_commit = repo.head()?.peel_to_commit()?;
let head_tree = parent_commit.tree()?;
match head_tree.get_path(Path::new(dir_path)) {
Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) => {}
_ => {
tracing::debug!(tenant_id = %tenant_id, path = %dir_path, "directory not found for recursive deletion");
return Err(AppError::FileNotFound {
path: dir_path.to_string(),
});
}
}
let blobs = GitUtils::subtree_blob_paths(&repo, &head_tree, dir_path)?;
if blobs.is_empty() {
tracing::debug!(tenant_id = %tenant_id, path = %dir_path, "directory holds no files, skipping commit");
return Ok((parent_commit.id().to_string(), Vec::new()));
}
tracing::debug!(tenant_id = %tenant_id, path = %dir_path, file_count = blobs.len(), "staging recursive directory deletion");
WorkingTree::new(repo_path, checkout_files).remove_directory(dir_path)?;
let mut tree_update = TreeUpdateBuilder::new();
tree_update.remove(dir_path);
let mut file_changes: Vec<FileChange> = blobs
.iter()
.map(|(path, _oid)| FileChange::Deleted { path: path.clone() })
.collect();
let (parent_directory, dir_name) = order::split_parent(dir_path);
file_changes.extend(GitOrder::stage_entry_removed(
&repo,
repo_path,
&head_tree,
&mut tree_update,
parent_directory,
dir_name,
checkout_files,
)?);
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("delete: {}/", dir_path);
let message = commit_message.unwrap_or(&auto_message);
tracing::trace!(tenant_id = %tenant_id, path = %dir_path, message = %message, "committing recursive directory deletion");
let commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&parent_commit],
)?;
tracing::debug!(tenant_id = %tenant_id, path = %dir_path, sha = %commit_oid, change_count = file_changes.len(), "recursive directory deletion committed");
Ok((commit_oid.to_string(), file_changes))
}
#[allow(clippy::too_many_arguments)]
pub fn move_file(
repo_path: &Path,
tenant_id: &str,
from_path: &str,
to_path: &str,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Vec<FileChange>), AppError> {
tracing::debug!(
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
author_email = %author_email,
"moving file"
);
if order::is_order_file(from_path) {
return Err(AppError::FileNotFound {
path: from_path.to_string(),
});
}
if order::is_order_file(to_path) {
return Err(AppError::InvalidOperation {
reason: format!(
"destination is reserved for the file order index, write it through /order instead: {}",
to_path
),
});
}
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
if from_path == to_path {
tracing::debug!(tenant_id = %tenant_id, path = %from_path, "move rejected: source and destination are identical");
return Err(AppError::InvalidOperation {
reason: "destination must differ from source path".to_string(),
});
}
let parent_commit = repo.head()?.peel_to_commit()?;
let head_tree = parent_commit.tree()?;
let source_blob_oid = match head_tree.get_path(Path::new(from_path)) {
Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => entry.id(),
_ => {
tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, "source file not found for move");
return Err(AppError::FileNotFound {
path: from_path.to_string(),
});
}
};
if head_tree.get_path(Path::new(to_path)).is_ok() {
tracing::debug!(tenant_id = %tenant_id, to_path = %to_path, "move rejected: destination already exists");
return Err(AppError::InvalidOperation {
reason: format!("destination already exists: {}", to_path),
});
}
let content = GitUtils::blob_content_from_tree(&repo, &head_tree, from_path)?;
let working_tree = WorkingTree::new(repo_path, checkout_files);
working_tree.remove_file(from_path)?;
working_tree.write(to_path, content.as_bytes())?;
tracing::trace!(
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
"building updated tree for move"
);
let mut tree_update = TreeUpdateBuilder::new();
tree_update.remove(from_path);
tree_update.upsert(to_path, source_blob_oid, FileMode::Blob);
let mut file_changes = vec![FileChange::Moved {
from_path: from_path.to_string(),
to_path: to_path.to_string(),
content,
}];
let (from_directory, from_name) = order::split_parent(from_path);
let (to_directory, to_name) = order::split_parent(to_path);
if from_directory == to_directory {
file_changes.extend(GitOrder::stage_entry_renamed(
&repo,
repo_path,
&head_tree,
&mut tree_update,
from_directory,
from_name,
to_name,
checkout_files,
)?);
} else {
file_changes.extend(GitOrder::stage_entry_removed(
&repo,
repo_path,
&head_tree,
&mut tree_update,
from_directory,
from_name,
checkout_files,
)?);
file_changes.extend(GitOrder::stage_entry_appended(
&repo,
repo_path,
&head_tree,
&mut tree_update,
to_directory,
to_name,
checkout_files,
)?);
}
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("move: {} → {}", from_path, to_path);
let message = commit_message.unwrap_or(&auto_message);
tracing::trace!(
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
message = %message,
"committing file move"
);
let commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&parent_commit],
)?;
tracing::debug!(
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
sha = %commit_oid,
change_count = file_changes.len(),
"file move committed"
);
Ok((commit_oid.to_string(), file_changes))
}
#[allow(clippy::too_many_arguments)]
pub fn move_directory(
repo_path: &Path,
tenant_id: &str,
from_path: &str,
to_path: &str,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Vec<FileChange>), AppError> {
tracing::debug!(
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
author_email = %author_email,
"moving directory recursively"
);
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
if from_path == to_path {
tracing::debug!(tenant_id = %tenant_id, path = %from_path, "directory move rejected: source and destination are identical");
return Err(AppError::InvalidOperation {
reason: "destination must differ from source path".to_string(),
});
}
if to_path.starts_with(&format!("{}/", from_path)) {
tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, to_path = %to_path, "directory move rejected: destination is inside the source");
return Err(AppError::InvalidOperation {
reason: format!(
"destination must not be inside the source directory: {}",
to_path
),
});
}
let parent_commit = repo.head()?.peel_to_commit()?;
let head_tree = parent_commit.tree()?;
match head_tree.get_path(Path::new(from_path)) {
Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) => {}
_ => {
tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, "source directory not found for move");
return Err(AppError::FileNotFound {
path: from_path.to_string(),
});
}
}
if head_tree.get_path(Path::new(to_path)).is_ok() {
tracing::debug!(tenant_id = %tenant_id, to_path = %to_path, "directory move rejected: destination already exists");
return Err(AppError::InvalidOperation {
reason: format!("destination already exists: {}", to_path),
});
}
let blobs = GitUtils::subtree_blob_paths(&repo, &head_tree, from_path)?;
if blobs.is_empty() {
tracing::debug!(tenant_id = %tenant_id, from_path = %from_path, "source directory holds no files, skipping commit");
return Ok((parent_commit.id().to_string(), Vec::new()));
}
tracing::debug!(
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
file_count = blobs.len(),
"staging recursive directory move"
);
let working_tree = WorkingTree::new(repo_path, checkout_files);
let mut tree_update = TreeUpdateBuilder::new();
tree_update.remove(from_path);
let mut file_changes: Vec<FileChange> = Vec::with_capacity(blobs.len());
for (source_path, blob_oid) in &blobs {
let relative_path = source_path
.strip_prefix(from_path)
.and_then(|rest| rest.strip_prefix('/'))
.unwrap_or(source_path);
let destination_path = format!("{}/{}", to_path, relative_path);
let content = GitUtils::blob_content_from_tree(&repo, &head_tree, source_path)?;
working_tree.write(&destination_path, content.as_bytes())?;
tree_update.upsert(&destination_path, *blob_oid, FileMode::Blob);
file_changes.push(FileChange::Moved {
from_path: source_path.clone(),
to_path: destination_path,
content,
});
}
working_tree.remove_directory(from_path)?;
let (from_parent, from_name) = order::split_parent(from_path);
let (to_parent, to_name) = order::split_parent(to_path);
if from_parent == to_parent {
file_changes.extend(GitOrder::stage_entry_renamed(
&repo,
repo_path,
&head_tree,
&mut tree_update,
from_parent,
from_name,
&order::directory_entry(to_name),
checkout_files,
)?);
} else {
file_changes.extend(GitOrder::stage_entry_removed(
&repo,
repo_path,
&head_tree,
&mut tree_update,
from_parent,
from_name,
checkout_files,
)?);
file_changes.extend(GitOrder::stage_entry_appended(
&repo,
repo_path,
&head_tree,
&mut tree_update,
to_parent,
&order::directory_entry(to_name),
checkout_files,
)?);
}
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("move: {}/ → {}/", from_path, to_path);
let message = commit_message.unwrap_or(&auto_message);
tracing::trace!(
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
message = %message,
"committing recursive directory move"
);
let commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&parent_commit],
)?;
tracing::debug!(
tenant_id = %tenant_id,
from_path = %from_path,
to_path = %to_path,
sha = %commit_oid,
file_count = file_changes.len(),
"recursive directory move committed"
);
Ok((commit_oid.to_string(), file_changes))
}
}
pub struct GitOrder;
impl GitOrder {
pub fn read_order(
repo_path: &Path,
tenant_id: &str,
directory: &str,
) -> Result<Vec<String>, AppError> {
tracing::debug!(tenant_id = %tenant_id, directory = %order::display_directory(directory), "reading order index");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_tree = repo.head()?.peel_to_commit()?.tree()?;
Self::stored_order(&repo, &head_tree, directory).ok_or_else(|| AppError::OrderNotFound {
directory: order::display_directory(directory).to_string(),
})
}
pub fn list_order_directories(
repo_path: &Path,
tenant_id: &str,
path_prefix: Option<&str>,
include_hidden_files: bool,
) -> Result<Vec<String>, AppError> {
tracing::debug!(tenant_id = %tenant_id, path_prefix = ?path_prefix, include_hidden_files = include_hidden_files, "listing order index directories");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_tree = repo.head()?.peel_to_commit()?.tree()?;
let prefix = path_prefix.filter(|prefix| !prefix.is_empty());
let walk_tree: git2::Tree<'_> = match prefix {
Some(prefix) => match head_tree.get_path(Path::new(prefix)) {
Ok(entry) => match repo.find_tree(entry.id()) {
Ok(tree) => tree,
Err(_not_a_directory) => return Ok(Vec::new()),
},
Err(_absent) => return Ok(Vec::new()),
},
None => head_tree,
};
let mut directories: Vec<String> = Vec::new();
walk_tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {
if entry.kind() == Some(git2::ObjectType::Tree) {
if !include_hidden_files && entry.name().is_ok_and(|name| name.starts_with('.')) {
return git2::TreeWalkResult::Skip;
}
return git2::TreeWalkResult::Ok;
}
if entry.kind() == Some(git2::ObjectType::Blob)
&& entry
.name()
.is_ok_and(|name| name == order::ORDER_FILE_NAME)
{
directories.push(root.trim_end_matches('/').to_string());
}
git2::TreeWalkResult::Ok
})?;
let directories: Vec<String> = match prefix {
Some(prefix) => directories
.into_iter()
.map(|directory| {
if directory.is_empty() {
prefix.to_string()
} else {
format!("{}/{}", prefix, directory)
}
})
.collect(),
None => directories,
};
tracing::debug!(tenant_id = %tenant_id, directory_count = directories.len(), "collected order index directories");
Ok(directories)
}
pub fn replay_read_orders(
repo_path: &Path,
tenant_id: &str,
directories: &[String],
) -> Result<Vec<Option<Vec<String>>>, AppError> {
tracing::trace!(tenant_id = %tenant_id, count = directories.len(), "reading replay order chunk");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_tree = repo.head()?.peel_to_commit()?.tree()?;
Ok(directories
.iter()
.map(|directory| Self::stored_order(&repo, &head_tree, directory))
.collect())
}
#[allow(clippy::too_many_arguments)]
pub fn write_order(
repo_path: &Path,
tenant_id: &str,
directory: &str,
order_entries: &[String],
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Option<FileChange>), AppError> {
let display_directory = order::display_directory(directory);
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, entry_count = order_entries.len(), author_name = %author_name, author_email = %author_email, "writing order index");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let parent_commit = repo.head()?.peel_to_commit()?;
let head_tree = parent_commit.tree()?;
if !directory.is_empty() {
match head_tree.get_path(Path::new(directory)) {
Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) => {}
_ => {
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, "directory not found for order write");
return Err(AppError::FileNotFound {
path: directory.to_string(),
});
}
}
}
let mut canonical: Vec<String> = Vec::with_capacity(order_entries.len());
for entry in order_entries {
let name = order::entry_name(entry);
let entry_path = if directory.is_empty() {
name.to_string()
} else {
format!("{}/{}", directory, name)
};
match head_tree.get_path(Path::new(&entry_path)) {
Ok(tree_entry) if tree_entry.kind() == Some(git2::ObjectType::Blob) => {
canonical.push(name.to_string())
}
Ok(tree_entry) if tree_entry.kind() == Some(git2::ObjectType::Tree) => {
canonical.push(order::directory_entry(name))
}
_ => {
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, entry = %name, "order write rejected: entry does not exist");
return Err(AppError::InvalidOperation {
reason: format!(
"order entry does not exist in '{}': {}",
display_directory, name
),
});
}
}
}
let index_path = order::order_file_path(directory);
let existing_oid = GitUtils::blob_oid_in_tree(&head_tree, &index_path);
let incoming_oid = git2::Oid::hash_object(
git2::ObjectType::Blob,
order::serialize(&canonical).as_bytes(),
)?;
if existing_oid == Some(incoming_oid) {
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, "order unchanged, skipping commit");
return Ok((parent_commit.id().to_string(), None));
}
let mut tree_update = TreeUpdateBuilder::new();
let change = Self::stage_index(
&repo,
repo_path,
&mut tree_update,
directory,
&canonical,
existing_oid.is_some(),
checkout_files,
)?;
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("reorder: {}", display_directory);
let message = commit_message.unwrap_or(&auto_message);
let commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&parent_commit],
)?;
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, sha = %commit_oid, "order write committed");
Ok((commit_oid.to_string(), Some(change)))
}
#[allow(clippy::too_many_arguments)]
pub fn reorder_entry(
repo_path: &Path,
tenant_id: &str,
entry_path: &str,
position: OrderPosition,
implicit_default_index: Option<i64>,
implicit_allow_hidden_files: bool,
allow_prefix_path: bool,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Option<FileChange>), AppError> {
tracing::debug!(tenant_id = %tenant_id, path = %entry_path, position = ?position, implicit_default_index = ?implicit_default_index, implicit_allow_hidden_files = implicit_allow_hidden_files, allow_prefix_path = allow_prefix_path, author_name = %author_name, author_email = %author_email, "reordering order index entry");
if order::is_order_file(entry_path) {
return Err(AppError::FileNotFound {
path: entry_path.to_string(),
});
}
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let parent_commit = repo.head()?.peel_to_commit()?;
let head_tree = parent_commit.tree()?;
let (directory, name) = order::split_parent(entry_path);
let display_directory = order::display_directory(directory);
let canonical_entry = match head_tree.get_path(Path::new(entry_path)) {
Ok(entry) if entry.kind() == Some(git2::ObjectType::Blob) => name.to_string(),
Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) && allow_prefix_path => {
order::directory_entry(name)
}
_ => {
tracing::debug!(tenant_id = %tenant_id, path = %entry_path, allow_prefix_path = allow_prefix_path, "entry not found for reorder");
return Err(AppError::FileNotFound {
path: entry_path.to_string(),
});
}
};
let index_path = order::order_file_path(directory);
let existing_oid = GitUtils::blob_oid_in_tree(&head_tree, &index_path);
let stored = Self::stored_order(&repo, &head_tree, directory).unwrap_or_default();
let mut entries: Vec<String> = match position {
OrderPosition::At(_) => Self::materialized_order(
&repo,
&head_tree,
directory,
&stored,
implicit_default_index,
implicit_allow_hidden_files,
)?,
OrderPosition::Unlisted => stored,
};
entries.retain(|entry| order::entry_name(entry) != name);
let inserted_at = match position {
OrderPosition::At(position) => {
let position = position.min(entries.len());
entries.insert(position, canonical_entry);
Some(position)
}
OrderPosition::Unlisted => None,
};
let unchanged = if entries.is_empty() {
existing_oid.is_none()
} else {
let incoming_oid = git2::Oid::hash_object(
git2::ObjectType::Blob,
order::serialize(&entries).as_bytes(),
)?;
existing_oid == Some(incoming_oid)
};
if unchanged {
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, "order unchanged, skipping commit");
return Ok((parent_commit.id().to_string(), None));
}
let mut tree_update = TreeUpdateBuilder::new();
let change = Self::stage_index(
&repo,
repo_path,
&mut tree_update,
directory,
&entries,
existing_oid.is_some(),
checkout_files,
)?;
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("reorder: {}", entry_path);
let message = commit_message.unwrap_or(&auto_message);
let commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&parent_commit],
)?;
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, position = ?inserted_at, sha = %commit_oid, "order reorder committed");
Ok((commit_oid.to_string(), Some(change)))
}
pub fn delete_order(
repo_path: &Path,
tenant_id: &str,
directory: &str,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, FileChange), AppError> {
let display_directory = order::display_directory(directory);
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, author_name = %author_name, author_email = %author_email, "deleting order index");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let parent_commit = repo.head()?.peel_to_commit()?;
let head_tree = parent_commit.tree()?;
let index_path = order::order_file_path(directory);
if GitUtils::blob_oid_in_tree(&head_tree, &index_path).is_none() {
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, "order index not found for deletion");
return Err(AppError::OrderNotFound {
directory: display_directory.to_string(),
});
}
let mut tree_update = TreeUpdateBuilder::new();
let change = Self::stage_index(
&repo,
repo_path,
&mut tree_update,
directory,
&[],
true,
checkout_files,
)?;
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("reorder: {}", display_directory);
let message = commit_message.unwrap_or(&auto_message);
let commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&parent_commit],
)?;
tracing::debug!(tenant_id = %tenant_id, directory = %display_directory, sha = %commit_oid, "order deletion committed");
Ok((commit_oid.to_string(), change))
}
fn stored_order(
repo: &Repository,
tree: &git2::Tree<'_>,
directory: &str,
) -> Option<Vec<String>> {
let index_path = order::order_file_path(directory);
let index_oid = GitUtils::blob_oid_in_tree(tree, &index_path)?;
let blob = repo.find_blob(index_oid).ok()?;
let parsed = order::parse(std::str::from_utf8(blob.content()).ok()?);
if parsed.is_none() {
tracing::warn!(path = %index_path, "order index is malformed, ignoring it");
}
parsed
}
fn materialized_order(
repo: &Repository,
head_tree: &git2::Tree<'_>,
directory: &str,
stored: &[String],
implicit_default_index: Option<i64>,
allow_hidden_files: bool,
) -> Result<Vec<String>, AppError> {
let mut entries = Self::directory_entries(repo, head_tree, directory)?;
let ranks = GitFiles::order_ranks(stored);
let order_options = OrderOptions {
implicit_default_index,
};
if !allow_hidden_files {
entries.retain(|entry| {
!order::is_hidden(entry) || ranks.contains_key(order::entry_name(entry))
});
}
entries.sort_by_key(|entry| {
GitFiles::order_rank(&ranks, order::entry_name(entry), &order_options)
});
Ok(entries)
}
fn directory_entries(
repo: &Repository,
head_tree: &git2::Tree<'_>,
directory: &str,
) -> Result<Vec<String>, AppError> {
let subtree;
let tree = if directory.is_empty() {
head_tree
} else {
match head_tree.get_path(Path::new(directory)) {
Ok(entry) if entry.kind() == Some(git2::ObjectType::Tree) => {
subtree = entry.to_object(repo)?.peel_to_tree()?;
&subtree
}
_ => return Ok(Vec::new()),
}
};
let mut directories: Vec<String> = Vec::new();
let mut files: Vec<String> = Vec::new();
for entry in tree.iter() {
let Ok(entry_name) = entry.name() else {
continue;
};
if entry_name == order::ORDER_FILE_NAME {
continue;
}
match entry.kind() {
Some(git2::ObjectType::Tree) => {
directories.push(order::directory_entry(entry_name))
}
Some(git2::ObjectType::Blob) => files.push(entry_name.to_string()),
_ => {}
}
}
directories.sort();
files.sort();
directories.extend(files);
Ok(directories)
}
fn entry_position(
repo: &Repository,
tree: &git2::Tree<'_>,
directory: &str,
name: &str,
) -> i64 {
Self::stored_order(repo, tree, directory)
.and_then(|stored| {
stored
.iter()
.position(|entry| order::entry_name(entry) == name)
})
.map_or(order::UNLISTED_POSITION, |position| position as i64)
}
fn stage_index(
repo: &Repository,
repo_path: &Path,
tree_update: &mut TreeUpdateBuilder,
directory: &str,
order_entries: &[String],
index_existed: bool,
checkout_files: bool,
) -> Result<FileChange, AppError> {
let index_path = order::order_file_path(directory);
let working_tree = WorkingTree::new(repo_path, checkout_files);
if order_entries.is_empty() {
tracing::trace!(path = %index_path, "staging order index removal");
working_tree.remove_file(&index_path)?;
tree_update.remove(&index_path);
return Ok(FileChange::Deleted { path: index_path });
}
tracing::trace!(path = %index_path, entry_count = order_entries.len(), "staging order index write");
let content = order::serialize(order_entries);
working_tree.write(&index_path, content.as_bytes())?;
let blob_oid = repo.blob(content.as_bytes())?;
tree_update.upsert(&index_path, blob_oid, FileMode::Blob);
Ok(if index_existed {
FileChange::Updated {
path: index_path,
content,
}
} else {
FileChange::Created {
path: index_path,
content,
}
})
}
fn stage_entry_removed(
repo: &Repository,
repo_path: &Path,
head_tree: &git2::Tree<'_>,
tree_update: &mut TreeUpdateBuilder,
directory: &str,
name: &str,
checkout_files: bool,
) -> Result<Option<FileChange>, AppError> {
let Some(stored) = Self::stored_order(repo, head_tree, directory) else {
return Ok(None);
};
let entry_count = stored.len();
let retained: Vec<String> = stored
.into_iter()
.filter(|entry| order::entry_name(entry) != name)
.collect();
if retained.len() == entry_count {
return Ok(None);
}
Self::stage_index(
repo,
repo_path,
tree_update,
directory,
&retained,
true,
checkout_files,
)
.map(Some)
}
fn stage_entry_appended(
repo: &Repository,
repo_path: &Path,
head_tree: &git2::Tree<'_>,
tree_update: &mut TreeUpdateBuilder,
directory: &str,
canonical_entry: &str,
checkout_files: bool,
) -> Result<Option<FileChange>, AppError> {
let Some(mut stored) = Self::stored_order(repo, head_tree, directory) else {
return Ok(None);
};
let name = order::entry_name(canonical_entry);
if stored.iter().any(|entry| order::entry_name(entry) == name) {
return Ok(None);
}
stored.push(canonical_entry.to_string());
Self::stage_index(
repo,
repo_path,
tree_update,
directory,
&stored,
true,
checkout_files,
)
.map(Some)
}
#[allow(clippy::too_many_arguments)]
fn stage_entry_renamed(
repo: &Repository,
repo_path: &Path,
head_tree: &git2::Tree<'_>,
tree_update: &mut TreeUpdateBuilder,
directory: &str,
from_name: &str,
canonical_entry: &str,
checkout_files: bool,
) -> Result<Option<FileChange>, AppError> {
let Some(mut stored) = Self::stored_order(repo, head_tree, directory) else {
return Ok(None);
};
let Some(position) = stored
.iter()
.position(|entry| order::entry_name(entry) == from_name)
else {
return Ok(None);
};
stored[position] = canonical_entry.to_string();
Self::stage_index(
repo,
repo_path,
tree_update,
directory,
&stored,
true,
checkout_files,
)
.map(Some)
}
}
pub struct GitCommits;
impl GitCommits {
pub fn list_commits(
repo_path: &Path,
tenant_id: &str,
page: usize,
per_page: usize,
file_path: Option<&str>,
include_statistics: bool,
) -> Result<(Vec<CommitSummary>, bool), AppError> {
if let Some(path) = file_path {
return Self::list_commits_by_file(
repo_path,
tenant_id,
page,
per_page,
path,
include_statistics,
);
}
tracing::debug!(tenant_id = %tenant_id, page = page, per_page = per_page, include_statistics = include_statistics, "listing commits");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let mut revwalk = repo.revwalk()?;
revwalk.push_head()?;
revwalk.set_sorting(Sort::TIME | Sort::TOPOLOGICAL)?;
let skip_count = page.saturating_sub(1).saturating_mul(per_page);
tracing::trace!(tenant_id = %tenant_id, skip_count = skip_count, per_page = per_page, "walking commit graph");
let mut commits: Vec<CommitSummary> = revwalk
.skip(skip_count)
.take(per_page + 1)
.filter_map(|oid_result| oid_result.ok())
.filter_map(|oid| repo.find_commit(oid).ok())
.map(|commit| {
let statistics = if include_statistics {
Some(Self::statistics_for_commit(&repo, &commit)?)
} else {
None
};
Ok(CommitSummary {
sha: commit.id().to_string(),
message: commit.message().unwrap_or("").to_string(),
author: CommitAuthor {
name: commit.author().name().unwrap_or("").to_string(),
email: commit.author().email().unwrap_or("").to_string(),
},
committed_at: GitUtils::timestamp_from_git_time(commit.time()),
statistics,
})
})
.collect::<Result<Vec<CommitSummary>, AppError>>()?;
let has_more = commits.len() > per_page;
commits.truncate(per_page);
tracing::debug!(tenant_id = %tenant_id, page = page, returned = commits.len(), has_more = has_more, "commit listing complete");
Ok((commits, has_more))
}
fn list_commits_by_file(
repo_path: &Path,
tenant_id: &str,
page: usize,
per_page: usize,
file_path: &str,
include_statistics: bool,
) -> Result<(Vec<CommitSummary>, bool), AppError> {
tracing::debug!(
tenant_id = %tenant_id,
page = page,
per_page = per_page,
file_path = %file_path,
include_statistics = include_statistics,
"listing commits by file path"
);
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let mut revwalk = repo.revwalk()?;
revwalk.push_head()?;
revwalk.set_sorting(Sort::TIME | Sort::TOPOLOGICAL)?;
let skip_count = page.saturating_sub(1).saturating_mul(per_page);
let need = skip_count + per_page + 1;
let mut current_path = file_path.to_string();
let mut matching: Vec<CommitSummary> = Vec::new();
for oid_result in revwalk {
if matching.len() >= need {
break;
}
let oid = match oid_result {
Ok(id) => id,
Err(_) => continue,
};
let commit = match repo.find_commit(oid) {
Ok(c) => c,
Err(_) => continue,
};
let commit_tree = match commit.tree() {
Ok(t) => t,
Err(_) => continue,
};
let (is_match, rename_from) = if commit.parent_count() == 0 {
let exists = commit_tree.get_path(Path::new(¤t_path)).is_ok();
tracing::trace!(
tenant_id = %tenant_id,
sha = %commit.id(),
path = %current_path,
exists = exists,
"checking root commit for file"
);
(exists, None)
} else {
let parent_tree = match commit.parent(0).and_then(|p| p.tree()) {
Ok(t) => t,
Err(_) => continue,
};
let commit_entry = commit_tree.get_path(Path::new(¤t_path)).ok();
let parent_entry = parent_tree.get_path(Path::new(¤t_path)).ok();
match (commit_entry, parent_entry) {
(Some(in_commit), Some(in_parent))
if in_commit.id() == in_parent.id()
&& in_commit.filemode() == in_parent.filemode() =>
{
(false, None)
}
(Some(_), Some(_)) => (true, None),
(None, Some(_)) => (true, None),
(None, None) => (false, None),
(Some(_), None) => (
true,
Self::rename_source(&repo, &parent_tree, &commit_tree, ¤t_path),
),
}
};
if is_match {
tracing::trace!(
tenant_id = %tenant_id,
sha = %commit.id(),
path = %current_path,
"commit matched file path filter"
);
matching.push(CommitSummary {
sha: commit.id().to_string(),
message: commit.message().unwrap_or("").to_string(),
author: CommitAuthor {
name: commit.author().name().unwrap_or("").to_string(),
email: commit.author().email().unwrap_or("").to_string(),
},
committed_at: GitUtils::timestamp_from_git_time(commit.time()),
statistics: None,
});
if let Some(old_name) = rename_from {
current_path = old_name;
}
}
}
let has_more = matching.len() > skip_count + per_page;
let commits: Vec<CommitSummary> = matching
.into_iter()
.skip(skip_count)
.take(per_page)
.map(|mut summary| {
if include_statistics {
let oid = Oid::from_str(&summary.sha)?;
let commit = repo.find_commit(oid)?;
summary.statistics = Some(Self::statistics_for_commit(&repo, &commit)?);
}
Ok(summary)
})
.collect::<Result<Vec<CommitSummary>, AppError>>()?;
tracing::debug!(
tenant_id = %tenant_id,
page = page,
returned = per_page,
has_more = has_more,
"commit listing by file complete"
);
Ok((commits, has_more))
}
fn rename_source(
repo: &Repository,
parent_tree: &git2::Tree<'_>,
commit_tree: &git2::Tree<'_>,
current_path: &str,
) -> Option<String> {
let mut diff_opts = DiffOptions::new();
diff_opts.include_untracked(false);
let mut diff = repo
.diff_tree_to_tree(Some(parent_tree), Some(commit_tree), Some(&mut diff_opts))
.ok()?;
let mut find_opts = DiffFindOptions::new();
find_opts.renames(true);
diff.find_similar(Some(&mut find_opts)).ok()?;
for index in 0..diff.deltas().count() {
let Some(delta) = diff.get_delta(index) else {
continue;
};
if delta.status() != Delta::Renamed {
continue;
}
let new = delta
.new_file()
.path()
.map(|path| path.to_string_lossy().into_owned());
if new.as_deref() == Some(current_path) {
let old = delta
.old_file()
.path()
.map(|path| path.to_string_lossy().into_owned());
tracing::trace!(
from = ?old,
to = %current_path,
"rename detected, following path backward"
);
return old;
}
}
None
}
fn statistics_for_commit(
repo: &Repository,
commit: &git2::Commit,
) -> Result<CommitStatistics, AppError> {
let commit_tree = commit.tree()?;
let parent_tree = if commit.parent_count() > 0 {
Some(commit.parent(0)?.tree()?)
} else {
None
};
let mut diff_options = DiffOptions::new();
diff_options.include_untracked(false);
let mut diff = repo.diff_tree_to_tree(
parent_tree.as_ref(),
Some(&commit_tree),
Some(&mut diff_options),
)?;
let mut find_options = DiffFindOptions::new();
find_options.renames(true);
diff.find_similar(Some(&mut find_options))?;
let stats = diff.stats()?;
Ok(CommitStatistics {
insertions: stats.insertions(),
deletions: stats.deletions(),
files_changed: stats.files_changed(),
})
}
pub fn get_commit(
repo_path: &Path,
tenant_id: &str,
sha: &str,
) -> Result<CommitDetail, AppError> {
tracing::debug!(tenant_id = %tenant_id, sha = %sha, "fetching commit detail");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let object = repo
.revparse_single(sha)
.map_err(|_err| AppError::CommitNotFound {
sha: sha.to_string(),
})?;
let commit = object
.peel_to_commit()
.map_err(|_err| AppError::CommitNotFound {
sha: sha.to_string(),
})?;
let commit_tree = commit.tree()?;
let parent_tree = if commit.parent_count() > 0 {
Some(commit.parent(0)?.tree()?)
} else {
None
};
tracing::trace!(
tenant_id = %tenant_id,
sha = %sha,
has_parent = parent_tree.is_some(),
"diffing commit against parent"
);
let mut diff_options = DiffOptions::new();
diff_options.include_untracked(false);
let mut diff = repo.diff_tree_to_tree(
parent_tree.as_ref(),
Some(&commit_tree),
Some(&mut diff_options),
)?;
let mut find_options = DiffFindOptions::new();
find_options.renames(true);
diff.find_similar(Some(&mut find_options))?;
let diff_stats = diff.stats()?;
let statistics = CommitStatistics {
insertions: diff_stats.insertions(),
deletions: diff_stats.deletions(),
files_changed: diff_stats.files_changed(),
};
let records: Vec<DeltaRecord> = (0..diff.deltas().count())
.filter_map(|index| diff.get_delta(index))
.map(|delta| {
tracing::trace!(
tenant_id = %tenant_id,
sha = %sha,
status = ?delta.status(),
old_path = ?delta.old_file().path(),
new_path = ?delta.new_file().path(),
"processing diff delta"
);
DeltaRecord {
status: delta.status(),
old_oid: delta.old_file().id(),
new_oid: delta.new_file().id(),
old_path: delta.old_file().path().map(PathBuf::from),
new_path: delta.new_file().path().map(PathBuf::from),
}
})
.collect();
tracing::trace!(tenant_id = %tenant_id, sha = %sha, delta_count = records.len(), "building per-file diffs");
let mut per_file_diffs: Vec<String> = vec![String::new(); records.len()];
diff.print(DiffFormat::Patch, |delta, _hunk, line| {
let key = (delta.old_file().id(), delta.new_file().id());
if let Some(idx) = records
.iter()
.position(|record| (record.old_oid, record.new_oid) == key)
{
let bucket = &mut per_file_diffs[idx];
match line.origin() {
'+' | '-' | ' ' | '\\' => bucket.push(line.origin()),
_ => {}
}
bucket.push_str(std::str::from_utf8(line.content()).unwrap_or(""));
}
true
})?;
let mut file_details: Vec<CommitFileDetail> = Vec::with_capacity(records.len());
for (index, record) in records.iter().enumerate() {
let (change_label, file_path, from_path) = match record.status {
Delta::Added => (
"created",
GitUtils::path_string(record.new_path.as_deref()),
None,
),
Delta::Deleted => (
"deleted",
GitUtils::path_string(record.old_path.as_deref()),
None,
),
Delta::Renamed => (
"moved",
GitUtils::path_string(record.new_path.as_deref()),
record
.old_path
.as_deref()
.map(|path| path.to_string_lossy().into_owned()),
),
_ => (
"updated",
GitUtils::path_string(record.new_path.as_deref()),
None,
),
};
tracing::trace!(
tenant_id = %tenant_id,
sha = %sha,
path = %file_path,
change = %change_label,
"assembling commit file detail"
);
let content = if record.status == Delta::Deleted {
String::new()
} else {
GitUtils::blob_content_from_tree(&repo, &commit_tree, &file_path)?
};
file_details.push(CommitFileDetail {
path: file_path,
change: change_label.to_string(),
from_path,
content,
diff: std::mem::take(&mut per_file_diffs[index]),
});
}
let sha = commit.id().to_string();
let message = commit.message().unwrap_or("").to_string();
let author = CommitAuthor {
name: commit.author().name().unwrap_or("").to_string(),
email: commit.author().email().unwrap_or("").to_string(),
};
let committed_at = GitUtils::timestamp_from_git_time(commit.time());
tracing::debug!(tenant_id = %tenant_id, sha = %sha, file_count = file_details.len(), "commit detail ready");
Ok(CommitDetail {
sha,
message,
author,
committed_at,
files: file_details,
statistics,
})
}
pub fn revert_commit(
repo_path: &Path,
tenant_id: &str,
sha: &str,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Vec<FileChange>), AppError> {
tracing::debug!(tenant_id = %tenant_id, sha = %sha, author_name = %author_name, author_email = %author_email, "reverting commit");
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let object = repo
.revparse_single(sha)
.map_err(|_err| AppError::CommitNotFound {
sha: sha.to_string(),
})?;
let target_commit = object
.peel_to_commit()
.map_err(|_err| AppError::CommitNotFound {
sha: sha.to_string(),
})?;
if target_commit.parent_count() == 0 {
tracing::warn!(tenant_id = %tenant_id, sha = %sha, "cannot revert root commit");
return Err(AppError::InvalidOperation {
reason: "cannot revert the initial commit".to_string(),
});
}
let parent_commit = target_commit.parent(0)?;
let commit_tree = target_commit.tree()?;
let parent_tree = parent_commit.tree()?;
tracing::trace!(tenant_id = %tenant_id, sha = %sha, "computing diff for revert");
let mut diff = repo.diff_tree_to_tree(Some(&parent_tree), Some(&commit_tree), None)?;
let mut find_options = DiffFindOptions::new();
find_options.renames(true);
diff.find_similar(Some(&mut find_options))?;
let raw_deltas: Vec<DeltaRecord> = (0..diff.deltas().count())
.filter_map(|index| diff.get_delta(index))
.map(|delta| DeltaRecord {
status: delta.status(),
old_oid: delta.old_file().id(),
new_oid: delta.new_file().id(),
old_path: delta.old_file().path().map(PathBuf::from),
new_path: delta.new_file().path().map(PathBuf::from),
})
.collect();
tracing::trace!(tenant_id = %tenant_id, sha = %sha, delta_count = raw_deltas.len(), "applying revert deltas");
let head_commit = repo.head()?.peel_to_commit()?;
let head_tree = head_commit.tree()?;
let mut tree_update = TreeUpdateBuilder::new();
let mut file_changes: Vec<FileChange> = Vec::new();
let working_tree = WorkingTree::new(repo_path, checkout_files);
for raw_delta in &raw_deltas {
match raw_delta.status {
Delta::Added => {
if let Some(new_path) = &raw_delta.new_path {
tracing::trace!(
tenant_id = %tenant_id,
sha = %sha,
path = %new_path.display(),
"revert: removing added file"
);
working_tree.remove_file(new_path)?;
tree_update.remove(new_path);
file_changes.push(FileChange::Deleted {
path: new_path.to_string_lossy().into_owned(),
});
}
}
Delta::Deleted => {
if let Some(old_path) = &raw_delta.old_path {
tracing::trace!(
tenant_id = %tenant_id,
sha = %sha,
path = %old_path.display(),
"revert: restoring deleted file"
);
let content = GitUtils::blob_content_from_tree(
&repo,
&parent_tree,
&old_path.to_string_lossy(),
)?;
working_tree.write(old_path, content.as_bytes())?;
tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);
file_changes.push(FileChange::Created {
path: old_path.to_string_lossy().into_owned(),
content,
});
}
}
Delta::Modified => {
if let Some(old_path) = &raw_delta.old_path {
tracing::trace!(
tenant_id = %tenant_id,
sha = %sha,
path = %old_path.display(),
"revert: restoring modified file to previous version"
);
let content = GitUtils::blob_content_from_tree(
&repo,
&parent_tree,
&old_path.to_string_lossy(),
)?;
working_tree.write(old_path, content.as_bytes())?;
tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);
file_changes.push(FileChange::Updated {
path: old_path.to_string_lossy().into_owned(),
content,
});
}
}
Delta::Renamed => {
if let (Some(old_path), Some(new_path)) =
(&raw_delta.old_path, &raw_delta.new_path)
{
tracing::trace!(
tenant_id = %tenant_id,
sha = %sha,
from_path = %new_path.display(),
to_path = %old_path.display(),
"revert: reversing rename"
);
let content = GitUtils::blob_content_from_tree(
&repo,
&parent_tree,
&old_path.to_string_lossy(),
)?;
working_tree.remove_file(new_path)?;
working_tree.write(old_path, content.as_bytes())?;
tree_update.remove(new_path);
tree_update.upsert(old_path, raw_delta.old_oid, FileMode::Blob);
file_changes.push(FileChange::Moved {
from_path: new_path.to_string_lossy().into_owned(),
to_path: old_path.to_string_lossy().into_owned(),
content,
});
}
}
_ => {}
}
}
tracing::trace!(tenant_id = %tenant_id, sha = %sha, "building revert tree and committing");
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("revert: {}", target_commit.message().unwrap_or("unknown"));
let revert_message = commit_message.unwrap_or(&auto_message);
let new_commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
revert_message,
&tree,
&[&head_commit],
)?;
tracing::debug!(
tenant_id = %tenant_id,
reverted_sha = %sha,
new_sha = %new_commit_oid,
file_change_count = file_changes.len(),
"revert committed"
);
Ok((new_commit_oid.to_string(), file_changes))
}
pub fn rollback_commit(
repo_path: &Path,
tenant_id: &str,
sha: &str,
commit_message: Option<&str>,
author_name: &str,
author_email: &str,
checkout_files: bool,
) -> Result<(String, Vec<FileChange>), AppError> {
tracing::debug!(tenant_id = %tenant_id, sha = %sha, author_name = %author_name, author_email = %author_email, "rolling files back to commit");
fn restore_path(
repo: &Repository,
working_tree: &WorkingTree<'_>,
head_tree: &git2::Tree<'_>,
target_tree: &git2::Tree<'_>,
tree_update: &mut TreeUpdateBuilder,
path: &Path,
oid: Oid,
) -> Result<Option<FileChange>, AppError> {
let path_string = path.to_string_lossy().into_owned();
let head_oid = GitUtils::blob_oid_in_tree(head_tree, &path_string);
if head_oid == Some(oid) {
tracing::trace!(path = %path_string, "rollback: file already in target state");
return Ok(None);
}
tracing::trace!(
path = %path_string,
existed_in_head = head_oid.is_some(),
"rollback: restoring file content from target commit"
);
let content = GitUtils::blob_content_from_tree(repo, target_tree, &path_string)?;
working_tree.write(path, content.as_bytes())?;
tree_update.upsert(path, oid, FileMode::Blob);
Ok(Some(if head_oid.is_some() {
FileChange::Updated {
path: path_string,
content,
}
} else {
FileChange::Created {
path: path_string,
content,
}
}))
}
fn remove_path(
working_tree: &WorkingTree<'_>,
head_tree: &git2::Tree<'_>,
tree_update: &mut TreeUpdateBuilder,
path: &Path,
) -> Result<Option<FileChange>, AppError> {
let path_string = path.to_string_lossy().into_owned();
if GitUtils::blob_oid_in_tree(head_tree, &path_string).is_none() {
tracing::trace!(path = %path_string, "rollback: file already absent");
return Ok(None);
}
tracing::trace!(path = %path_string, "rollback: removing file absent from target commit");
working_tree.remove_file(path)?;
tree_update.remove(path);
Ok(Some(FileChange::Deleted { path: path_string }))
}
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let object = repo
.revparse_single(sha)
.map_err(|_err| AppError::CommitNotFound {
sha: sha.to_string(),
})?;
let target_commit = object
.peel_to_commit()
.map_err(|_err| AppError::CommitNotFound {
sha: sha.to_string(),
})?;
let target_tree = target_commit.tree()?;
tracing::trace!(tenant_id = %tenant_id, sha = %sha, "computing diff for rollback");
let parent_tree = match target_commit.parent_count() {
0 => None,
_ => Some(target_commit.parent(0)?.tree()?),
};
let mut diff = repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&target_tree), None)?;
let mut find_options = DiffFindOptions::new();
find_options.renames(true);
diff.find_similar(Some(&mut find_options))?;
let raw_deltas: Vec<DeltaRecord> = (0..diff.deltas().count())
.filter_map(|index| diff.get_delta(index))
.map(|delta| DeltaRecord {
status: delta.status(),
old_oid: delta.old_file().id(),
new_oid: delta.new_file().id(),
old_path: delta.old_file().path().map(PathBuf::from),
new_path: delta.new_file().path().map(PathBuf::from),
})
.collect();
tracing::trace!(tenant_id = %tenant_id, sha = %sha, delta_count = raw_deltas.len(), "applying rollback deltas");
let head_commit = repo.head()?.peel_to_commit()?;
let head_tree = head_commit.tree()?;
let mut tree_update = TreeUpdateBuilder::new();
let mut file_changes: Vec<FileChange> = Vec::new();
let working_tree = WorkingTree::new(repo_path, checkout_files);
for raw_delta in &raw_deltas {
match raw_delta.status {
Delta::Added | Delta::Modified => {
if let Some(new_path) = &raw_delta.new_path {
let change = restore_path(
&repo,
&working_tree,
&head_tree,
&target_tree,
&mut tree_update,
new_path,
raw_delta.new_oid,
)?;
file_changes.extend(change);
}
}
Delta::Deleted => {
if let Some(old_path) = &raw_delta.old_path {
let change =
remove_path(&working_tree, &head_tree, &mut tree_update, old_path)?;
file_changes.extend(change);
}
}
Delta::Renamed => {
if let (Some(old_path), Some(new_path)) =
(&raw_delta.old_path, &raw_delta.new_path)
{
let old_in_head =
GitUtils::blob_oid_in_tree(&head_tree, &old_path.to_string_lossy())
.is_some();
let new_in_head =
GitUtils::blob_oid_in_tree(&head_tree, &new_path.to_string_lossy())
.is_some();
if old_in_head && !new_in_head {
tracing::trace!(
tenant_id = %tenant_id,
sha = %sha,
from_path = %old_path.display(),
to_path = %new_path.display(),
"rollback: re-applying rename"
);
let content = GitUtils::blob_content_from_tree(
&repo,
&target_tree,
&new_path.to_string_lossy(),
)?;
let absolute_old = repo_path.join(old_path);
let absolute_new = repo_path.join(new_path);
match std::fs::remove_file(&absolute_old) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(AppError::Io(err)),
}
if let Some(parent_dir) = absolute_new.parent() {
std::fs::create_dir_all(parent_dir)?;
}
std::fs::write(&absolute_new, &content)?;
tree_update.remove(old_path);
tree_update.upsert(new_path, raw_delta.new_oid, FileMode::Blob);
file_changes.push(FileChange::Moved {
from_path: old_path.to_string_lossy().into_owned(),
to_path: new_path.to_string_lossy().into_owned(),
content,
});
} else {
let restored = restore_path(
&repo,
&working_tree,
&head_tree,
&target_tree,
&mut tree_update,
new_path,
raw_delta.new_oid,
)?;
file_changes.extend(restored);
let removed =
remove_path(&working_tree, &head_tree, &mut tree_update, old_path)?;
file_changes.extend(removed);
}
}
}
_ => {}
}
}
if file_changes.is_empty() {
tracing::debug!(tenant_id = %tenant_id, sha = %sha, "files already in target state, skipping commit");
return Ok((head_commit.id().to_string(), file_changes));
}
tracing::trace!(tenant_id = %tenant_id, sha = %sha, "building rollback tree and committing");
let tree_id = tree_update.create_updated(&repo, &head_tree)?;
let tree = repo.find_tree(tree_id)?;
let signature = GitUtils::git_signature(author_name, author_email)?;
let auto_message = format!("rollback: {}", target_commit.message().unwrap_or("unknown"));
let message = commit_message.unwrap_or(&auto_message);
let new_commit_oid = repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&[&head_commit],
)?;
tracing::debug!(
tenant_id = %tenant_id,
rolled_back_to_sha = %sha,
new_sha = %new_commit_oid,
file_change_count = file_changes.len(),
"rollback committed"
);
Ok((new_commit_oid.to_string(), file_changes))
}
}
pub struct GitTenant;
impl GitTenant {
pub fn delete_repo(repo_path: &Path, tenant_id: &str) -> Result<(), AppError> {
tracing::debug!(tenant_id = %tenant_id, "deleting tenant repository");
if !repo_path.exists() {
tracing::debug!(tenant_id = %tenant_id, "tenant repository not found for deletion");
return Err(AppError::TenantNotFound {
tenant_id: tenant_id.to_string(),
});
}
GitStaging::remove(repo_path).map_err(|err| {
tracing::error!(
tenant_id = %tenant_id,
path = %repo_path.display(),
err = %err,
"failed to remove tenant repository directory"
);
err
})?;
tracing::info!(tenant_id = %tenant_id, "tenant repository deleted");
Ok(())
}
}
#[derive(Debug, Serialize)]
pub struct RepositoryHead {
pub collection_id: String,
pub tenant_id: String,
pub head_sha: String,
}
#[derive(Debug, Default)]
pub struct RepositoryScan {
pub repositories: Vec<RepositoryHead>,
pub complete: bool,
}
enum HeadProbe {
At(String),
NotARepository,
Unreadable,
}
#[derive(Debug)]
pub enum PackApply {
FastForwarded { from: Option<String>, to: String },
UpToDate,
Ahead { local: String, remote: String },
Diverged { local: String, remote: String },
}
#[derive(Debug, PartialEq, Eq)]
pub enum HeadRelation {
Unknown,
Same,
Ahead { local: String },
Diverged { local: String },
}
pub struct GitReplication;
impl GitReplication {
pub fn head_sha(repo_path: &Path) -> Option<String> {
match Self::probe_head(repo_path) {
HeadProbe::At(head_sha) => Some(head_sha),
HeadProbe::NotARepository | HeadProbe::Unreadable => None,
}
}
fn probe_head(repo_path: &Path) -> HeadProbe {
if !repo_path.join(".git").exists() {
return HeadProbe::NotARepository;
}
let repo = match Repository::open(repo_path) {
Ok(repo) => repo,
Err(err) => {
tracing::warn!(path = %repo_path.display(), err = %err, "repository cannot be opened");
return HeadProbe::Unreadable;
}
};
let probe = match repo.head() {
Ok(head) => match head.target() {
Some(head_oid) => HeadProbe::At(head_oid.to_string()),
None => HeadProbe::Unreadable,
},
Err(err) if err.code() == git2::ErrorCode::UnbornBranch => HeadProbe::NotARepository,
Err(err) => {
tracing::warn!(path = %repo_path.display(), err = %err, "repository HEAD cannot be read");
HeadProbe::Unreadable
}
};
probe
}
pub fn list_repositories(repos_root: &Path) -> RepositoryScan {
let mut scan = RepositoryScan {
repositories: Vec::new(),
complete: true,
};
let collections = match std::fs::read_dir(repos_root) {
Ok(collections) => collections,
Err(err) => {
tracing::warn!(
path = %repos_root.display(),
err = %err,
"repositories root cannot be read, listing is incomplete"
);
scan.complete = false;
return scan;
}
};
for collection_entry in collections {
let Ok(collection_entry) = collection_entry else {
scan.complete = false;
continue;
};
let Some(collection_id) =
Self::scannable_name(&collection_entry, validate::collection_id)
else {
continue;
};
let collection_path = collection_entry.path();
if !collection_path.is_dir() {
continue;
}
let tenants = match std::fs::read_dir(&collection_path) {
Ok(tenants) => tenants,
Err(err) => {
tracing::warn!(
path = %collection_path.display(),
err = %err,
"collection directory cannot be read, listing is incomplete"
);
scan.complete = false;
continue;
}
};
for tenant_entry in tenants {
let Ok(tenant_entry) = tenant_entry else {
scan.complete = false;
continue;
};
let Some(tenant_id) = Self::scannable_name(&tenant_entry, validate::tenant_id)
else {
continue;
};
let tenant_path = tenant_entry.path();
if !tenant_path.is_dir() {
continue;
}
match Self::probe_head(&tenant_path) {
HeadProbe::At(head_sha) => scan.repositories.push(RepositoryHead {
collection_id: collection_id.clone(),
tenant_id,
head_sha,
}),
HeadProbe::NotARepository => {}
HeadProbe::Unreadable => scan.complete = false,
}
}
}
scan
}
fn scannable_name(
entry: &std::fs::DirEntry,
validator: fn(&str) -> Result<&str, AppError>,
) -> Option<String> {
let name = entry.file_name();
let name = name.to_str()?;
validator(name).ok().map(str::to_string)
}
pub fn build_pack<F>(
repo_path: &Path,
tenant_id: &str,
head_sha: &str,
have: Option<&str>,
mut on_chunk: F,
) -> Result<usize, AppError>
where
F: FnMut(&[u8]) -> bool,
{
let repo = GitUtils::open_tenant_repo(repo_path, tenant_id)?;
let head_oid = Oid::from_str(head_sha).map_err(|_err| AppError::CommitNotFound {
sha: head_sha.to_string(),
})?;
let mut revwalk = repo.revwalk()?;
revwalk.push(head_oid)?;
if let Some(have) = have {
match Oid::from_str(have) {
Ok(have_oid) if repo.find_commit(have_oid).is_ok() => {
tracing::trace!(tenant_id = %tenant_id, have = %have, "hiding replica head from pack walk");
revwalk.hide(have_oid)?;
}
_ => {
tracing::debug!(
tenant_id = %tenant_id,
have = %have,
"replica reported an unknown commit, sending a full pack"
);
}
}
}
let mut packbuilder = repo.packbuilder()?;
packbuilder.insert_walk(&mut revwalk)?;
let object_count = packbuilder.object_count();
packbuilder.foreach(|chunk| on_chunk(chunk))?;
tracing::debug!(
tenant_id = %tenant_id,
head = %head_sha,
objects = object_count,
"replication pack built"
);
Ok(object_count)
}
pub fn apply_pack(
repo_path: &Path,
pack_path: &Path,
new_head: &str,
) -> Result<PackApply, AppError> {
if repo_path.join(".git").exists() {
let repo = Repository::open(repo_path)?;
return Self::import_pack(&repo, pack_path, new_head);
}
tracing::info!(path = %repo_path.display(), "initialising replica repository");
if repo_path.exists() {
let repo = Repository::init(repo_path)?;
return Self::import_pack(&repo, pack_path, new_head);
}
GitStaging::create(repo_path, |staging| {
let repo = Repository::init(staging)?;
Self::import_pack(&repo, pack_path, new_head)
})
}
fn import_pack(
repo: &Repository,
pack_path: &Path,
new_head: &str,
) -> Result<PackApply, AppError> {
let new_oid = Oid::from_str(new_head).map_err(|_err| AppError::CommitNotFound {
sha: new_head.to_string(),
})?;
{
let odb = repo.odb()?;
let mut packwriter = odb.packwriter()?;
let mut pack_file = std::fs::File::open(pack_path)?;
std::io::copy(&mut pack_file, &mut packwriter)?;
packwriter.commit()?;
}
repo.find_commit(new_oid)
.map_err(|_err| AppError::CommitNotFound {
sha: new_head.to_string(),
})?;
let local_head = repo.head().ok().and_then(|head| head.target());
if let Some(local_oid) = local_head {
if local_oid == new_oid {
return Ok(PackApply::UpToDate);
}
if !repo.graph_descendant_of(new_oid, local_oid)? {
let ahead = repo.graph_descendant_of(local_oid, new_oid)?;
return Ok(if ahead {
PackApply::Ahead {
local: local_oid.to_string(),
remote: new_head.to_string(),
}
} else {
PackApply::Diverged {
local: local_oid.to_string(),
remote: new_head.to_string(),
}
});
}
}
let head_reference = Self::head_reference_name(repo)?;
repo.reference(
&head_reference,
new_oid,
true,
&format!("replication: fast-forward to {}", new_head),
)?;
Ok(PackApply::FastForwarded {
from: local_head.map(|oid| oid.to_string()),
to: new_head.to_string(),
})
}
pub fn mirror_working_tree(repo_path: &Path) -> usize {
let Ok(repo) = Repository::open(repo_path) else {
return 0;
};
Self::mirror_repository(repo_path, &repo)
}
fn mirror_repository(repo_path: &Path, repo: &Repository) -> usize {
if repo.head().ok().and_then(|head| head.target()).is_none() {
return 0;
}
if let Err(err) = GitLocks::cleanup_stale_index_lock(repo_path) {
tracing::warn!(
path = %repo_path.display(),
err = %err,
"cannot clear stale index lock before mirroring the working tree"
);
}
if let Err(err) = Self::refresh_index(repo) {
tracing::warn!(
path = %repo_path.display(),
err = %err,
"cannot refresh the index before mirroring the working tree"
);
}
let touched = std::cell::Cell::new(0_usize);
let mut checkout = CheckoutBuilder::new();
checkout
.force()
.remove_untracked(true)
.notify_on(git2::CheckoutNotificationType::UPDATED)
.notify(|_kind, _path, _baseline, _target, _workdir| {
touched.set(touched.get() + 1);
true
});
if let Err(err) = repo.checkout_head(Some(&mut checkout)) {
tracing::warn!(
path = %repo_path.display(),
err = %err,
"cannot mirror the working tree onto HEAD"
);
}
touched.get()
}
fn refresh_index(repo: &Repository) -> Result<(), AppError> {
let head_tree = repo.head()?.peel_to_commit()?.tree()?;
let mut index = repo.index()?;
index.read_tree(&head_tree)?;
index.write()?;
Ok(())
}
pub fn relation_to(repo_path: &Path, remote_sha: &str) -> HeadRelation {
let Ok(repo) = Repository::open(repo_path) else {
return HeadRelation::Unknown;
};
let Some(local_oid) = repo.head().ok().and_then(|head| head.target()) else {
return HeadRelation::Unknown;
};
let Ok(remote_oid) = Oid::from_str(remote_sha) else {
return HeadRelation::Unknown;
};
if repo.find_commit(remote_oid).is_err() {
return HeadRelation::Unknown;
}
if remote_oid == local_oid {
return HeadRelation::Same;
}
match repo.graph_descendant_of(local_oid, remote_oid) {
Ok(true) => HeadRelation::Ahead {
local: local_oid.to_string(),
},
Ok(false) => HeadRelation::Diverged {
local: local_oid.to_string(),
},
Err(_) => HeadRelation::Unknown,
}
}
fn head_reference_name(repo: &Repository) -> Result<String, AppError> {
let head = repo.find_reference("HEAD")?;
Ok(head
.symbolic_target()?
.unwrap_or("refs/heads/master")
.to_string())
}
}