workyard_state/workspace/
projects.rs1use super::Layout;
3use crate::{Lock, Reader, Store, documents};
4use std::{
5 collections::BTreeSet,
6 path::{Component, Path, PathBuf},
7};
8use workyard_core::{Control, Problem, ProblemCode};
9
10#[derive(Clone, Copy)]
12pub enum RootEdit {
13 Track,
15 Untrack,
17}
18
19impl Reader {
20 pub fn tracked_only(&self) -> Result<bool, Problem> {
22 Ok(Layout::read(self.state())?.tracked_only)
23 }
24
25 pub fn project_registration_path(&self, path: &Path) -> Result<PathBuf, Problem> {
27 let workspace = self.state().parent().expect("workspace marker");
28 Ok(workspace.join(registration(workspace, path)?))
29 }
30
31 pub fn project_roots(&self) -> Result<Vec<PathBuf>, Problem> {
33 let workspace = self.state().parent().expect("workspace marker");
34 Ok(Layout::read(self.state())?
35 .located_roots(workspace)?
36 .into_iter()
37 .map(|root| workspace.join(root))
38 .collect())
39 }
40}
41
42impl Store {
43 pub async fn remember_workspace(&self, control: &Control) -> Result<bool, Problem> {
45 let state = self.state_dir();
46 let workspace = state.parent().expect("workspace marker");
47 control.check()?;
48 if Layout::read(state)?.is_at(workspace)? {
49 return Ok(false);
50 }
51 let lock = Lock::wait(&state.join("locks/projects.lock"), control).await?;
52 self.verify()?;
53 let mut layout = Layout::read(state)?;
54 if !layout.update_workspace(workspace)? {
55 return Ok(false);
56 }
57 lock.verify()?;
58 control.check()?;
59 documents::publish(&state.join("workspace.json"), &layout)?;
60 Ok(true)
61 }
62
63 pub async fn edit_project_roots(
65 &self,
66 edit: RootEdit,
67 paths: &[PathBuf],
68 control: &Control,
69 ) -> Result<Vec<PathBuf>, Problem> {
70 if paths.is_empty() {
71 return Ok(Vec::new());
72 }
73 let workspace = self.state_dir().parent().expect("workspace marker");
74 let lock = Lock::wait(&self.state_dir().join("locks/projects.lock"), control).await?;
75 self.verify()?;
76 let mut layout = Layout::read(self.state_dir())?;
77 let roots = paths
78 .iter()
79 .map(|path| edit.registration(workspace, path))
80 .collect::<Result<BTreeSet<_>, _>>()?;
81 layout.update_workspace(workspace)?;
83 let mut registered = layout.project_roots()?;
84 let mut changed = Vec::new();
85
86 for root in roots {
87 let matches: Vec<_> = registered
88 .iter()
89 .filter(|stored| {
90 **stored == root
91 || (stored.components().any(|part| part == Component::ParentDir)
92 && registration(workspace, &workspace.join(stored))
93 .is_ok_and(|path| path == root))
94 })
95 .cloned()
96 .collect();
97 match edit {
98 RootEdit::Track if matches.is_empty() => {
99 registered.insert(root.clone());
100 }
101 RootEdit::Untrack if !matches.is_empty() => {
102 for stored in matches {
103 registered.remove(&stored);
104 }
105 }
106 _ => continue,
107 }
108 changed.push(workspace.join(root));
109 }
110 if !changed.is_empty() {
111 control.check()?;
112 lock.verify()?;
113 layout.set_project_roots(®istered);
114 documents::publish(&self.state_dir().join("workspace.json"), &layout)?;
115 }
116 Ok(changed)
117 }
118}
119
120pub(super) fn initial_roots(
121 workspace: &Path,
122 paths: &[&Path],
123) -> Result<Option<BTreeSet<PathBuf>>, Problem> {
124 if paths.is_empty() {
125 return Ok(None);
126 }
127
128 let roots = paths
129 .iter()
130 .map(|&path| {
131 if path.is_absolute() {
132 return RootEdit::Track.registration(workspace, path);
133 }
134 if path.as_os_str().is_empty()
135 || path
136 .components()
137 .any(|part| matches!(part, Component::RootDir | Component::Prefix(_)))
138 {
139 return Err(Problem::new(
140 ProblemCode::InvalidInput,
141 "Supply a relative or absolute project path.",
142 ));
143 }
144
145 let resolved = crate::canonical_future(&workspace.join(path))?;
146 validate_track_path(&resolved)?;
147 Ok(path.to_owned())
148 })
149 .collect::<Result<BTreeSet<_>, _>>()?;
150 Ok(Some(roots))
151}
152
153impl RootEdit {
154 fn registration(self, workspace: &Path, path: &Path) -> Result<PathBuf, Problem> {
155 if matches!(self, Self::Track) {
156 validate_track_path(path)?;
157 }
158 registration(workspace, path)
159 }
160}
161
162fn validate_track_path(path: &Path) -> Result<(), Problem> {
163 match std::fs::metadata(path) {
164 Ok(meta) if !meta.is_dir() => Err(Problem::new(
165 ProblemCode::InvalidInput,
166 format!("Project root {path:?} must be a directory."),
167 )),
168 Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
169 Err(Problem::io(format!("Inspect project root {path:?}"), error))
170 }
171 _ => Ok(()),
172 }
173}
174
175fn registration(workspace: &Path, path: &Path) -> Result<PathBuf, Problem> {
178 if path.as_os_str().is_empty() {
179 return Err(Problem::new(
180 workyard_core::ProblemCode::InvalidInput,
181 "Project root cannot be empty.",
182 ));
183 }
184 let absolute =
185 std::path::absolute(path).map_err(|error| Problem::io("Resolve project root", error))?;
186 let inside = absolute.starts_with(workspace)
188 && !absolute
189 .components()
190 .any(|part| part == std::path::Component::ParentDir);
191 let absolute = match (absolute.parent(), absolute.file_name()) {
192 _ if inside => absolute,
193 (Some(parent), Some(name)) => crate::canonical_future(parent)?.join(name),
194 _ => crate::canonical_future(&absolute)?,
195 };
196 let relative = absolute.strip_prefix(workspace).unwrap_or(&absolute);
197 Ok(if relative.as_os_str().is_empty() {
198 PathBuf::from(".")
199 } else {
200 relative.to_owned()
201 })
202}