use super::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorktreeLane {
pub path: PathBuf,
pub branch: String,
pub base: Option<String>,
}
impl WorktreeLane {
pub fn plan(repo: &Path, name: &str) -> Option<Self> {
let slug = lane_slug(name)?;
let parent = repo.parent()?;
let base = repo.file_name()?.to_string_lossy();
Some(Self {
path: parent.join(format!("{base}-{slug}")),
branch: format!("agent/{slug}"),
base: None,
})
}
}
pub(super) fn lane_slug(name: &str) -> Option<String> {
let mapped: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
let mut out = String::new();
for part in mapped.split('-').filter(|p| !p.is_empty()) {
if !out.is_empty() {
out.push('-');
}
out.push_str(part);
}
if out.is_empty() {
return None;
}
let capped: String = out.chars().take(60).collect();
let capped = capped.trim_matches('-');
(!capped.is_empty()).then(|| capped.to_string())
}
pub fn lane_removal_block(lane: &Path) -> Option<String> {
let Some(path_str) = lane.to_str() else {
return Some(format!("{} is not a readable path", lane.display()));
};
let output = Git::new()
.at(path_str)
.args(["status", "--porcelain", "--ignored"])
.into_command()
.output();
let Ok(output) = output else {
return Some(String::from(
"could not run git to check for uncommitted work",
));
};
if !output.status.success() {
return Some(format!("{path_str} does not look like a git worktree"));
}
let dirty = String::from_utf8_lossy(&output.stdout);
let mut changed = 0usize;
let mut ignored = 0usize;
for line in dirty.lines().filter(|l| !l.trim().is_empty()) {
if line.starts_with("!!") {
ignored += 1;
} else {
changed += 1;
}
}
match (changed, ignored) {
(0, 0) => None,
(0, n) => Some(format!(
"this lane has {n} ignored file{} (build output, local config) that removal would \
delete — clear them by hand first",
if n == 1 { "" } else { "s" }
)),
(1, _) => Some(String::from(
"this lane has 1 file with uncommitted changes — commit or discard it first",
)),
(n, _) => Some(format!(
"this lane has {n} files with uncommitted changes — commit or discard them first"
)),
}
}
pub fn add_worktree_lane(repo: &Path, lane: &mut WorktreeLane) -> Result<(), String> {
let Some(path) = lane.path.to_str().map(str::to_owned) else {
return Err(String::from("lane path is not valid UTF-8"));
};
let base = current_branch(repo);
run_git_mut(repo, &["worktree", "add", "-b", &lane.branch, &path])?;
lane.base = base;
Ok(())
}
pub fn remove_worktree_lane(lane: &Path) -> Result<(), String> {
let Some(path) = lane.to_str() else {
return Err(String::from("lane path is not valid UTF-8"));
};
run_git_mut(lane, &["worktree", "remove", path])
}
pub fn pr_worktree_path(repo: &Path, number: u64) -> Option<PathBuf> {
let name = repo.file_name()?.to_str()?;
Some(repo.parent()?.join(format!("{name}-pr-{number}")))
}
pub fn remote_for_slug(repo: &Path, slug: &str) -> String {
let slug = slug.to_ascii_lowercase();
let names = |url: &str| {
let url = url.trim().to_ascii_lowercase();
let url = url.strip_suffix(".git").unwrap_or(&url).to_string();
url.ends_with(&format!("/{slug}")) || url.ends_with(&format!(":{slug}"))
};
run_git(repo, &["remote", "-v"])
.ok()
.and_then(|out| {
out.lines().find_map(|l| {
let mut parts = l.split_whitespace();
let (name, url) = (parts.next()?, parts.next()?);
names(url).then(|| name.to_string())
})
})
.unwrap_or_else(|| format!("https://github.com/{slug}.git"))
}
pub(super) fn is_worktree_of(repo: &Path, path: &Path) -> bool {
let want = path.canonicalize().ok();
run_git(repo, &["worktree", "list", "--porcelain"]).is_ok_and(|out| {
out.lines()
.filter_map(|l| l.strip_prefix("worktree "))
.any(|w| Path::new(w).canonicalize().ok() == want)
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrWorktree {
pub oid: String,
pub created: bool,
}
pub fn checkout_pr_worktree(
repo: &Path,
remote: &str,
number: u64,
path: &Path,
previous: Option<&str>,
) -> Result<PrWorktree, String> {
let Some(path_s) = path.to_str() else {
return Err(String::from("worktree path is not valid UTF-8"));
};
let Some(repo_s) = repo.to_str() else {
return Err(String::from("repository path is not valid UTF-8"));
};
let fetch = Git::new()
.at(repo_s)
.args(["fetch", "--quiet", remote])
.arg(format!("refs/pull/{number}/head"))
.never_prompting()
.into_command()
.output()
.map_err(|e| e.to_string())?;
if !fetch.status.success() {
let err = String::from_utf8_lossy(&fetch.stderr);
return Err(err
.trim()
.lines()
.next()
.unwrap_or("git fetch failed")
.to_string());
}
let oid = run_git(repo, &["rev-parse", "FETCH_HEAD"])
.map_err(|e| e.to_string())?
.trim()
.to_string();
if path.exists() {
if !is_worktree_of(repo, path) {
return Err(format!(
"{path_s} already exists and is not a worktree of this repository"
));
}
let head = worktree_head(path);
if head.as_deref() != Some(oid.as_str()) {
if let Some(why) = lane_removal_block(path) {
return Err(format!("the existing checkout has work in it: {why}"));
}
if previous.is_none() || head.as_deref() != previous {
return Err(format!(
"{path_s} is at a commit review mode did not check out — put that work on a branch, or remove the worktree"
));
}
}
run_git_mut(path, &["checkout", "--quiet", "--detach", &oid])?;
Ok(PrWorktree {
oid,
created: false,
})
} else {
run_git_mut(repo, &["worktree", "add", "--detach", path_s, &oid])?;
Ok(PrWorktree { oid, created: true })
}
}
pub fn worktree_head(path: &Path) -> Option<String> {
run_git(path, &["rev-parse", "HEAD"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
pub fn pr_worktree_keep_reason(path: &Path, checked_out: &str) -> Option<String> {
if let Some(why) = lane_removal_block(path) {
return Some(why);
}
match worktree_head(path) {
Some(head) if head == checked_out => None,
Some(_) => Some(String::from(
"it has commits beyond the pull request's head — put them on a branch first",
)),
None => Some(String::from("git cannot read its HEAD")),
}
}