use std::path::{Path, PathBuf};
use crate::constants::{format_config_key, CONFIG_KEY_BASE_BRANCH, CONFIG_KEY_BASE_PATH};
use crate::error::{CwError, Result};
use crate::git;
use crate::messages;
pub struct ResolvedTarget {
pub path: PathBuf,
pub branch: String,
pub repo: PathBuf,
}
#[derive(Debug)]
pub struct StrictTarget {
pub name: String,
pub branch: Option<String>,
pub path: PathBuf,
}
pub fn parse_repo_branch_target(target: &str) -> (Option<&str>, &str) {
if let Some((repo, branch)) = target.split_once(':') {
if !repo.is_empty() && !branch.is_empty() {
return (Some(repo), branch);
}
}
(None, target)
}
pub fn get_branch_for_worktree(repo: &Path, worktree_path: &Path) -> Option<String> {
let worktrees = git::parse_worktrees(repo).ok()?;
let resolved = git::canonicalize_or(worktree_path);
for (branch, path) in &worktrees {
let p_resolved = git::canonicalize_or(path);
if p_resolved == resolved {
if branch == "(detached)" {
return None;
}
return Some(git::normalize_branch_name(branch).to_string());
}
}
None
}
pub fn resolve_worktree_target(
target: Option<&str>,
lookup_mode: Option<&str>,
) -> Result<ResolvedTarget> {
let Some(target) = target else {
let cwd = std::env::current_dir()?;
let branch = git::get_current_branch(Some(&cwd))?;
let repo = git::get_repo_root(Some(&cwd))?;
return Ok(ResolvedTarget {
path: cwd,
branch,
repo,
});
};
let main_repo = git::get_main_repo_root(None)?;
let branch_match = if lookup_mode != Some("worktree") {
git::find_worktree_by_intended_branch(&main_repo, target)?
} else {
None
};
let worktree_match = if lookup_mode != Some("branch") {
git::find_worktree_by_name(&main_repo, target)?
} else {
None
};
match (branch_match, worktree_match) {
(Some(bp), Some(_wp)) => {
let repo = git::get_repo_root(Some(&bp))?;
Ok(ResolvedTarget {
path: bp,
branch: target.to_string(),
repo,
})
}
(Some(bp), None) => {
let repo = git::get_repo_root(Some(&bp))?;
Ok(ResolvedTarget {
path: bp,
branch: target.to_string(),
repo,
})
}
(None, Some(wp)) => {
let branch =
get_branch_for_worktree(&main_repo, &wp).unwrap_or_else(|| target.to_string());
let repo = git::get_repo_root(Some(&wp))?;
Ok(ResolvedTarget {
path: wp,
branch,
repo,
})
}
(None, None) => Err(CwError::WorktreeNotFound(messages::worktree_not_found(
target,
))),
}
}
pub fn get_worktree_metadata(branch: &str, repo: &Path) -> Result<(String, PathBuf)> {
let base_key = format_config_key(CONFIG_KEY_BASE_BRANCH, branch);
let path_key = format_config_key(CONFIG_KEY_BASE_PATH, branch);
let base_branch = git::get_config(&base_key, Some(repo));
let base_path_str = git::get_config(&path_key, Some(repo));
if let (Some(bb), Some(bp)) = (base_branch, base_path_str) {
return Ok((bb, PathBuf::from(bp)));
}
eprintln!(
"Warning: Metadata missing for branch '{}'. Attempting to infer...",
branch
);
let worktrees = git::parse_worktrees(repo)?;
let inferred_base_path = worktrees.first().map(|(_, p)| p.clone()).ok_or_else(|| {
CwError::Other(format!(
"Cannot infer base repository path for branch '{}'. Use 'gw new' to create worktrees.",
branch
))
})?;
let mut inferred_base_branch: Option<String> = None;
for candidate in &["main", "master", "develop"] {
if git::branch_exists(candidate, Some(&inferred_base_path)) {
inferred_base_branch = Some(candidate.to_string());
break;
}
}
if inferred_base_branch.is_none() {
if let Some((first_branch, _)) = worktrees.first() {
if first_branch != "(detached)" {
inferred_base_branch = Some(git::normalize_branch_name(first_branch).to_string());
}
}
}
let base = inferred_base_branch.ok_or_else(|| {
CwError::Other(format!(
"Cannot infer base branch for '{}'. Use 'gw new' to create worktrees.",
branch
))
})?;
eprintln!(" Inferred base branch: {}", base);
eprintln!(" Inferred base path: {}", inferred_base_path.display());
Ok((base, inferred_base_path))
}
pub fn resolve_target_strict(repo_root: &Path, target: &str) -> Result<StrictTarget> {
let worktrees = git::parse_worktrees(repo_root)?;
let main_path = worktrees
.first()
.map(|(_, p)| git::canonicalize_or(p))
.unwrap_or_default();
let make = |(branch_raw, path): &(String, PathBuf)| -> StrictTarget {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let normalized = git::normalize_branch_name(branch_raw);
let branch = if normalized == "(detached)" {
None
} else {
Some(normalized.to_string())
};
StrictTarget {
name,
branch,
path: path.clone(),
}
};
for entry in &worktrees {
let (_, path) = entry;
if git::canonicalize_or(path) == main_path {
continue;
}
let name = path
.file_name()
.map(|n| n.to_string_lossy())
.unwrap_or_default();
if name == target {
return Ok(make(entry));
}
}
for entry in &worktrees {
let (branch_raw, path) = entry;
if git::canonicalize_or(path) == main_path {
continue;
}
if git::normalize_branch_name(branch_raw) == target {
return Ok(make(entry));
}
}
let abs = PathBuf::from(target);
let abs_resolved = git::canonicalize_or(&abs);
for entry in &worktrees {
let (_, path) = entry;
let path_resolved = git::canonicalize_or(path);
if path_resolved == abs_resolved {
return Ok(make(entry));
}
}
Err(CwError::WorktreeNotFound(messages::target_not_found(
target,
)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_repo_branch_target() {
assert_eq!(
parse_repo_branch_target("myrepo:feat/x"),
(Some("myrepo"), "feat/x")
);
assert_eq!(parse_repo_branch_target("feat/x"), (None, "feat/x"));
assert_eq!(parse_repo_branch_target(":feat/x"), (None, ":feat/x"));
assert_eq!(parse_repo_branch_target("myrepo:"), (None, "myrepo:"));
}
}