use std::{
ffi::OsStr,
fmt,
path::{Path, PathBuf},
process::Stdio,
time::Duration,
};
use rho_protocol::SessionWorktree;
use crate::{
config::Config,
process_tree::{ProcessTree as _, SupervisedTree},
};
mod squash;
mod unowned;
mod size;
pub(crate) use size::size;
pub(crate) use unowned::unowned;
const REMOTE: &str = "origin";
const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Start {
Head,
Remote,
}
impl Start {
pub(crate) fn of(config: &Config) -> Self {
match config.worktree_from_remote {
true => Self::Remote,
false => Self::Head,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Started {
Head,
Remote(String),
FellBack(String),
}
impl fmt::Display for Started {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Head => formatter.write_str("HEAD"),
Self::Remote(branch) => formatter.write_str(branch),
Self::FellBack(reason) => write!(
formatter,
"HEAD, since {REMOTE}'s default branch could not be fetched: {reason}"
),
}
}
}
pub(crate) fn root(rho_home: &Path) -> PathBuf {
rho_home.join("worktrees")
}
#[derive(Debug)]
pub(crate) struct Added {
pub(crate) worktree: SessionWorktree,
pub(crate) cwd: PathBuf,
pub(crate) started: Started,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum WorktreeError {
#[error(
"{} is not in a git repository, so no worktree can be added for it",
.0.display()
)]
NotARepository(PathBuf),
#[error("could not run git: {0}")]
NoGit(#[source] std::io::Error),
#[error("git {action} failed in {}: {detail}", repository.display())]
Git {
action: String,
repository: PathBuf,
detail: String,
},
#[error("could not create {}: {error}", path.display())]
Io {
path: PathBuf,
#[source]
error: std::io::Error,
},
#[error("{error}; the worktree stays at {} on branch {branch}", path.display())]
Kept {
path: PathBuf,
branch: String,
#[source]
error: Box<WorktreeError>,
},
#[error(
"the rho daemon opened the session without a worktree, as a daemon older than this rho does; \
run `rho daemon restart` once its jobs finish, then try again"
)]
DaemonIgnored,
}
enum Ran {
Succeeded(String),
Failed { code: Option<i32>, stderr: String },
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Holds {
Changes,
Merged { base: String, commit: String },
Unmerged { base: String },
}
pub(crate) async fn add(
root: &Path,
workspace: &Path,
start: Start,
) -> Result<Added, WorktreeError> {
let toplevel = match git(
workspace,
["rev-parse", "--show-toplevel"],
&[("LC_ALL", "C")],
)
.await?
{
Ran::Succeeded(stdout) => canonical(Path::new(&stdout))?,
Ran::Failed { stderr, .. } if stderr.contains("not a git repository") => {
return Err(WorktreeError::NotARepository(workspace.to_path_buf()));
}
Ran::Failed { stderr: detail, .. } => {
return Err(WorktreeError::Git {
action: "rev-parse".to_owned(),
repository: workspace.to_path_buf(),
detail,
});
}
};
let repository_name = toplevel.file_name().map(|name| name.to_string_lossy());
let name = format!(
"{}-{}",
branch_safe(&repository_name.unwrap_or_default()),
&uuid::Uuid::new_v4().simple().to_string()[..8]
);
let branch = format!("rho/{name}");
std::fs::create_dir_all(root).map_err(|error| WorktreeError::Io {
path: root.to_path_buf(),
error,
})?;
let path = canonical(root)?.join(&name);
let head = || "HEAD".to_owned();
let (started, commit) = match start {
Start::Head => (Started::Head, head()),
Start::Remote => match tokio::time::timeout(FETCH_TIMEOUT, fetch_tip(&toplevel)).await {
Ok(Ok(Some(tip))) => (Started::Remote(tip.label), tip.commit),
Ok(Ok(None)) => (Started::Head, head()),
Ok(Err(error)) => (Started::FellBack(error.to_string()), head()),
Err(_) => {
let secs = FETCH_TIMEOUT.as_secs();
let reason = format!("{REMOTE} did not answer within {secs} seconds");
(Started::FellBack(reason), head())
}
},
};
let args: [&OsStr; 6] = [
"worktree".as_ref(),
"add".as_ref(),
"-b".as_ref(),
branch.as_ref(),
path.as_os_str(),
commit.as_ref(),
];
if let Ran::Failed { stderr: detail, .. } = git(&toplevel, args, &[]).await? {
return Err(WorktreeError::Git {
action: format!("worktree add {} on branch {branch}", path.display()),
repository: toplevel,
detail,
});
}
let kept = |error| WorktreeError::Kept {
path: path.clone(),
branch: branch.clone(),
error: Box::new(error),
};
let canonical_path = canonical(&path).map_err(kept)?;
let inside = workspace.strip_prefix(&toplevel).map_err(|_| {
kept(WorktreeError::Git {
action: "rev-parse".to_owned(),
repository: workspace.to_path_buf(),
detail: format!(
"the repository root {} does not hold it",
toplevel.display()
),
})
})?;
let cwd = match inside.as_os_str().is_empty() {
true => canonical_path.clone(),
false => canonical_path.join(inside),
};
std::fs::create_dir_all(&cwd).map_err(|error| {
kept(WorktreeError::Io {
path: cwd.clone(),
error,
})
})?;
Ok(Added {
worktree: SessionWorktree {
branch,
path: canonical_path,
origin: workspace.to_path_buf(),
},
cwd,
started,
})
}
struct RemoteTip {
label: String,
commit: String,
}
async fn fetch_tip(repository: &Path) -> Result<Option<RemoteTip>, WorktreeError> {
let remotes = succeeded(repository, "remote", ["remote"]).await?;
if !remotes.lines().any(|remote| remote == REMOTE) {
return Ok(None);
}
let listed = remote(
repository,
"ls-remote",
["ls-remote", "--symref", REMOTE, "HEAD"],
)
.await?;
let branch = listed
.lines()
.find_map(|line| {
line.strip_prefix("ref: refs/heads/")?
.strip_suffix("\tHEAD")
})
.ok_or_else(|| no_default(repository))?;
fetch_branch(repository, branch).await?;
let head = format!("refs/remotes/{REMOTE}/HEAD");
let target = format!("refs/remotes/{REMOTE}/{branch}");
let record = ["symbolic-ref", head.as_str(), target.as_str()];
succeeded(repository, "symbolic-ref", record).await?;
remote_tip(repository)
.await?
.ok_or_else(|| no_default(repository))
.map(Some)
}
async fn fetch_branch(repository: &Path, branch: &str) -> Result<(), WorktreeError> {
let refspec = format!("+refs/heads/{branch}:refs/remotes/{REMOTE}/{branch}");
let fetch = [
"fetch",
"--quiet",
"--no-tags",
"--no-write-fetch-head",
"--no-recurse-submodules",
REMOTE,
refspec.as_str(),
];
remote(repository, "fetch", fetch).await.map(drop)
}
fn no_default(repository: &Path) -> WorktreeError {
WorktreeError::Git {
action: "ls-remote".to_owned(),
repository: repository.to_path_buf(),
detail: format!("{REMOTE} names no default branch"),
}
}
async fn remote_default(repository: &Path) -> Result<Option<String>, WorktreeError> {
let reference = format!("refs/remotes/{REMOTE}/HEAD");
let read = ["symbolic-ref", "--quiet", reference.as_str()];
let prefix = format!("refs/remotes/{REMOTE}/");
Ok(answered(repository, "symbolic-ref", read)
.await?
.and_then(|target| target.strip_prefix(&prefix).map(str::to_owned)))
}
async fn remote_tip(repository: &Path) -> Result<Option<RemoteTip>, WorktreeError> {
let Some(branch) = remote_default(repository).await? else {
return Ok(None);
};
let object = format!("refs/remotes/{REMOTE}/{branch}^{{commit}}");
let verify = ["rev-parse", "--verify", "--quiet", object.as_str()];
Ok(answered(repository, "rev-parse", verify)
.await?
.map(|commit| RemoteTip {
label: format!("{REMOTE}/{branch}"),
commit,
}))
}
pub(crate) async fn inspect(worktree: &SessionWorktree) -> Result<Holds, WorktreeError> {
let status = succeeded(
&worktree.path,
"status",
[
"status",
"--porcelain",
"--untracked-files=all",
"--ignore-submodules=none",
],
)
.await?;
if !status.is_empty() {
return Ok(Holds::Changes);
}
let head = succeeded(&worktree.path, "rev-parse", ["rev-parse", "HEAD"]).await?;
let origin = &worktree.origin;
let base_commit = succeeded(origin, "rev-parse", ["rev-parse", "HEAD"]).await?;
let base = match succeeded(origin, "rev-parse", ["rev-parse", "--abbrev-ref", "HEAD"]).await? {
detached if detached == "HEAD" => {
let short = ["rev-parse", "--short", base_commit.as_str()];
succeeded(origin, "rev-parse", short).await?
}
branch => branch,
};
if has_changes_of(origin, &base_commit, &head).await? {
return Ok(Holds::Merged { base, commit: head });
}
if let Some(tip) = remote_tip(origin)
.await?
.filter(|tip| tip.commit != base_commit)
{
if has_changes_of(origin, &tip.commit, &head).await? {
let base = tip.label;
return Ok(Holds::Merged { base, commit: head });
}
}
Ok(Holds::Unmerged { base })
}
async fn has_changes_of(dir: &Path, base: &str, commit: &str) -> Result<bool, WorktreeError> {
let ancestor = ["merge-base", "--is-ancestor", commit, base];
if answered(dir, "merge-base", ancestor).await?.is_some() {
return Ok(true);
}
let range = format!("{base}..{commit}");
let merges = ["rev-list", "--merges", "--max-count=1", range.as_str()];
if succeeded(dir, "rev-list", merges).await?.is_empty() {
let cherry = succeeded(dir, "cherry", ["cherry", base, commit]).await?;
if !cherry.is_empty() && cherry.lines().all(|line| line.starts_with('-')) {
return Ok(true);
}
}
let merge = ["merge-tree", "--write-tree", base, commit];
match answered(dir, "merge-tree", merge).await {
Ok(Some(tree)) => {
let base_tree = format!("{base}^{{tree}}");
let base_tree = succeeded(dir, "rev-parse", ["rev-parse", base_tree.as_str()]).await?;
if tree.lines().next() == Some(base_tree.as_str()) {
return Ok(true);
}
}
Ok(None) => {}
Err(error) => {
tracing::warn!(
%error,
"could not merge a worktree's branch in memory (it needs git 2.38 or later)"
);
}
}
match squash::squashed_into(dir, base, commit).await {
Ok(squashed) => Ok(squashed),
Err(error) => {
tracing::warn!(%error, "could not look for a worktree branch's squash commit");
Ok(false)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Admin {
pub(crate) moved_at: Option<std::time::SystemTime>,
pub(crate) locked: bool,
}
pub(crate) async fn admin(path: &Path) -> Result<Admin, WorktreeError> {
let dir = succeeded(path, "rev-parse", ["rev-parse", "--absolute-git-dir"]).await?;
let dir = Path::new(&dir);
let moved_at = [dir.join("HEAD"), dir.join("logs/HEAD")]
.iter()
.filter_map(|file| {
std::fs::metadata(file)
.and_then(|meta| meta.modified())
.ok()
})
.max();
Ok(Admin {
moved_at,
locked: dir.join("locked").exists(),
})
}
pub(crate) async fn remove(worktree: &SessionWorktree) -> Result<(), WorktreeError> {
let args: [&OsStr; 3] = [
"worktree".as_ref(),
"remove".as_ref(),
worktree.path.as_os_str(),
];
succeeded(&worktree.origin, "worktree remove", args)
.await
.map(drop)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Checkout {
Branch,
Detached,
}
pub(crate) async fn restore(
worktree: &SessionWorktree,
commit: &str,
cwd: &Path,
checkout: Checkout,
) -> Result<(), WorktreeError> {
let origin = &worktree.origin;
let path = worktree.path.as_os_str();
let branch: &OsStr = worktree.branch.as_ref();
let object = format!("{commit}^{{commit}}");
let exists = ["rev-parse", "--verify", "--quiet", object.as_str()];
let head;
let commit: &OsStr = match answered(origin, "rev-parse", exists).await? {
Some(_) => commit.as_ref(),
None => {
head = succeeded(origin, "rev-parse", ["rev-parse", "HEAD"]).await?;
tracing::warn!(
branch = %worktree.branch,
missing = %commit,
%head,
"git no longer has the commit a session worktree was removed at; \
adding it back at the origin's HEAD"
);
head.as_ref()
}
};
let args: Vec<&OsStr> = match checkout {
Checkout::Branch => {
let reference = format!("refs/heads/{}", worktree.branch);
let verify = ["rev-parse", "--verify", "--quiet", reference.as_str()];
match answered(origin, "rev-parse", verify).await? {
Some(_) => vec!["worktree".as_ref(), "add".as_ref(), path, branch],
None => vec![
"worktree".as_ref(),
"add".as_ref(),
"-b".as_ref(),
branch,
path,
commit,
],
}
}
Checkout::Detached => vec![
"worktree".as_ref(),
"add".as_ref(),
"--detach".as_ref(),
path,
commit,
],
};
succeeded(origin, "worktree add", args).await?;
std::fs::create_dir_all(cwd).map_err(|error| WorktreeError::Io {
path: cwd.to_path_buf(),
error,
})
}
pub(crate) fn require(asked: bool, opened: Option<&SessionWorktree>) -> Result<(), WorktreeError> {
match (asked, opened) {
(true, None) => Err(WorktreeError::DaemonIgnored),
(true, Some(_)) | (false, _) => Ok(()),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Removal {
Daemon,
Unowned,
}
pub(crate) fn hint(worktree: &SessionWorktree, removal: Removal) -> String {
let removal = match removal {
Removal::Daemon => "rho removes it once it is clean and merged, and keeps the branch",
Removal::Unowned => {
"rho removes it once it is clean, merged, and unused for a day, and keeps the branch"
}
};
format!(
"the session works in worktree {} on branch {}; {removal}",
worktree.path.display(),
worktree.branch
)
}
async fn succeeded(
dir: &Path,
action: &str,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> Result<String, WorktreeError> {
match git(dir, args, &[]).await? {
Ran::Succeeded(stdout) => Ok(stdout),
Ran::Failed { stderr, .. } => Err(WorktreeError::Git {
action: action.to_owned(),
repository: dir.to_path_buf(),
detail: stderr,
}),
}
}
async fn answered(
dir: &Path,
action: &str,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> Result<Option<String>, WorktreeError> {
match git(dir, args, &[]).await? {
Ran::Succeeded(stdout) => Ok(Some(stdout)),
Ran::Failed { code: Some(1), .. } => Ok(None),
Ran::Failed { stderr, .. } => Err(WorktreeError::Git {
action: action.to_owned(),
repository: dir.to_path_buf(),
detail: stderr,
}),
}
}
async fn remote(
dir: &Path,
action: &str,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> Result<String, WorktreeError> {
let mut command = command(dir, args, &[]);
SupervisedTree::prepare(&mut command);
let child = command
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(WorktreeError::NoGit)?;
let _tree = SupervisedTree::attach(&child).map_err(WorktreeError::NoGit)?;
let output = child
.wait_with_output()
.await
.map_err(WorktreeError::NoGit)?;
match ran(&output) {
Ran::Succeeded(stdout) => Ok(stdout),
Ran::Failed { stderr, .. } => Err(WorktreeError::Git {
action: action.to_owned(),
repository: dir.to_path_buf(),
detail: stderr,
}),
}
}
async fn git(
dir: &Path,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
env: &[(&str, &str)],
) -> Result<Ran, WorktreeError> {
let output = command(dir, args, env)
.output()
.await
.map_err(WorktreeError::NoGit)?;
Ok(ran(&output))
}
fn command(
dir: &Path,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
env: &[(&str, &str)],
) -> tokio::process::Command {
let mut command = tokio::process::Command::new("git");
for name in crate::git::LOCATION_ENV {
command.env_remove(name);
}
command.env("GIT_TERMINAL_PROMPT", "0");
command
.arg("-C")
.arg(dir)
.args(args)
.envs(env.iter().copied())
.stdin(Stdio::null());
command
}
fn ran(output: &std::process::Output) -> Ran {
let text = |bytes: &[u8]| String::from_utf8_lossy(bytes).trim().to_owned();
if output.status.success() {
Ran::Succeeded(text(&output.stdout))
} else {
Ran::Failed {
code: output.status.code(),
stderr: text(&output.stderr),
}
}
}
fn canonical(path: &Path) -> Result<PathBuf, WorktreeError> {
crate::paths::canonicalize(path).map_err(|error| WorktreeError::Io {
path: path.to_path_buf(),
error,
})
}
fn branch_safe(name: &str) -> String {
let safe: String = name
.chars()
.map(|char| match char {
'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '-' => char,
_ => '-',
})
.collect();
if safe.is_empty() {
"repository".to_owned()
} else {
safe
}
}
#[cfg(test)]
#[path = "worktree_tests.rs"]
mod tests;