use crate::error::{Context, Result};
use super::objects::{Blob, Tree, TreeEntry};
use super::manager::{CommitInfo, VcsManager};
impl VcsManager {
pub fn get_branch_diff(&self, branch_name: &str) -> Result<String> {
let branch_commit_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
let branch_tree = self.commit_tree(&branch_commit_id)?;
let head_tree = self.head_tree().unwrap_or(Tree::new(vec![]));
let diff = self.diff_trees(&head_tree, &branch_tree);
Ok(diff)
}
pub fn get_diff(&self) -> Result<String> {
let head_tree = self.head_tree().unwrap_or(Tree::new(vec![]));
let wt_files = self.walk_working_tree(&self.repo_path)?;
let mut wt_entries: std::collections::HashMap<String, Vec<u8>> = std::collections::HashMap::new();
for path in &wt_files {
let rel = path.strip_prefix(&self.repo_path).unwrap_or(path);
let rel_str = rel.to_string_lossy().to_string();
if let Ok(content) = std::fs::read(path) {
wt_entries.insert(rel_str, content);
}
}
let mut diff = String::new();
let head_set: std::collections::HashMap<&String, &String> = head_tree.entries.iter().map(|e| (&e.name, &e.id)).collect();
for (path, content) in &wt_entries {
let blob = Blob::new(content.clone());
if let Some(head_blob_id) = head_set.get(path) {
if &blob.id() != *head_blob_id {
diff.push_str(&format!("diff --git a/{} b/{}\n", path, path));
let old_content = self.repo.read_blob(head_blob_id)?.content;
diff.push_str(&self.unified_diff(path, &old_content, content));
}
} else {
diff.push_str(&format!("diff --git a/{} b/{}\n", path, path));
diff.push_str("new file\n");
diff.push_str(&self.unified_diff(path, &[], content));
}
}
for (name, blob_id) in &head_set {
if !wt_entries.contains_key(*name) {
diff.push_str(&format!("diff --git a/{} b/{}\n", name, name));
diff.push_str("deleted file\n");
let old_content = self.repo.read_blob(blob_id)?.content;
diff.push_str(&self.unified_diff(name, &old_content, &[]));
}
}
Ok(diff)
}
pub fn get_commit_history(&self, branch_name: &str, limit: usize) -> Result<Vec<CommitInfo>> {
let mut commit_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
let mut commits = Vec::new();
for _ in 0..limit {
let commit = self.repo.read_commit(&commit_id)?;
let files = self.commit_files(&commit_id)?;
commits.push(CommitInfo {
hash: commit_id.clone(),
message: commit.message.clone(),
author: commit.author.clone(),
timestamp: commit.timestamp as i64,
files_changed: files,
});
if commit.parents.is_empty() {
break;
}
commit_id = commit.parents[0].clone();
}
Ok(commits)
}
pub fn get_commits_between(&self, branch_name: &str, base_branch: &str) -> Result<Vec<CommitInfo>> {
let branch_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
let base_id = self
.repo
.refs()
.get_branch(base_branch)?
.with_context(|| format!("Base branch '{}' not found", base_branch))?;
let mut commits = Vec::new();
let mut current = branch_id.clone();
while current != base_id {
let commit = self.repo.read_commit(¤t)?;
let files = self.commit_files(¤t)?;
commits.push(CommitInfo {
hash: current.clone(),
message: commit.message.clone(),
author: commit.author.clone(),
timestamp: commit.timestamp as i64,
files_changed: files,
});
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
Ok(commits)
}
fn unified_diff(&self, path: &str, old: &[u8], new: &[u8]) -> String {
let old_text = String::from_utf8_lossy(old);
let new_text = String::from_utf8_lossy(new);
let old_lines: Vec<&str> = old_text.lines().collect();
let new_lines: Vec<&str> = new_text.lines().collect();
let mut diff = String::new();
diff.push_str(&format!("--- a/{}\n", path));
diff.push_str(&format!("+++ b/{}\n", path));
let max_len = old_lines.len().max(new_lines.len());
for i in 0..max_len {
let old_line = old_lines.get(i);
let new_line = new_lines.get(i);
match (old_line, new_line) {
(Some(o), Some(n)) if o == n => {
diff.push_str(&format!(" {}\n", o));
}
(Some(o), Some(n)) => {
diff.push_str(&format!("-{}\n", o));
diff.push_str(&format!("+{}\n", n));
}
(Some(o), None) => {
diff.push_str(&format!("-{}\n", o));
}
(None, Some(n)) => {
diff.push_str(&format!("+{}\n", n));
}
(None, None) => {}
}
}
diff
}
pub fn show_commit_diff(&self, commit_id: &str) -> Result<String> {
let commit = self.repo.read_commit(&commit_id.to_string())?;
let new_tree = self.repo.read_tree(&commit.tree)?;
let old_tree = if !commit.parents.is_empty() {
let parent = self.repo.read_commit(&commit.parents[0])?;
self.repo.read_tree(&parent.tree)?
} else {
Tree::new(vec![])
};
Ok(self.diff_trees(&old_tree, &new_tree))
}
pub fn interdiff(&self, commit_a: &str, commit_b: &str) -> Result<String> {
let head_id = self.repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let a_id = self.resolve_commit_pub(commit_a, &head_id)?;
let b_id = self.resolve_commit_pub(commit_b, &head_id)?;
let a_commit = self.repo.read_commit(&a_id)?;
let b_commit = self.repo.read_commit(&b_id)?;
let a_tree = self.repo.read_tree(&a_commit.tree)?;
let b_tree = self.repo.read_tree(&b_commit.tree)?;
Ok(self.diff_trees(&a_tree, &b_tree))
}
pub fn diff_working_tree(&self, commit_id: Option<&str>) -> Result<String> {
let base_tree = if let Some(id) = commit_id {
let commit = self.repo.read_commit(&id.to_string())?;
self.repo.read_tree(&commit.tree)?
} else {
self.head_tree()?
};
let base_map: std::collections::HashMap<String, String> = base_tree
.entries.iter().map(|e| (e.name.clone(), e.id.clone())).collect();
let wt_files = self.walk_working_tree(&self.repo_path)?;
let mut wt_entries: Vec<TreeEntry> = Vec::new();
for file in &wt_files {
let relative = file.strip_prefix(&self.repo_path).unwrap_or(file);
let relative_str = relative.to_string_lossy().to_string();
let content = std::fs::read(file)?;
let blob_id = self.repo.write_blob(&content)?;
wt_entries.push(TreeEntry { mode: 0o100644, name: relative_str, id: blob_id });
}
let wt_names: std::collections::HashSet<&str> =
wt_entries.iter().map(|e| e.name.as_str()).collect();
for name in base_map.keys() {
if !wt_names.contains(name.as_str()) {
}
}
let wt_tree = Tree::new(wt_entries);
Ok(self.diff_trees(&base_tree, &wt_tree))
}
pub fn file_search(&self, pattern: &str) -> Result<Vec<(String, usize, String)>> {
let tree = self.head_tree()?;
let mut results = Vec::new();
let pattern_lower = pattern.to_lowercase();
for entry in &tree.entries {
if let Ok(blob) = self.repo.read_blob(&entry.id) {
let content = String::from_utf8_lossy(&blob.content);
for (i, line) in content.lines().enumerate() {
if line.to_lowercase().contains(&pattern_lower) {
results.push((entry.name.clone(), i + 1, line.to_string()));
}
}
}
}
Ok(results)
}
pub fn file_search_names(&self, pattern: &str) -> Result<Vec<String>> {
let tree = self.head_tree()?;
let pattern_lower = pattern.to_lowercase();
Ok(tree.entries.iter()
.filter(|e| e.name.to_lowercase().contains(&pattern_lower))
.map(|e| e.name.clone())
.collect())
}
pub fn forks(&self) -> Result<Vec<(String, String)>> {
let branches = self.repo.refs().list_branches()?;
let mut child_count: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
let mut commit_msgs: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for branch in &branches {
if let Some(tip) = self.repo.refs().get_branch(branch)? {
let mut current = tip;
loop {
let commit = self.repo.read_commit(¤t)?;
commit_msgs.entry(current.clone()).or_insert_with(|| commit.message.lines().next().unwrap_or("").to_string());
if commit.parents.is_empty() {
break;
}
let parent = &commit.parents[0];
*child_count.entry(parent.clone()).or_insert(0) += 1;
commit_msgs.entry(parent.clone()).or_insert_with(|| {
self.repo.read_commit(parent).ok()
.and_then(|c| c.message.lines().next().map(|s| s.to_string()))
.unwrap_or_default()
});
current = parent.clone();
}
}
}
let mut forks: Vec<(String, String)> = child_count.iter()
.filter(|&(_, &count)| count > 1)
.map(|(hash, _)| (hash.clone(), commit_msgs.get(hash).cloned().unwrap_or_default()))
.collect();
forks.sort();
Ok(forks)
}
pub fn merge_point(&self, commit_a: &str, commit_b: &str) -> Result<Option<String>> {
let head_id = self.repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let a_id = self.resolve_commit_pub(commit_a, &head_id)?;
let b_id = self.resolve_commit_pub(commit_b, &head_id)?;
let mut ancestors_a: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut current = a_id.clone();
loop {
ancestors_a.insert(current.clone());
let commit = self.repo.read_commit(¤t)?;
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
let mut current = b_id.clone();
loop {
if ancestors_a.contains(¤t) {
return Ok(Some(current));
}
let commit = self.repo.read_commit(¤t)?;
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
Ok(None)
}
pub fn verify_commit(&self, commit_spec: &str) -> Result<Vec<String>> {
let head_id = self.repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let commit_id = self.resolve_commit_pub(commit_spec, &head_id)?;
let mut issues = Vec::new();
let commit = match self.repo.read_commit(&commit_id) {
Ok(c) => c,
Err(_) => {
issues.push(format!("Commit {} not found in object store", commit_spec));
return Ok(issues);
}
};
if self.repo.read_tree(&commit.tree).is_err() {
issues.push(format!("Tree {} not found for commit {}", commit.tree, commit_spec));
}
for (i, parent) in commit.parents.iter().enumerate() {
if self.repo.read_commit(parent).is_err() {
issues.push(format!("Parent {} ({}) not found for commit {}", i, parent, commit_spec));
}
}
if let Ok(tree) = self.repo.read_tree(&commit.tree) {
for entry in &tree.entries {
if self.repo.read_blob(&entry.id).is_err() {
issues.push(format!("Blob {} not found for file '{}' in commit {}", entry.id, entry.name, commit_spec));
}
}
}
Ok(issues)
}
pub async fn run_across_commits(&self, from_spec: &str, command: &[String]) -> Result<Vec<(String, bool)>> {
let repo = self.repo.clone();
let repo_path = self.repo_path.clone();
let from_spec = from_spec.to_string();
let command = command.to_vec();
tokio::task::spawn_blocking(move || -> Result<Vec<(String, bool)>> {
let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0 };
let head_id = repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let from_id = mgr.resolve_commit(&from_spec, &head_id)?;
let mut commits: Vec<String> = Vec::new();
let mut current = head_id.clone();
loop {
commits.push(current.clone());
if current == from_id {
break;
}
let commit = repo.read_commit(¤t)?;
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
commits.reverse();
let mut results = Vec::new();
for commit_hash in &commits {
mgr.sync_index_to_commit(commit_hash)?;
mgr.restore_working_tree_pub(commit_hash)?;
if command.is_empty() {
results.push((commit_hash.clone(), false));
continue;
}
let status = std::process::Command::new(&command[0])
.args(&command[1..])
.current_dir(&repo_path)
.status();
let success = status.map(|s| s.success()).unwrap_or(false);
results.push((commit_hash.clone(), success));
}
mgr.sync_index_to_commit(&head_id)?;
mgr.restore_working_tree_pub(&head_id)?;
Ok(results)
})
.await?
}
pub fn file_list(&self, commit_spec: Option<&str>) -> Result<Vec<String>> {
let tree = if let Some(spec) = commit_spec {
let head_id = self.repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let commit_id = self.resolve_commit_pub(spec, &head_id)?;
let commit = self.repo.read_commit(&commit_id)?;
self.repo.read_tree(&commit.tree)?
} else {
self.head_tree()?
};
Ok(tree.entries.iter().map(|e| e.name.clone()).collect())
}
pub fn heads(&self) -> Result<Vec<(String, String)>> {
let branches = self.repo.refs().list_branches()?;
let mut result = Vec::new();
for branch in &branches {
if let Some(commit_id) = self.repo.refs().get_branch(branch)? {
result.push((branch.clone(), commit_id));
}
}
Ok(result)
}
pub fn file_log(&self, file_path: &str) -> Result<Vec<(String, u64, String)>> {
let head_id = self.repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let mut results = Vec::new();
let mut current = head_id;
let mut prev_blob: Option<String> = None;
loop {
let commit = self.repo.read_commit(¤t)?;
let tree = self.repo.read_tree(&commit.tree)?;
let current_blob = tree.entries.iter()
.find(|e| e.name == file_path)
.map(|e| e.id.clone());
if current_blob != prev_blob {
let first_line = commit.message.lines().next().unwrap_or("").to_string();
results.push((current.clone(), commit.timestamp, first_line));
prev_blob = current_blob;
}
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
Ok(results)
}
pub fn blame(&self, file_path: &str) -> Result<Vec<(usize, String, String)>> {
let head_id = self.repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let head_commit = self.repo.read_commit(&head_id)?;
let head_tree = self.repo.read_tree(&head_commit.tree)?;
let blob_id = head_tree.entries.iter()
.find(|e| e.name == file_path)
.map(|e| e.id.clone())
.context(format!("File '{}' not found in HEAD", file_path))?;
let content = self.repo.read_blob(&blob_id)?.content;
let text = String::from_utf8_lossy(&content);
let lines: Vec<&str> = text.lines().collect();
let mut line_commits: Vec<String> = vec![head_id.clone(); lines.len()];
let mut current = head_id.clone();
let mut prev_lines: Option<Vec<String>> = None;
loop {
let commit = self.repo.read_commit(¤t)?;
let tree = self.repo.read_tree(&commit.tree)?;
let current_blob = tree.entries.iter()
.find(|e| e.name == file_path)
.map(|e| e.id.clone());
if let Some(blob_id) = ¤t_blob {
let c = self.repo.read_blob(blob_id)?.content;
let c_text = String::from_utf8_lossy(&c);
let c_lines: Vec<String> = c_text.lines().map(|s| s.to_string()).collect();
if let Some(ref prev) = prev_lines {
for (i, line) in c_lines.iter().enumerate() {
if i < line_commits.len()
&& prev.get(i).map(|s| s.as_str()) != Some(line.as_str())
{
line_commits[i] = current.clone();
}
}
}
prev_lines = Some(c_lines);
} else {
prev_lines = None;
}
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
let mut result = Vec::new();
for (i, line) in lines.iter().enumerate() {
let short = &line_commits[i][..7.min(line_commits[i].len())];
result.push((i + 1, short.to_string(), line.to_string()));
}
Ok(result)
}
pub fn clean(&self) -> Result<Vec<String>> {
let head_tree = self.head_tree()?;
let tracked: std::collections::HashSet<String> = head_tree
.entries.iter().map(|e| e.name.clone()).collect();
let wt_files = self.walk_working_tree(&self.repo_path)?;
let mut removed = Vec::new();
for file in &wt_files {
let relative = file.strip_prefix(&self.repo_path).unwrap_or(file);
let relative_str = relative.to_string_lossy().to_string();
if !tracked.contains(&relative_str) {
std::fs::remove_file(file)?;
removed.push(relative_str);
}
}
Ok(removed)
}
pub fn gc(&self) -> Result<usize> {
let branches = self.repo.refs().list_branches()?;
let mut reachable: std::collections::HashSet<String> = std::collections::HashSet::new();
for branch in &branches {
if let Ok(Some(commit_id)) = self.repo.refs().get_branch(branch) {
let mut current = commit_id;
loop {
if reachable.contains(¤t) {
break;
}
reachable.insert(current.clone());
let commit = match self.repo.read_commit(¤t) {
Ok(c) => c,
Err(_) => break,
};
reachable.insert(commit.tree.clone());
if let Ok(tree) = self.repo.read_tree(&commit.tree) {
for entry in &tree.entries {
reachable.insert(entry.id.clone());
}
}
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
}
}
let objects_dir = self.repo.root().join("objects");
let mut removed = 0;
if !objects_dir.exists() {
return Ok(0);
}
for entry in std::fs::read_dir(&objects_dir)? {
let entry = entry?;
if !entry.file_type()?.is_dir() {
continue;
}
let dir_name = entry.file_name().to_string_lossy().to_string();
if dir_name.len() != 2 {
continue;
}
for file_entry in std::fs::read_dir(entry.path())? {
let file_entry = file_entry?;
let file_name = file_entry.file_name().to_string_lossy().to_string();
let hash = format!("{}{}", dir_name, file_name);
if !reachable.contains(&hash) {
std::fs::remove_file(file_entry.path())?;
removed += 1;
}
}
}
Ok(removed)
}
fn diff_trees(&self, old: &Tree, new: &Tree) -> String {
let old_map: std::collections::HashMap<&String, &String> = old
.entries
.iter()
.map(|e| (&e.name, &e.id))
.collect();
let new_map: std::collections::HashMap<&String, &String> = new
.entries
.iter()
.map(|e| (&e.name, &e.id))
.collect();
let all_names: std::collections::BTreeSet<&String> = old_map.keys().chain(new_map.keys()).copied().collect();
let mut diff = String::new();
for name in all_names {
let old_blob = old_map.get(name);
let new_blob = new_map.get(name);
match (old_blob, new_blob) {
(Some(o), Some(n)) if o == n => continue,
(Some(o), Some(n)) => {
diff.push_str(&format!("diff --git a/{} b/{}\n", name, name));
let old_content = self.repo.read_blob(o).map(|b| b.content).unwrap_or_default();
let new_content = self.repo.read_blob(n).map(|b| b.content).unwrap_or_default();
diff.push_str(&self.unified_diff(name, &old_content, &new_content));
}
(None, Some(n)) => {
diff.push_str(&format!("diff --git a/{} b/{}\n", name, name));
diff.push_str("new file\n");
let new_content = self.repo.read_blob(n).map(|b| b.content).unwrap_or_default();
diff.push_str(&self.unified_diff(name, &[], &new_content));
}
(Some(o), None) => {
diff.push_str(&format!("diff --git a/{} b/{}\n", name, name));
diff.push_str("deleted file\n");
let old_content = self.repo.read_blob(o).map(|b| b.content).unwrap_or_default();
diff.push_str(&self.unified_diff(name, &old_content, &[]));
}
(None, None) => {}
}
}
diff
}
}