Skip to main content

workyard_state/workspace/
projects.rs

1//! Each edit merges into the latest manifest under its own short-lived lock.
2use super::Layout;
3use crate::{Lock, Reader, Store, documents};
4use std::{
5	collections::BTreeSet,
6	path::{Path, PathBuf},
7};
8use workyard_core::{Control, Problem, ProblemCode};
9
10/// Requested change to the project's discovery roots.
11#[derive(Clone, Copy)]
12pub enum RootEdit {
13	/// Add the supplied roots to the project catalog configuration.
14	Track,
15	/// Remove the supplied roots from the project catalog configuration.
16	Untrack,
17}
18
19impl Reader {
20	/// Absolute selection to retain for a deferred project registration.
21	pub fn project_registration_path(&self, path: &Path) -> Result<PathBuf, Problem> {
22		let workspace = self.state().parent().expect("workspace marker");
23		Ok(workspace.join(registration(workspace, path)?))
24	}
25
26	/// Read the workspace's configured discovery roots.
27	pub fn project_roots(&self) -> Result<Vec<PathBuf>, Problem> {
28		let workspace = self.state().parent().expect("workspace marker");
29		Ok(Layout::read(self.state())?
30			.located_roots(workspace)?
31			.into_iter()
32			.map(|root| workspace.join(root))
33			.collect())
34	}
35}
36
37impl Store {
38	/// Record the verified location of the active workspace.
39	pub async fn remember_workspace(&self, control: &Control) -> Result<bool, Problem> {
40		let state = self.state_dir();
41		let workspace = state.parent().expect("workspace marker");
42		control.check()?;
43		if Layout::read(state)?.is_at(workspace)? {
44			return Ok(false);
45		}
46		let lock = Lock::wait(&state.join("locks/projects.lock"), control).await?;
47		self.verify()?;
48		let mut layout = Layout::read(state)?;
49		if !layout.update_workspace(workspace)? {
50			return Ok(false);
51		}
52		lock.verify()?;
53		control.check()?;
54		documents::publish(&state.join("workspace.json"), &layout)?;
55		Ok(true)
56	}
57
58	/// Apply the requested root changes to workspace configuration.
59	pub async fn edit_project_roots(
60		&self,
61		edit: RootEdit,
62		paths: &[PathBuf],
63		control: &Control,
64	) -> Result<Vec<PathBuf>, Problem> {
65		if paths.is_empty() {
66			return Ok(Vec::new());
67		}
68		let workspace = self.state_dir().parent().expect("workspace marker");
69		let lock = Lock::wait(&self.state_dir().join("locks/projects.lock"), control).await?;
70		self.verify()?;
71		let mut layout = Layout::read(self.state_dir())?;
72		let roots = paths
73			.iter()
74			.map(|path| edit.registration(workspace, path))
75			.collect::<Result<BTreeSet<_>, _>>()?;
76		// Evaluate edits against the same roots a project listing would show here.
77		layout.update_workspace(workspace)?;
78		let mut registered = layout.project_roots()?;
79		let mut changed = Vec::new();
80
81		for root in roots {
82			let updated = match edit {
83				RootEdit::Track => registered.insert(root.clone()),
84				RootEdit::Untrack => registered.remove(&root),
85			};
86			if updated {
87				changed.push(workspace.join(root));
88			}
89		}
90		if !changed.is_empty() {
91			control.check()?;
92			lock.verify()?;
93			layout.set_project_roots(&registered);
94			documents::publish(&self.state_dir().join("workspace.json"), &layout)?;
95		}
96		Ok(changed)
97	}
98}
99
100impl RootEdit {
101	fn registration(self, workspace: &Path, path: &Path) -> Result<PathBuf, Problem> {
102		if matches!(self, Self::Track) {
103			match std::fs::metadata(path) {
104				Ok(meta) if !meta.is_dir() => {
105					return Err(Problem::new(
106						ProblemCode::InvalidInput,
107						format!("Project root {path:?} must be a directory."),
108					));
109				}
110				Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
111					return Err(Problem::io(format!("Inspect project root {path:?}"), error));
112				}
113				_ => {}
114			}
115		}
116		registration(workspace, path)
117	}
118}
119
120// Preserve the registered path as a discovery source, including a directory symlink.
121// Resolve parent traversals with filesystem semantics before storing a portable spelling.
122fn registration(workspace: &Path, path: &Path) -> Result<PathBuf, Problem> {
123	if path.as_os_str().is_empty() {
124		return Err(Problem::new(
125			workyard_core::ProblemCode::InvalidInput,
126			"Project root cannot be empty.",
127		));
128	}
129	let absolute =
130		std::path::absolute(path).map_err(|error| Problem::io("Resolve project root", error))?;
131	// Canonical parents also put Windows drive paths in the workspace marker's native form.
132	let inside = absolute.starts_with(workspace)
133		&& !absolute
134			.components()
135			.any(|part| part == std::path::Component::ParentDir);
136	let absolute = match (absolute.parent(), absolute.file_name()) {
137		_ if inside => absolute,
138		(Some(parent), Some(name)) => crate::canonical_future(parent)?.join(name),
139		_ => crate::canonical_future(&absolute)?,
140	};
141	let relative = absolute.strip_prefix(workspace).unwrap_or(&absolute);
142	Ok(if relative.as_os_str().is_empty() {
143		PathBuf::from(".")
144	} else {
145		relative.to_owned()
146	})
147}