use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Worktree {
pub repo: PathBuf,
pub path: PathBuf,
pub branch: String,
pub base: String,
}
fn git(dir: &Path, env: &[(String, String)], args: &[&str]) -> Result<String> {
let out = Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.env_clear()
.envs(env.iter().map(|(k, v)| (k, v)))
.output()
.context("running git")?;
if !out.status.success() {
bail!("{}", String::from_utf8_lossy(&out.stderr).trim());
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
pub fn create(
home: &Path,
cwd: &Path,
id: &str,
name: &str,
env: &[(String, String)],
) -> Result<(Worktree, PathBuf)> {
let repo = PathBuf::from(
git(cwd, env, &["rev-parse", "--show-toplevel"])
.context("--worktree needs a git repository")?,
);
let prefix = git(cwd, env, &["rev-parse", "--show-prefix"])?;
let base = git(cwd, env, &["rev-parse", "--short", "HEAD"])
.context("the repository has no commit to start the worktree from")?;
let repo_name = repo
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "repo".into());
let hash = crate::paths::fnv1a(repo.to_string_lossy().to_lowercase().as_bytes()) as u32;
let path = home
.join("worktrees")
.join(format!("{repo_name}-{hash:08x}"))
.join(id);
let branch = format!("axiopera/{name}");
let path_arg = path.to_string_lossy();
if let Err(e) = git(
&repo,
env,
&["worktree", "add", "-b", &branch, &path_arg, "HEAD"],
) {
if path.exists() {
let _ = git(&repo, env, &["worktree", "remove", "--force", &path_arg]);
let _ = git(&repo, env, &["branch", "-D", &branch]);
}
return Err(e.context("creating the worktree"));
}
let cwd = path.join(prefix);
Ok((
Worktree {
repo,
path,
branch,
base,
},
cwd,
))
}
pub fn remove(wt: &Worktree, env: &[(String, String)]) -> Result<Option<String>> {
if wt.path.exists() {
git(
&wt.repo,
env,
&["worktree", "remove", &wt.path.to_string_lossy()],
)?;
}
Ok(git(&wt.repo, env, &["branch", "-d", &wt.branch])
.err()
.map(|_| format!("branch {} kept: not merged", wt.branch)))
}