use std::{
path::{Path, PathBuf},
time::Duration,
};
use rho_protocol::{ErrorCode, RpcError, SessionWorktree, WorktreeReport, WorktreeVerdict};
use super::{open::Workspace, Sessions};
use crate::{
app::daemon_host::jobs::{unix_now, JobRecord, JobSubject},
worktree::{Checkout, Holds},
};
const STALE_AFTER: Duration = Duration::from_secs(14 * 24 * 60 * 60);
const QUIET_BEFORE_DAILY: Duration = Duration::from_secs(24 * 60 * 60);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::app::daemon_host) enum Prune {
Daily,
Now,
DryRun,
}
impl Prune {
fn checks(self, updated_at: u64, now: u64) -> bool {
match self {
Self::Daily => now.saturating_sub(updated_at) >= QUIET_BEFORE_DAILY.as_secs(),
Self::Now | Self::DryRun => true,
}
}
}
pub(in crate::app::daemon_host) struct InUse(Vec<PathBuf>);
impl InUse {
fn holds(&self, worktree: &Path) -> bool {
self.0
.iter()
.any(|workspace| workspace.starts_with(worktree))
}
}
pub(super) async fn add_for_session(
root: &Path,
workspace: &Workspace,
) -> Result<(Workspace, SessionWorktree), RpcError> {
let added = crate::worktree::add(root, workspace.path())
.await
.map_err(|error| {
RpcError::new(
ErrorCode::SessionOpenFailed,
format!("could not open session in a worktree: {error}"),
)
})?;
tracing::info!(
branch = %added.worktree.branch,
path = %added.worktree.path.display(),
"added a session worktree"
);
let workspace =
Workspace::parse(&added.cwd).map_err(|error| kept(error, Some(&added.worktree)))?;
Ok((workspace, added.worktree))
}
pub(super) fn kept(mut error: RpcError, worktree: Option<&SessionWorktree>) -> RpcError {
if let Some(worktree) = worktree {
error.message = format!(
"{}; the worktree added for it stays at {} on branch {}",
error.message,
worktree.path.display(),
worktree.branch
);
}
error
}
pub(in crate::app::daemon_host) fn worktree_stale(
record: &JobRecord,
in_use: &InUse,
now: u64,
) -> bool {
record.worktree.as_ref().is_some_and(|worktree| {
now.saturating_sub(record.updated_at) >= STALE_AFTER.as_secs()
&& !in_use.holds(&worktree.path)
&& worktree.path.exists()
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Restore {
Turns,
Reading,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
pub(super) enum Restored {
Nothing,
OnBranch,
ForReading,
}
impl Sessions {
pub(super) async fn restore_worktree(
&self,
record: &mut JobRecord,
purpose: Restore,
) -> Result<Restored, RpcError> {
let (Some(worktree), Some(commit)) = (&record.worktree, &record.worktree_removed_at) else {
return Ok(Restored::Nothing);
};
let failed = |error: crate::worktree::WorktreeError| {
RpcError::new(
ErrorCode::SessionOpenFailed,
format!(
"could not add back the session's worktree at {} on branch {}: {error}",
worktree.path.display(),
worktree.branch
),
)
};
if worktree.path.exists() {
crate::worktree::remove(worktree).await.map_err(failed)?;
}
let restore =
|checkout| crate::worktree::restore(worktree, commit, &record.workspace, checkout);
let restored = match (restore(Checkout::Branch).await, purpose) {
(Ok(()), _) => Ok(Checkout::Branch),
(Err(error), Restore::Reading) => {
tracing::warn!(
branch = %worktree.branch,
%error,
"could not add back a session worktree on its branch; checking its commit out alone to read it"
);
restore(Checkout::Detached)
.await
.map(|()| Checkout::Detached)
}
(Err(error), Restore::Turns) => Err(error),
};
let checkout = restored.map_err(failed)?;
tracing::info!(
branch = %worktree.branch,
path = %worktree.path.display(),
%commit,
?checkout,
"restored a session worktree"
);
match checkout {
Checkout::Branch => {
record.worktree_removed_at = None;
self.jobs.set_worktree_removed_at(&record.id, None);
Ok(Restored::OnBranch)
}
Checkout::Detached => Ok(Restored::ForReading),
}
}
pub(super) async fn end_read_checkout(record: &JobRecord) {
let Some(worktree) = &record.worktree else {
return;
};
if let Err(error) = crate::worktree::remove(worktree).await {
tracing::warn!(
path = %worktree.path.display(),
%error,
"could not remove the checkout a read of a session added"
);
}
}
pub(in crate::app::daemon_host) fn worktrees_in_use(&self, records: &[JobRecord]) -> InUse {
let loaded = self.loaded();
InUse(
records
.iter()
.filter(|record| {
record.state.in_progress()
|| matches!(&record.subject, JobSubject::Session { session } if loaded.contains_key(session))
})
.map(|record| record.workspace.clone())
.collect(),
)
}
pub(in crate::app::daemon_host) async fn prune_worktrees(
&self,
prune: Prune,
) -> Vec<WorktreeReport> {
let mut reports = Vec::new();
for listed in self.jobs.list() {
let (Some(_), JobSubject::Session { session }) = (&listed.worktree, &listed.subject)
else {
continue;
};
let _reopening = self.reopening.lock(session).await;
let Some(record) = self.jobs.get(&listed.id) else {
continue;
};
if !prune.checks(record.updated_at, unix_now()) {
continue;
}
reports.extend(self.prune_worktree(&record, prune).await);
}
let removed = reports
.iter()
.filter(|report| matches!(report.verdict, WorktreeVerdict::Merged { .. }))
.count();
tracing::info!(
?prune,
removed,
kept = reports.len() - removed,
"pruned session worktrees"
);
reports
}
pub(super) async fn prune_worktree(
&self,
record: &JobRecord,
prune: Prune,
) -> Option<WorktreeReport> {
let worktree = record.worktree.as_ref()?;
if !worktree.path.exists() {
return None;
}
let in_use = self.worktrees_in_use(&self.jobs.list());
let verdict = match in_use.holds(&worktree.path) {
true => WorktreeVerdict::InUse,
false => match crate::worktree::inspect(worktree).await {
Ok(Holds::Changes) => WorktreeVerdict::Dirty,
Ok(Holds::Unmerged { base }) => WorktreeVerdict::Unmerged { base },
Ok(Holds::Merged { base, commit }) => match prune {
Prune::DryRun => WorktreeVerdict::Merged { base },
Prune::Daily | Prune::Now => match crate::worktree::remove(worktree).await {
Ok(()) => {
self.jobs
.set_worktree_removed_at(&record.id, Some(commit.clone()));
tracing::info!(
branch = %worktree.branch,
path = %worktree.path.display(),
%base,
%commit,
"removed a merged session worktree"
);
WorktreeVerdict::Merged { base }
}
Err(error) => WorktreeVerdict::Failed {
error: error.to_string(),
},
},
},
Err(error) => WorktreeVerdict::Failed {
error: error.to_string(),
},
},
};
let stale = worktree_stale(record, &in_use, unix_now());
Some(WorktreeReport {
job: (&record.id).into(),
worktree: worktree.clone(),
verdict,
stale,
})
}
}
#[cfg(test)]
#[path = "worktree_tests.rs"]
mod tests;