Skip to main content

workyard_git/
removal.rs

1//! Destructive worktree operations verify Git ownership independently of cached paths.
2mod dirty;
3mod protected;
4mod restoration;
5mod validation;
6
7use crate::{Repository, Runner, process::args};
8use workyard_core::{
9	Control, ObservationGit, Participant, Problem, ProblemCode, RemovalGit, RemovalObservation,
10	RetainedHistory,
11};
12
13impl RemovalGit for Runner {
14	async fn inspect_removal(
15		&self,
16		participant: &Participant,
17		control: &Control,
18	) -> Result<RemovalObservation, Problem> {
19		let facts = self.observe(participant, control).await?;
20		let Some(destination) = facts.path else {
21			return Err(blocked(
22				"Managed worktree is missing; repair its registration before removal.",
23			));
24		};
25		if destination != participant.destination {
26			match std::fs::symlink_metadata(&participant.destination) {
27				Ok(_) => {
28					return Err(blocked(
29						"The recorded participant location is occupied by other files. Inspect both locations before removing the worktree.",
30					));
31				}
32				Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
33				Err(error) => return Err(Problem::io("Inspect recorded worktree location", error)),
34			}
35		}
36		let worktree_entry = workyard_system::entry_identity(&destination)?;
37		let repository = Repository::local(self, &destination, control).await?;
38		let output = self
39			.checked(
40				&destination,
41				&args(&["rev-parse", "--path-format=absolute", "--git-dir"]),
42				control,
43			)
44			.await?;
45		let git_dir = crate::output::path_line(&output)
46			.map_err(|_| blocked("Invalid Git administrative path."))?;
47		if git_dir == repository.common_dir {
48			return Err(blocked(
49				"Main worktrees cannot be removed as task participants.",
50			));
51		}
52		if facts.conflicted {
53			return Err(blocked("Worktree has unresolved Git conflicts."));
54		}
55		validation::require_removable_admin(&git_dir, &repository.common_dir)?;
56
57		let branch = facts.branch.filter(|branch| branch != "HEAD");
58		let history = match &branch {
59			Some(branch) => self.retained_history(&destination, branch, control).await?,
60			None => {
61				self.require_retained_head(&destination, control).await?;
62				RetainedHistory::Detached
63			}
64		};
65		let (dirty_paths, dirty_token) =
66			dirty::inspect(self, &destination, worktree_entry, control).await?;
67		Ok(RemovalObservation {
68			administration_identity: workyard_system::directory_identity(&git_dir)?,
69			worktree_entry,
70			repository: repository.into(),
71			destination: Some(destination),
72			branch,
73			dirty_paths,
74			dirty_token,
75			history,
76		})
77	}
78
79	async fn remove_worktree(
80		&self,
81		observation: &RemovalObservation,
82		discard: bool,
83		control: &Control,
84		before_unlink: impl FnOnce() -> Result<(), Problem> + Send,
85	) -> Result<(), workyard_core::UnlinkFailure> {
86		let destination = observation
87			.destination
88			.as_ref()
89			.ok_or_else(|| blocked("Removal has no verified worktree destination."))?;
90
91		let _gate =
92			crate::relationships::relationship_lock(&observation.repository, control).await?;
93		let admin = self
94			.verify_removal_location(observation, destination, control)
95			.await?;
96		self.validate_disclosure(observation, destination, &admin, control)
97			.await?;
98
99		let mut arguments = args(&["worktree", "remove"]);
100		if discard {
101			arguments.push("--force".into());
102		}
103		arguments.push("--".into());
104		arguments.push(dunce::simplified(destination).into());
105
106		before_unlink()?;
107		self.effect(&observation.repository.common_dir, &arguments, control)
108			.await
109			.map_err(workyard_core::UnlinkFailure::Command)
110	}
111
112	async fn inspect_restoration(
113		&self,
114		participant: &Participant,
115		branch: &str,
116		control: &Control,
117	) -> Result<workyard_core::Repository, Problem> {
118		restoration::require_vacant_destination(&participant.destination)?;
119		let repository = restoration::backing_repository(self, participant, control).await?;
120		restoration::verify_registration(
121			self,
122			&repository,
123			branch,
124			&participant.destination,
125			control,
126		)
127		.await?;
128		Ok(repository.into())
129	}
130
131	async fn reconcile_recreation(
132		&self,
133		participant: &Participant,
134		branch: &str,
135		control: &Control,
136	) -> Result<workyard_core::RecoveryObservation, Problem> {
137		let mut participant = participant.clone();
138		participant.phase = workyard_core::Phase::WorktreeCreated;
139		let observed =
140			workyard_core::RecoveryGit::reconcile(self, &participant, branch, control).await?;
141		if observed.destination.is_none() || observed.operation_in_progress {
142			return Err(blocked(
143				"Successfully recreated worktree is missing or has unfinished Git work; inspect and repair it before recovery.",
144			));
145		}
146		Ok(observed)
147	}
148
149	async fn reconcile_restored(
150		&self,
151		participant: &Participant,
152		control: &Control,
153	) -> Result<workyard_core::RecoveryObservation, Problem> {
154		let facts = self.observe(participant, control).await?;
155		if let Some(problem) = facts.problem {
156			return Err(problem);
157		}
158		let destination = facts.path.ok_or_else(|| {
159			blocked("Restored worktree is missing; preserve state and inspect Git.")
160		})?;
161		let source = if participant
162			.source
163			.try_exists()
164			.map_err(|error| Problem::io("Inspect restored backing location", error))?
165		{
166			&participant.source
167		} else {
168			&destination
169		};
170		let repository = Repository::local(self, source, control).await?;
171		if repository.identity != participant.backing_identity {
172			return Err(blocked("Restored worktree backing identity changed."));
173		}
174		Ok(workyard_core::RecoveryObservation {
175			repository: repository.into(),
176			destination: Some(destination),
177			operation_in_progress: facts.operation_in_progress || facts.conflicted,
178		})
179	}
180}
181
182impl Runner {
183	/// Removal and copy activation serialize on the backing repository. Git resolves
184	/// its worktree argument at execution, so verify its backlink while holding the gate.
185	async fn verify_removal_location(
186		&self,
187		observation: &RemovalObservation,
188		destination: &std::path::Path,
189		control: &Control,
190	) -> Result<std::path::PathBuf, Problem> {
191		use crate::{
192			relationships::pointer::{absolute, read_path},
193			worktree_path::same_path,
194		};
195		let actual = destination
196			.canonicalize()
197			.map_err(|e| Problem::io("Resolve worktree before removal", e))?;
198		if !same_path(&actual, destination)
199			|| workyard_system::entry_identity(destination)? != observation.worktree_entry
200		{
201			return Err(blocked(
202				"The physical worktree at the removal destination changed. Inspect it and retry.",
203			));
204		}
205		let output = self
206			.checked(
207				destination,
208				&args(&["rev-parse", "--path-format=absolute", "--git-dir"]),
209				control,
210			)
211			.await?;
212		let admin =
213			crate::output::path_line(&output).map_err(|_| blocked("Invalid worktree path."))?;
214		let backlink = absolute(&admin, &read_path(&admin.join("gitdir"))?);
215		if !same_path(&backlink, &destination.join(".git"))
216			|| workyard_system::directory_identity(&admin)? != observation.administration_identity
217			|| workyard_system::directory_identity(&observation.repository.common_dir)?
218				!= observation.repository.identity
219		{
220			return Err(blocked(
221				"Git registration changed before removal. Inspect workyard status and retry.",
222			));
223		}
224		Ok(admin)
225	}
226
227	async fn retained_history(
228		&self,
229		destination: &std::path::Path,
230		branch: &str,
231		control: &Control,
232	) -> Result<RetainedHistory, Problem> {
233		let upstream = self
234			.checked(
235				destination,
236				&args(&[
237					"for-each-ref",
238					"--format=%(upstream)",
239					&format!("refs/heads/{branch}"),
240				]),
241				control,
242			)
243			.await?;
244		if upstream.iter().all(u8::is_ascii_whitespace) {
245			return Ok(RetainedHistory::NoUpstream);
246		}
247		let ahead = self
248			.checked(
249				destination,
250				&args(&["rev-list", "--count", "@{upstream}..HEAD"]),
251				control,
252			)
253			.await?;
254		if ahead == b"0\n" {
255			Ok(RetainedHistory::UpToDate)
256		} else {
257			Ok(RetainedHistory::Unpushed)
258		}
259	}
260}
261
262fn blocked(message: impl Into<String>) -> Problem {
263	Problem::new(ProblemCode::RepositoryChanged, message)
264		.remedy("Inspect git status and git worktree list; preserve files and repair Git relationships before retrying. Force cannot bypass this check.")
265}