feat(api): extend commit and diff services with new functionality
- Add FindCommit, ListCommitsByOid, CommitIsAncestor RPCs to CommitService - Add CheckObjectsExist, CommitsByMessage, GetCommitStats RPCs to CommitService - Add LastCommitForPath, CountCommits, CountDivergingCommits RPCs to CommitService - Add RawDiff, RawPatch, FindChangedPaths RPCs to DiffService - Add FindMergeBase, WriteRef, SearchFilesByContent RPCs to RepositoryService - Add SearchFilesByName, ObjectsSize, RepositorySize RPCs to RepositoryService - Add FindLicense, OptimizeRepository, GetRawChanges RPCs to RepositoryService - Add FetchRemote, CreateRepositoryFromURL RPCs to RepositoryService - Implement server handlers for all new RPC methods - Add new modules for commit counting, finding, and querying features - Add new modules for diff changed paths and raw operations - Add new modules for refs and remote operations - Remove unnecessary comments from various source files - Update proto definitions with new message types and service methods
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
use crate::bare::GitBare;
|
||||
use crate::error::GitResult;
|
||||
use crate::pb::*;
|
||||
|
||||
impl GitBare {
|
||||
/// Count commits in a revision range or path.
|
||||
pub fn count_commits(&self, request: CountCommitsRequest) -> GitResult<CountCommitsResponse> {
|
||||
let revision = if request.revision.is_empty() { "HEAD" } else { &request.revision };
|
||||
crate::sanitize::validate_revision(revision)?;
|
||||
|
||||
let mut args = vec![
|
||||
"--git-dir".to_string(),
|
||||
self.bare_dir.to_string_lossy().into_owned(),
|
||||
"rev-list".to_string(),
|
||||
"--count".to_string(),
|
||||
];
|
||||
|
||||
if !request.since.is_empty() {
|
||||
args.push(format!("--since={}", request.since));
|
||||
}
|
||||
if !request.until.is_empty() {
|
||||
args.push(format!("--until={}", request.until));
|
||||
}
|
||||
|
||||
args.push(revision.to_string());
|
||||
|
||||
if !request.path.is_empty() {
|
||||
args.push("--".to_string());
|
||||
args.push(request.path.clone());
|
||||
}
|
||||
|
||||
let output = std::process::Command::new("git")
|
||||
.args(&args)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.map_err(|e| crate::error::GitError::CommandFailed {
|
||||
status_code: None,
|
||||
stderr: e.to_string(),
|
||||
})?;
|
||||
|
||||
let count = String::from_utf8_lossy(&output.stdout)
|
||||
.trim()
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0);
|
||||
|
||||
Ok(CountCommitsResponse { count })
|
||||
}
|
||||
|
||||
/// Count diverging commits between two branches (left vs right).
|
||||
pub fn count_diverging_commits(&self, request: CountDivergingCommitsRequest) -> GitResult<CountDivergingCommitsResponse> {
|
||||
crate::sanitize::validate_revision(&request.left)?;
|
||||
crate::sanitize::validate_revision(&request.right)?;
|
||||
|
||||
let output = std::process::Command::new("git")
|
||||
.args([
|
||||
"--git-dir",
|
||||
&self.bare_dir.to_string_lossy(),
|
||||
"rev-list",
|
||||
"--count",
|
||||
"--left-right",
|
||||
&format!("{}...{}", request.left, request.right),
|
||||
])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.map_err(|e| crate::error::GitError::CommandFailed {
|
||||
status_code: None,
|
||||
stderr: e.to_string(),
|
||||
})?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
// Format: "<left_count>\t<right_count>"
|
||||
let parts: Vec<&str> = stdout.split('\t').collect();
|
||||
let left_count = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let right_count = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
|
||||
Ok(CountDivergingCommitsResponse { left_count, right_count })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use crate::bare::GitBare;
|
||||
use crate::error::{GitError, GitResult};
|
||||
use crate::pb::*;
|
||||
|
||||
impl GitBare {
|
||||
/// Find a single commit by revision.
|
||||
pub fn find_commit(&self, request: FindCommitRequest) -> GitResult<Commit> {
|
||||
let revision = match request.revision.and_then(|s| s.selector) {
|
||||
Some(object_selector::Selector::Oid(oid)) => oid.hex,
|
||||
Some(object_selector::Selector::Revision(name)) => name.revision,
|
||||
None => "HEAD".to_string(),
|
||||
};
|
||||
crate::sanitize::validate_revision(&revision)?;
|
||||
|
||||
let repo = self.gix_repo()?;
|
||||
let oid = repo.rev_parse_single(revision.as_str())
|
||||
.map_err(|e| GitError::Gix(e.to_string()))?;
|
||||
let commit = oid.object()
|
||||
.map_err(|e| GitError::Gix(e.to_string()))?
|
||||
.try_into_commit()
|
||||
.map_err(|e| GitError::Gix(format!("not a commit: {e}")))?;
|
||||
|
||||
Ok(crate::commit::get_commit::commit_to_pb(self, &commit, request.include_stats))
|
||||
}
|
||||
|
||||
/// Batch lookup commits by OID list.
|
||||
pub fn list_commits_by_oid(&self, request: ListCommitsByOidRequest) -> GitResult<ListCommitsByOidResponse> {
|
||||
let repo = self.gix_repo()?;
|
||||
let mut commits = Vec::new();
|
||||
|
||||
for oid_bytes in &request.oids {
|
||||
let hex: String = oid_bytes.iter().map(|b| format!("{b:02x}")).collect();
|
||||
if let Ok(oid) = gix::ObjectId::from_hex(hex.as_bytes()) {
|
||||
if let Ok(obj) = repo.find_object(oid) {
|
||||
if let Ok(commit) = obj.try_into_commit() {
|
||||
commits.push(crate::commit::get_commit::commit_to_pb(self, &commit, request.include_stats));
|
||||
}
|
||||
}
|
||||
}
|
||||
if commits.len() >= 100 { break; }
|
||||
}
|
||||
|
||||
Ok(ListCommitsByOidResponse { commits })
|
||||
}
|
||||
}
|
||||
+47
-43
@@ -12,48 +12,52 @@ impl GitBare {
|
||||
.object()?
|
||||
.try_into_commit()
|
||||
.map_err(|e| GitError::Gix(e.to_string()))?;
|
||||
let hex = commit.id.to_string();
|
||||
let tree_hex = commit.tree_id()?.to_string();
|
||||
let message = commit.message_raw()?.to_string();
|
||||
let (subject, body) = message
|
||||
.split_once('\n')
|
||||
.map(|(s, b)| (s.to_string(), b.trim_start_matches('\n').to_string()))
|
||||
.unwrap_or_else(|| (message.clone(), String::new()));
|
||||
let author_sig = commit.author().ok();
|
||||
let committer_sig = commit.committer().ok();
|
||||
Ok(Commit {
|
||||
oid: Some(self.oid_to_pb(hex.clone())),
|
||||
abbreviated_oid: commit
|
||||
.short_id()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|_| hex.chars().take(7).collect()),
|
||||
parent_oids: commit
|
||||
.parent_ids()
|
||||
.map(|p| self.oid_to_pb(p.to_string()))
|
||||
.collect(),
|
||||
tree_oid: Some(self.oid_to_pb(tree_hex)),
|
||||
author: author_sig.as_ref().map(gix_sig_to_pb),
|
||||
committer: committer_sig.as_ref().map(gix_sig_to_pb),
|
||||
subject,
|
||||
body,
|
||||
message,
|
||||
trailers: Vec::new(),
|
||||
signature: None,
|
||||
stats: None,
|
||||
authored_at: author_sig.as_ref().map(|s| prost_types::Timestamp {
|
||||
seconds: s.seconds(),
|
||||
nanos: 0,
|
||||
}),
|
||||
committed_at: committer_sig.as_ref().map(|s| prost_types::Timestamp {
|
||||
seconds: s.seconds(),
|
||||
nanos: 0,
|
||||
}),
|
||||
raw: if request.include_raw {
|
||||
commit.data.clone()
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
})
|
||||
Ok(commit_to_pb(self, &commit, request.include_raw))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn commit_to_pb(gb: &GitBare, commit: &gix::Commit<'_>, include_raw: bool) -> Commit {
|
||||
let hex = commit.id.to_string();
|
||||
let tree_hex = commit.tree_id().map(|t| t.to_string()).unwrap_or_default();
|
||||
let message = commit.message_raw().map(|m| m.to_string()).unwrap_or_default();
|
||||
let (subject, body) = message
|
||||
.split_once('\n')
|
||||
.map(|(s, b)| (s.to_string(), b.trim_start_matches('\n').to_string()))
|
||||
.unwrap_or_else(|| (message.clone(), String::new()));
|
||||
let author_sig = commit.author().ok();
|
||||
let committer_sig = commit.committer().ok();
|
||||
Commit {
|
||||
oid: Some(gb.oid_to_pb(hex.clone())),
|
||||
abbreviated_oid: commit
|
||||
.short_id()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|_| hex.chars().take(7).collect()),
|
||||
parent_oids: commit
|
||||
.parent_ids()
|
||||
.map(|p| gb.oid_to_pb(p.to_string()))
|
||||
.collect(),
|
||||
tree_oid: Some(gb.oid_to_pb(tree_hex)),
|
||||
author: author_sig.as_ref().map(gix_sig_to_pb),
|
||||
committer: committer_sig.as_ref().map(gix_sig_to_pb),
|
||||
subject,
|
||||
body,
|
||||
message,
|
||||
trailers: Vec::new(),
|
||||
signature: None,
|
||||
stats: None,
|
||||
authored_at: author_sig.as_ref().map(|s| prost_types::Timestamp {
|
||||
seconds: s.seconds(),
|
||||
nanos: 0,
|
||||
}),
|
||||
committed_at: committer_sig.as_ref().map(|s| prost_types::Timestamp {
|
||||
seconds: s.seconds(),
|
||||
nanos: 0,
|
||||
}),
|
||||
raw: if include_raw {
|
||||
commit.data.clone()
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,4 +74,4 @@ pub(crate) fn gix_sig_to_pb(sig: &gix::actor::SignatureRef<'_>) -> crate::pb::Si
|
||||
}),
|
||||
timezone_offset: time.map(|t| t.offset / 60).unwrap_or(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
pub mod cherry_pick_commit;
|
||||
pub mod compare_commits;
|
||||
pub mod count_commits;
|
||||
pub mod create_commit;
|
||||
pub mod find_commit;
|
||||
pub mod get_commit;
|
||||
pub mod get_commit_ancestors;
|
||||
pub mod list_commits;
|
||||
pub mod query;
|
||||
pub mod revert_commit;
|
||||
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
use crate::bare::GitBare;
|
||||
use crate::error::GitResult;
|
||||
use crate::pb::*;
|
||||
|
||||
impl GitBare {
|
||||
/// Search commits by message content.
|
||||
pub fn commits_by_message(&self, request: CommitsByMessageRequest) -> GitResult<CommitsByMessageResponse> {
|
||||
let revision = if request.revision.is_empty() { "HEAD" } else { &request.revision };
|
||||
crate::sanitize::validate_revision(revision)?;
|
||||
|
||||
let limit = if request.limit == 0 { 20 } else { request.limit.min(200) };
|
||||
|
||||
let mut args = vec![
|
||||
"--git-dir".to_string(),
|
||||
self.bare_dir.to_string_lossy().into_owned(),
|
||||
"log".to_string(),
|
||||
format!("--max-count={}", limit),
|
||||
"--format=%H".to_string(),
|
||||
];
|
||||
|
||||
if request.case_insensitive {
|
||||
args.push(format!("--grep={}", request.query));
|
||||
args.push("-i".to_string());
|
||||
} else {
|
||||
args.push(format!("--grep={}", request.query));
|
||||
}
|
||||
|
||||
if !revision.is_empty() && revision != "HEAD" {
|
||||
args.push(revision.to_string());
|
||||
} else {
|
||||
args.push("--all".to_string());
|
||||
}
|
||||
|
||||
let output = std::process::Command::new("git")
|
||||
.args(&args)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.output()
|
||||
.map_err(|e| crate::error::GitError::CommandFailed {
|
||||
status_code: None,
|
||||
stderr: e.to_string(),
|
||||
})?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let repo = self.gix_repo()?;
|
||||
let mut commits = Vec::new();
|
||||
|
||||
for line in stdout.lines().skip(request.offset as usize) {
|
||||
let hex = line.trim();
|
||||
if let Ok(oid) = gix::ObjectId::from_hex(hex.as_bytes()) {
|
||||
if let Ok(obj) = repo.find_object(oid) {
|
||||
if let Ok(commit) = obj.try_into_commit() {
|
||||
commits.push(crate::commit::get_commit::commit_to_pb(self, &commit, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CommitsByMessageResponse { commits })
|
||||
}
|
||||
|
||||
/// Batch check if objects/revisions exist.
|
||||
pub fn check_objects_exist(&self, request: CheckObjectsExistRequest) -> GitResult<CheckObjectsExistResponse> {
|
||||
let repo = self.gix_repo()?;
|
||||
let mut revisions = Vec::new();
|
||||
|
||||
for rev in &request.revisions {
|
||||
crate::sanitize::validate_revision(rev)?;
|
||||
let exists = repo.rev_parse_single(rev.as_str()).is_ok();
|
||||
revisions.push(RevisionExistence {
|
||||
revision: rev.clone(),
|
||||
exists,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(CheckObjectsExistResponse { revisions })
|
||||
}
|
||||
|
||||
/// Get stats for a single commit.
|
||||
pub fn get_commit_stats(&self, request: GetCommitStatsRequest) -> GitResult<CommitStats> {
|
||||
let revision = match request.revision.and_then(|s| s.selector) {
|
||||
Some(object_selector::Selector::Oid(oid)) => oid.hex,
|
||||
Some(object_selector::Selector::Revision(name)) => name.revision,
|
||||
None => "HEAD".to_string(),
|
||||
};
|
||||
crate::sanitize::validate_revision(&revision)?;
|
||||
|
||||
let output = std::process::Command::new("git")
|
||||
.args([
|
||||
"--git-dir",
|
||||
&self.bare_dir.to_string_lossy(),
|
||||
"diff-tree",
|
||||
"--numstat",
|
||||
&format!("{revision}^!"),
|
||||
])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.map_err(|e| crate::error::GitError::CommandFailed {
|
||||
status_code: None,
|
||||
stderr: e.to_string(),
|
||||
})?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let mut additions = 0u32;
|
||||
let mut deletions = 0u32;
|
||||
let mut changed_files = 0u32;
|
||||
|
||||
for line in stdout.lines() {
|
||||
let parts: Vec<&str> = line.split('\t').collect();
|
||||
if parts.len() >= 2 {
|
||||
if let Ok(add) = parts[0].parse::<u32>() {
|
||||
additions += add;
|
||||
}
|
||||
if let Ok(del) = parts[1].parse::<u32>() {
|
||||
deletions += del;
|
||||
}
|
||||
changed_files += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CommitStats { additions, deletions, changed_files })
|
||||
}
|
||||
|
||||
/// Get the last commit for a given path.
|
||||
pub fn last_commit_for_path(&self, request: LastCommitForPathRequest) -> GitResult<LastCommitForPathResponse> {
|
||||
crate::sanitize::validate_file_path(&request.path)?;
|
||||
let revision = if request.revision.is_empty() { "HEAD" } else { &request.revision };
|
||||
crate::sanitize::validate_revision(revision)?;
|
||||
|
||||
let args = vec![
|
||||
"--git-dir".to_string(),
|
||||
self.bare_dir.to_string_lossy().into_owned(),
|
||||
"log".to_string(),
|
||||
"-1".to_string(),
|
||||
"--format=%H".to_string(),
|
||||
revision.to_string(),
|
||||
"--".to_string(),
|
||||
request.path.clone(),
|
||||
];
|
||||
|
||||
let _ = request.literal_pathspec;
|
||||
|
||||
let output = std::process::Command::new("git")
|
||||
.args(&args)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.map_err(|e| crate::error::GitError::CommandFailed {
|
||||
status_code: None,
|
||||
stderr: e.to_string(),
|
||||
})?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let hex = stdout.lines().next().unwrap_or("").trim().to_string();
|
||||
|
||||
if hex.is_empty() {
|
||||
return Ok(LastCommitForPathResponse { commit: None, path: request.path });
|
||||
}
|
||||
|
||||
let repo = self.gix_repo()?;
|
||||
let commit = if let Ok(oid) = gix::ObjectId::from_hex(hex.as_bytes()) {
|
||||
repo.find_object(oid).ok().and_then(|obj| {
|
||||
obj.try_into_commit().ok().map(|c| {
|
||||
crate::commit::get_commit::commit_to_pb(self, &c, false)
|
||||
})
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(LastCommitForPathResponse { commit, path: request.path })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user