use anyhow::{Context, Result};
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
fn find_flush(data: &[u8]) -> Option<usize> {
let mut pos = 0;
while pos + 4 <= data.len() {
let len_hex = &data[pos..pos + 4];
if len_hex == b"0000" {
return Some(pos);
}
if let Ok(s) = std::str::from_utf8(len_hex) {
if let Ok(len) = usize::from_str_radix(s, 16) {
if len < 4 || pos + len > data.len() {
break;
}
pos += len;
} else {
break;
}
} else {
break;
}
}
None
}
fn advertisement_only(data: &[u8]) -> Vec<u8> {
match find_flush(data) {
Some(pos) => data[..pos + 4].to_vec(),
None => data.to_vec(),
}
}
fn strip_advertisement(data: &[u8]) -> Vec<u8> {
match find_flush(data) {
Some(pos) => data[pos + 4..].to_vec(),
None => data.to_vec(),
}
}
pub fn advertise_refs(repo_path: &Path) -> Result<Vec<u8>> {
let grit = crate::grit_executable();
let mut cmd = Command::new(&grit);
cmd.arg("receive-pack")
.arg(repo_path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd
.spawn()
.with_context(|| format!("failed to spawn '{} receive-pack'", grit.display()))?;
drop(child.stdin.take());
let output = child
.wait_with_output()
.context("failed to wait for receive-pack")?;
if output.stdout.is_empty() && !output.status.success() {
let err = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("receive-pack advertisement failed: {}", err.trim());
}
Ok(advertisement_only(&output.stdout))
}
pub fn stateless_rpc(repo_path: &Path, request_body: &[u8]) -> Result<Vec<u8>> {
let grit = crate::grit_executable();
let mut cmd = Command::new(&grit);
cmd.arg("receive-pack")
.arg(repo_path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd
.spawn()
.with_context(|| format!("failed to spawn '{} receive-pack'", grit.display()))?;
if let Some(mut stdin) = child.stdin.take() {
let _ = stdin.write_all(request_body);
}
let output = child
.wait_with_output()
.context("failed to wait for receive-pack")?;
if !output.status.success() {
let err = String::from_utf8_lossy(&output.stderr);
if !output.stdout.is_empty() {
eprintln!("receive-pack stderr (non-fatal): {}", err.trim());
return Ok(strip_advertisement(&output.stdout));
}
anyhow::bail!("receive-pack failed: {}", err.trim());
}
Ok(strip_advertisement(&output.stdout))
}