1use std::fs;
10use std::io::{self, Read, Write};
11use std::path::{Component, Display, Path, PathBuf};
12
13use nibkeep_base::SpaceId;
14
15use crate::{Library, NodeError, Tree, resolved_path};
16
17pub const LIBRARY_DATA: &str = ".nib";
20
21const NAMES: &str = "library: ";
23
24const MOST: u64 = 64 * 1024;
26
27#[derive(Debug, thiserror::Error)]
29pub enum PointerError {
30 #[error("{} should name the library of the tree in its folder, but {why}", .file.display())]
32 Bad {
33 file: PathBuf,
35 why: String,
37 },
38 #[error(
41 "{} names the library in {}, which keeps no tree in that folder on this device",
42 .file.display(),
43 .library.display()
44 )]
45 Stray {
46 file: PathBuf,
48 library: PathBuf,
50 },
51 #[error(
54 "{} is no file: the file there names the library of a tree outside the library's folder",
55 .0.display()
56 )]
57 InTheWay(PathBuf),
58 #[error(
60 "{} could not be written: {error}; the tree is there, and nib init {} in the library's folder writes the file again",
61 .file.display(),
62 folder_of(.file)
63 )]
64 NotWritten {
65 file: PathBuf,
67 error: io::Error,
69 },
70 #[error(
73 "{} could not be deleted: {error}; the tree is there, and once the file is gone, commands in {} find the library",
74 .file.display(),
75 folder_of(.file)
76 )]
77 NotTakenAway {
78 file: PathBuf,
80 error: io::Error,
82 },
83 #[error(transparent)]
85 Library(#[from] NodeError),
86}
87
88#[derive(Debug)]
90pub struct Found {
91 pub folder: PathBuf,
93 pub named_in: Option<PathBuf>,
95}
96
97impl Found {
98 #[must_use]
100 pub const fn library(folder: PathBuf) -> Self {
101 Self {
102 folder,
103 named_in: None,
104 }
105 }
106}
107
108#[must_use]
112pub fn resolved_as_far_as_it_exists(folder: PathBuf) -> PathBuf {
113 let mut rest = Vec::new();
114 let mut existing = folder.as_path();
115 loop {
116 if let Ok(mut resolved) = resolved_path(existing) {
117 for part in rest.into_iter().rev() {
118 match part {
119 Component::ParentDir => {
120 resolved.pop();
121 }
122 Component::CurDir => {}
123 part => resolved.push(part),
124 }
125 }
126 return resolved;
127 }
128 let mut parts = existing.components();
129 match parts.next_back() {
130 Some(last) if !parts.as_path().as_os_str().is_empty() => {
131 rest.push(last);
132 existing = parts.as_path();
133 }
134 _ => return folder,
135 }
136 }
137}
138
139#[must_use]
142pub fn holds_library(folder: &Path) -> bool {
143 let data = folder.join(LIBRARY_DATA);
144 data.is_dir() && Library::exists(&data)
145}
146
147#[must_use]
149pub fn folder_of(file: &Path) -> Display<'_> {
150 file.parent().unwrap_or(file).display()
151}
152
153pub fn nearest(here: &Path, ceiling: Option<&Path>) -> Result<Option<Found>, PointerError> {
161 for folder in here
162 .ancestors()
163 .take_while(|folder| ceiling != Some(*folder))
164 {
165 let data = folder.join(LIBRARY_DATA);
166 if data.is_dir() {
167 if Library::exists(&data) {
168 return Ok(Some(Found::library(resolved_as_far_as_it_exists(
169 folder.to_owned(),
170 ))));
171 }
172 } else if data.is_file() {
173 let named = named(&data, ceiling)?;
174 return Ok(Some(Found {
175 folder: named,
176 named_in: Some(data),
177 }));
178 }
179 }
180 Ok(None)
181}
182
183fn named(file: &Path, ceiling: Option<&Path>) -> Result<PathBuf, PointerError> {
186 let bad = |why: String| PointerError::Bad {
187 file: file.to_owned(),
188 why,
189 };
190 let mut text = String::new();
191 fs::File::open(file)
192 .and_then(|opened| opened.take(MOST).read_to_string(&mut text))
193 .map_err(|error| bad(format!("it cannot be read: {error}")))?;
194 let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
196 let line = text
197 .strip_suffix('\n')
198 .map_or(text, |line| line.strip_suffix('\r').unwrap_or(line));
199 let Some(named) = line
200 .strip_prefix(NAMES)
201 .filter(|named| !named.contains(['\n', '\r']))
202 else {
203 return Err(bad(format!("it is not one line, {NAMES}FOLDER")));
204 };
205 let named = PathBuf::from(named);
206 if !named.is_absolute() {
207 return Err(bad(format!("{} is not a full path", named.display())));
208 }
209 if let Some(ceiling) = ceiling {
211 let ceiling = resolved_as_far_as_it_exists(ceiling.to_owned());
212 let below = resolved_as_far_as_it_exists(named.clone());
213 if below == ceiling || !below.starts_with(&ceiling) {
214 return Err(bad(format!(
215 "{} is not below {}, which NIBKEEP_CEILING names",
216 named.display(),
217 ceiling.display()
218 )));
219 }
220 }
221 if !holds_library(&named) {
222 return Err(bad(format!(
223 "{} holds no library; run nib init {} in the library's folder, its new one if it moved",
224 named.display(),
225 folder_of(file)
226 )));
227 }
228 Ok(resolved_as_far_as_it_exists(named))
229}
230
231pub fn tree_rooted_at(
238 library: &Library,
239 folder: &Path,
240) -> Result<Option<(SpaceId, Tree)>, NodeError> {
241 for space in library.spaces() {
242 if let Some(tree) = library.tree_at(space, folder)?
243 && tree.root.as_deref() == Some(folder)
244 {
245 return Ok(Some((space, tree)));
246 }
247 }
248 Ok(None)
249}
250
251pub fn check(
261 library: &Library,
262 found: &Found,
263 starting: Option<&Path>,
264) -> Result<(), PointerError> {
265 let Some(file) = &found.named_in else {
266 return Ok(());
267 };
268 let folder = resolved_as_far_as_it_exists(file.parent().unwrap_or(file).to_owned());
269 let started_here = starting
270 .is_some_and(|starting| resolved_as_far_as_it_exists(starting.to_owned()) == folder);
271 if started_here || tree_rooted_at(library, &folder)?.is_some() {
272 return Ok(());
273 }
274 Err(PointerError::Stray {
275 file: file.clone(),
276 library: found.folder.clone(),
277 })
278}
279
280#[must_use]
285pub fn needed(root: &Path, library: &Path, ceiling: Option<&Path>) -> bool {
286 let ceiling = ceiling.map(|ceiling| resolved_as_far_as_it_exists(ceiling.to_owned()));
287 for folder in root
288 .ancestors()
289 .take_while(|folder| ceiling.as_deref() != Some(*folder))
290 {
291 let data = folder.join(LIBRARY_DATA);
292 if data.is_dir() {
293 if Library::exists(&data) {
294 return resolved_as_far_as_it_exists(folder.to_owned()) != library;
295 }
296 } else if folder != root && data.is_file() {
297 return true;
298 }
299 }
300 true
301}
302
303#[must_use]
305pub fn names(root: &Path, library: &Path) -> bool {
306 named(&root.join(LIBRARY_DATA), None).is_ok_and(|named| named == library)
307}
308
309pub fn check_place(root: &Path) -> Result<(), PointerError> {
316 let file = root.join(LIBRARY_DATA);
317 match fs::symlink_metadata(&file) {
318 Ok(metadata) if !metadata.is_file() => Err(PointerError::InTheWay(file)),
319 _ => Ok(()),
320 }
321}
322
323pub fn write(root: &Path, library: &Path) -> Result<PathBuf, PointerError> {
331 check_place(root)?;
332 let file = root.join(LIBRARY_DATA);
333 let text = format!("{NAMES}{}\n", library.display());
334 fs::File::create(&file)
335 .and_then(|mut opened| {
336 opened.write_all(text.as_bytes())?;
337 opened.sync_all()
338 })
339 .map_err(|error| PointerError::NotWritten {
340 file: file.clone(),
341 error,
342 })?;
343 let _ = fs::File::open(root).and_then(|folder| folder.sync_all());
345 Ok(file)
346}
347
348#[derive(Debug, PartialEq, Eq)]
350pub enum Settled {
351 Written(PathBuf),
353 TakenAway(PathBuf),
355 Nothing,
357}
358
359pub fn settle(
372 root: &Path,
373 library: &Path,
374 ceiling: Option<&Path>,
375) -> Result<Settled, PointerError> {
376 if needed(root, library, ceiling) {
377 return write(root, library).map(Settled::Written);
378 }
379 let file = root.join(LIBRARY_DATA);
381 if !file.is_file() {
382 return Ok(Settled::Nothing);
383 }
384 match fs::remove_file(&file) {
385 Ok(()) => {}
386 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Settled::Nothing),
387 Err(error) => return Err(PointerError::NotTakenAway { file, error }),
388 }
389 let _ = fs::File::open(root).and_then(|folder| folder.sync_all());
390 Ok(Settled::TakenAway(file))
391}