use serde::{Deserialize, Serialize};
use std::{
ffi::OsStr,
path::{Path, PathBuf},
};
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Identity {
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "crate::platform::path_serde::option"
)]
pub common_dir: Option<PathBuf>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "crate::platform::path_serde::option"
)]
pub worktree_path: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
}
fn git(path: &Path, args: &[&str]) -> Option<Vec<u8>> {
let args = [OsStr::new("-C"), path.as_os_str()]
.into_iter()
.chain(args.iter().map(OsStr::new));
crate::process::tool_output("git", args)
}
fn git_path(path: &Path, arg: &str) -> Option<PathBuf> {
let output = git(path, &["rev-parse", "--path-format=absolute", arg])?;
let path = crate::platform::path_from_line(&output);
crate::platform::canonicalize(&path).ok()
}
pub fn checked_out_branch(path: &Path) -> Option<String> {
git(path, &["symbolic-ref", "--quiet", "--short", "HEAD"]).map(|bytes| {
crate::platform::output_text(crate::platform::fingerprint_line_ending(&bytes).0)
.into_owned()
})
}
pub fn identify(path: &Path) -> Identity {
let common_dir = git_path(path, "--git-common-dir");
let worktree_path = git_path(path, "--show-toplevel");
if common_dir.is_none() || worktree_path.is_none() {
return Identity::default();
}
let branch = checked_out_branch(path);
Identity {
common_dir,
worktree_path,
branch,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Worktree {
pub path: PathBuf,
pub branch: Option<String>,
}
pub fn worktrees(common_dir: &Path) -> Vec<Worktree> {
let args = [OsStr::new("--git-dir"), common_dir.as_os_str()]
.into_iter()
.chain(["worktree", "list", "--porcelain", "-z"].map(OsStr::new));
crate::process::tool_output("git", args)
.map(|output| parse_worktrees(&output))
.unwrap_or_default()
.into_iter()
.filter(|tree| crate::platform::paths::target_exists(&tree.path).unwrap_or(false))
.collect()
}
fn parse_worktrees(bytes: &[u8]) -> Vec<Worktree> {
let mut trees: Vec<(Worktree, bool)> = Vec::new();
for field in bytes.split(|byte| *byte == 0) {
if let Some(path) = field.strip_prefix(b"worktree ") {
let path = crate::platform::path_from_bytes(path);
trees.push((Worktree { path, branch: None }, false));
} else if let Some((tree, _)) = trees.last_mut()
&& let Some(branch) = field.strip_prefix(b"branch refs/heads/")
{
tree.branch = Some(crate::platform::output_text(branch).into_owned());
} else if let Some((_, prunable)) = trees.last_mut()
&& (field == b"prunable" || field.starts_with(b"prunable "))
{
*prunable = true;
}
}
trees
.into_iter()
.filter_map(|(tree, prunable)| (!prunable).then_some(tree))
.collect()
}
#[cfg(test)]
mod tests;