use std::{
collections::BTreeSet,
fs,
path::{Path, PathBuf},
process::{Command, Output},
sync::atomic::{AtomicUsize, Ordering},
};
use crate::{Error, Result};
#[derive(Debug)]
pub struct TempDir(PathBuf);
static NEXT: AtomicUsize = AtomicUsize::new(0);
impl TempDir {
pub fn new() -> Result<Self> {
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
let dir =
std::env::temp_dir().join(format!("sokf-pack-{}-{n}-{nanos:08x}", std::process::id()));
fs::create_dir_all(&dir).map_err(|e| Error::io(&dir, e))?;
Ok(TempDir(dir))
}
pub fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn git(dir: Option<&Path>, args: &[&str]) -> Result<Output> {
let mut cmd = Command::new("git");
if let Some(dir) = dir {
cmd.current_dir(dir);
}
cmd.env("GIT_TERMINAL_PROMPT", "0");
cmd.args(["-c", "core.autocrlf=false", "-c", "core.eol=lf"]);
cmd.args(args)
.output()
.map_err(|e| Error::Pack(format!("cannot run `git`: {e}")))
}
const NO_CONVERSION: &str = "* -text -ident -filter -working-tree-encoding\n";
fn checkout(repo: &Path, rev: &str) -> Result<()> {
let info = repo.join(".git").join("info");
fs::create_dir_all(&info).map_err(|e| Error::io(&info, e))?;
let attributes = info.join("attributes");
fs::write(&attributes, NO_CONVERSION).map_err(|e| Error::io(&attributes, e))?;
checked(Some(repo), &["checkout", "--quiet", "--force", rev])?;
Ok(())
}
fn checked(dir: Option<&Path>, args: &[&str]) -> Result<String> {
let out = git(dir, args)?;
if !out.status.success() {
return Err(Error::Pack(format!(
"`git {}` failed: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
)));
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
#[derive(Debug)]
pub struct Clone {
pub dir: TempDir,
pub git_ref: String,
pub commit: String,
}
impl Clone {
pub fn worktree(&self) -> PathBuf {
self.dir.path().join("repo")
}
pub fn executables(&self) -> Result<BTreeSet<String>> {
let out = git(Some(&self.worktree()), &["ls-tree", "-r", "-z", "HEAD"])?;
if !out.status.success() {
return Err(Error::Pack(format!(
"`git ls-tree` failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
Ok(String::from_utf8_lossy(&out.stdout)
.split('\0')
.filter_map(|entry| {
let (meta, path) = entry.split_once('\t')?;
meta.starts_with("100755 ").then(|| path.to_string())
})
.collect())
}
}
pub fn shallow_clone(source: &str, git_ref: Option<&str>) -> Result<Clone> {
let dir = TempDir::new()?;
let repo = dir.path().join("repo");
let repo_arg = repo.to_string_lossy().into_owned();
let clone = ["clone", "--quiet", "--no-checkout", "--depth", "1"];
let git_ref = match git_ref {
None => {
checked(None, &[&clone[..], &["--", source, &repo_arg]].concat())?;
checkout(&repo, "HEAD")?;
checked(Some(&repo), &["rev-parse", "--abbrev-ref", "HEAD"])?
}
Some(r) => {
let branch = git(
None,
&[&clone[..], &["--branch", r, "--", source, &repo_arg]].concat(),
)?;
if branch.status.success() {
checkout(&repo, "HEAD")?;
} else {
let _ = fs::remove_dir_all(&repo);
checked(None, &["init", "--quiet", &repo_arg])?;
checked(
Some(&repo),
&["fetch", "--quiet", "--depth", "1", "--", source, r],
)?;
checkout(&repo, "FETCH_HEAD")?;
}
r.to_string()
}
};
let commit = checked(Some(&repo), &["rev-parse", "HEAD"])?;
Ok(Clone {
dir,
git_ref,
commit,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Merge {
pub text: Vec<u8>,
pub conflicted: bool,
}
pub fn merge_file(current: &[u8], base: &[u8], upstream: &[u8], label: &str) -> Result<Merge> {
let dir = TempDir::new()?;
let write = |name: &str, bytes: &[u8]| -> Result<String> {
let p = dir.path().join(name);
fs::write(&p, bytes).map_err(|e| Error::io(&p, e))?;
Ok(p.to_string_lossy().into_owned())
};
let (c, b, u) = (
write("current", current)?,
write("base", base)?,
write("upstream", upstream)?,
);
let out = git(
None,
&[
"merge-file",
"-p",
"-L",
label,
"-L",
"base",
"-L",
"upstream",
&c,
&b,
&u,
],
)?;
match out.status.code() {
Some(0) => Ok(Merge {
text: out.stdout,
conflicted: false,
}),
Some(n) if (1..=127).contains(&n) => Ok(Merge {
text: out.stdout,
conflicted: true,
}),
_ => Err(Error::Pack(format!(
"`git merge-file` failed on {label}: {}",
String::from_utf8_lossy(&out.stderr).trim()
))),
}
}
pub fn diff(rel: &str, base: &[u8], current: Option<&[u8]>) -> Result<String> {
diff_modes(rel, Some(base), current, None)
}
pub fn diff_modes(
rel: &str,
base: Option<&[u8]>,
current: Option<&[u8]>,
modes: Option<(bool, bool)>,
) -> Result<String> {
let dir = TempDir::new()?;
let write = |side: &str, bytes: &[u8]| -> Result<()> {
let p = dir.path().join(side).join(rel);
if let Some(parent) = p.parent() {
fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
}
fs::write(&p, bytes).map_err(|e| Error::io(&p, e))
};
let side = |name: &str, bytes: Option<&[u8]>| -> Result<String> {
match bytes {
Some(bytes) => {
write(name, bytes)?;
Ok(format!("{name}/{rel}"))
}
None => Ok("/dev/null".to_string()),
}
};
let a = side("a", base)?;
let b = side("b", current)?;
if let Some((old, new)) = modes {
let sides = [("a", base.map(|_| old)), ("b", current.map(|_| new))];
for (side, bit) in sides {
if let Some(bit) = bit {
let p = dir.path().join(side).join(rel);
super::mode::set_executable(&p, bit).map_err(|e| Error::io(&p, e))?;
}
}
}
let out = git(
Some(dir.path()),
&[
"-c",
"core.quotePath=false",
"diff",
"--no-index",
"--no-color",
"--no-ext-diff",
"--no-prefix",
"--",
&a,
&b,
],
)?;
match out.status.code() {
Some(0) | Some(1) => Ok(String::from_utf8_lossy(&out.stdout).into_owned()),
_ => Err(Error::Pack(format!(
"`git diff` failed on {rel}: {}",
String::from_utf8_lossy(&out.stderr).trim()
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_merge_keeps_both_changes_or_marks_the_conflict() {
let base = b"one\ntwo\nthree\nfour\nfive\n";
let current = b"one\nTWO\nthree\nfour\nfive\n";
let upstream = b"one\ntwo\nthree\nfour\nFIVE\n";
let m = merge_file(current, base, upstream, "/knowledge/a.md").unwrap();
assert!(!m.conflicted);
assert_eq!(m.text, b"one\nTWO\nthree\nfour\nFIVE\n");
let m = merge_file(current, base, b"one\n2\nthree\nfour\nfive\n", "/k/a.md").unwrap();
assert!(m.conflicted);
let text = String::from_utf8(m.text).unwrap();
assert!(text.contains("<<<<<<< /k/a.md\n"), "{text}");
assert!(text.contains(">>>>>>> upstream\n"), "{text}");
}
#[test]
fn a_diff_names_the_paths_of_the_pack() {
let d = diff("schemas/a.md", b"x\n", Some(b"y\n")).unwrap();
assert!(d.contains("--- a/schemas/a.md\n"), "{d}");
assert!(d.contains("+++ b/schemas/a.md\n"), "{d}");
assert!(d.contains("-x\n+y\n"), "{d}");
assert_eq!(diff("schemas/a.md", b"x\n", Some(b"x\n")).unwrap(), "");
}
#[cfg(unix)]
#[test]
fn a_diff_carries_the_executable_bit_of_each_side() {
let rel = "files/run.sh";
let d = diff_modes(rel, Some(b"x\n"), Some(b"x\n"), Some((false, true))).unwrap();
assert!(d.contains("old mode 100644\nnew mode 100755\n"), "{d}");
let d = diff_modes(rel, Some(b"x\n"), Some(b"y\n"), Some((true, true))).unwrap();
assert!(d.contains(" 100755\n"), "{d}");
assert!(!d.contains("old mode"), "{d}");
let d = diff_modes(rel, Some(b"x\n"), None, Some((true, false))).unwrap();
assert!(d.contains("deleted file mode 100755\n"), "{d}");
}
#[cfg(unix)]
#[test]
fn a_new_file_carries_its_executable_bit() {
let rel = "files/scripts/new.sh";
let d = diff_modes(rel, None, Some(b"x\n"), Some((false, true))).unwrap();
assert!(d.contains("new file mode 100755\n"), "{d}");
assert!(
d.contains("--- /dev/null\n+++ b/files/scripts/new.sh\n"),
"{d}"
);
let d = diff_modes(rel, None, Some(b"x\n"), Some((false, false))).unwrap();
assert!(d.contains("new file mode 100644\n"), "{d}");
}
#[test]
fn a_temporary_directory_goes_when_dropped() {
let dir = TempDir::new().unwrap();
let path = dir.path().to_path_buf();
assert!(path.is_dir());
drop(dir);
assert!(!path.exists());
}
}