Skip to main content

nibkeep_node/
pointer.rs

1//! The `.nib` file in the folder of a tree outside its library's folder, which names the
2//! library, as a worktree's `.git` file names its repository, so that commands run there find
3//! it; and none in the folder of a tree inside it, where the commands find the library
4//! without one, and a file left there would take them over. `nib` and the apps that start
5//! trees settle it alike ([technical design: trees]).
6//!
7//! [technical design: trees]: ../../../docs/Technical-design.md#15-trees
8
9use 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
17/// The folder in a library's folder that holds the library, and the file in a tree's folder
18/// that names it.
19pub const LIBRARY_DATA: &str = ".nib";
20
21/// What the file's one line says before the library's folder.
22const NAMES: &str = "library: ";
23
24/// The most of a `.nib` file that is read, far more than any path.
25const MOST: u64 = 64 * 1024;
26
27/// What is wrong with a `.nib` file, or with writing one.
28#[derive(Debug, thiserror::Error)]
29pub enum PointerError {
30	/// A `.nib` file in a folder that names no library that may be opened.
31	#[error("{} should name the library of the tree in its folder, but {why}", .file.display())]
32	Bad {
33		/// The file.
34		file: PathBuf,
35		/// What is wrong with it.
36		why: String,
37	},
38	/// A `.nib` file that names a library which keeps no tree in that folder on this device,
39	/// as a copy of a tree's folder would.
40	#[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		/// The file.
47		file: PathBuf,
48		/// The library's folder.
49		library: PathBuf,
50	},
51	/// Something other than a file where the `.nib` file of a tree outside the library's
52	/// folder goes.
53	#[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	/// The `.nib` file of a tree outside the library's folder could not be written.
59	#[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		/// The file.
66		file: PathBuf,
67		/// Why not.
68		error: io::Error,
69	},
70	/// The `.nib` file of a tree inside the library's folder, which would take over the
71	/// commands there, could not be deleted.
72	#[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		/// The file.
79		file: PathBuf,
80		/// Why not.
81		error: io::Error,
82	},
83	/// The library could not be read.
84	#[error(transparent)]
85	Library(#[from] NodeError),
86}
87
88/// A library that a command found, and the `.nib` file that named it, if one did.
89#[derive(Debug)]
90pub struct Found {
91	/// The library's folder, as the file system resolves it.
92	pub folder: PathBuf,
93	/// The `.nib` file in a tree's folder that named the library, if one did.
94	pub named_in: Option<PathBuf>,
95}
96
97impl Found {
98	/// A library found in its own folder, or given.
99	#[must_use]
100	pub const fn library(folder: PathBuf) -> Self {
101		Self {
102			folder,
103			named_in: None,
104		}
105	}
106}
107
108/// A folder as the file system resolves it, so that one folder is named one way: the
109/// nearest part of it that exists, resolved, then the rest, which nothing can link
110/// elsewhere yet.
111#[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/// Whether a folder's `.nib` holds a library, what is left of starting one, or copies of
140/// replicas made elsewhere.
141#[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/// The folder that a `.nib` file is in, for messages.
148#[must_use]
149pub fn folder_of(file: &Path) -> Display<'_> {
150	file.parent().unwrap_or(file).display()
151}
152
153/// The nearest library of `here` and the folders it is in, below `ceiling`: the folder whose
154/// `.nib` holds it, or the one that a `.nib` file names.
155///
156/// # Errors
157///
158/// Returns [`PointerError::Bad`] if the nearest `.nib` is a file that names no library that
159/// may be opened; nothing looks further, as the person meant that library.
160pub 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
183/// The folder of the library that the `.nib` file `file` names, as the file system resolves
184/// it.
185fn 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	// A mark of UTF-8 that some editors write first.
195	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	// A build under development never leaves its ceiling, as it never looks above it.
210	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
231/// The tree whose folder on this device is `folder` itself, in any space of the library,
232/// with its space.
233///
234/// # Errors
235///
236/// Returns an error if a space cannot be read.
237pub 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
251/// Refuses a library that a `.nib` file named, unless the library keeps a tree in that very
252/// folder on this device: a `.nib` file from elsewhere, such as in an archive, must not point
253/// commands at the person's library. A file in `starting`, the folder that `nib init` makes
254/// a tree, counts all the same, as init writes it anew.
255///
256/// # Errors
257///
258/// Returns [`PointerError::Stray`] if it keeps none there, and an error if a space cannot be
259/// read.
260pub 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/// Whether commands run in the tree's folder `root` need a `.nib` file there to find the
281/// library in `library`: unless the nearest library of the folder and those it is in, below
282/// `ceiling`, is that one, in its own folder. Another tree's `.nib` file above it would name
283/// another library, or none.
284#[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/// Whether the tree's folder `root` holds a `.nib` file that names the library in `library`.
304#[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
309/// Refuses where something other than a file is in the place of the tree's `.nib` file,
310/// which writing must neither follow nor replace.
311///
312/// # Errors
313///
314/// Returns [`PointerError::InTheWay`] if something else is there.
315pub 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
323/// Writes into the tree's folder `root` the `.nib` file that names the library in `library`,
324/// over one that is there, and saves it, and the folder where the system allows.
325///
326/// # Errors
327///
328/// Returns [`PointerError::InTheWay`] if something other than a file is in its place, and
329/// [`PointerError::NotWritten`] if writing fails.
330pub 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	// Windows opens no folder as a file, and saves its entries with the file.
344	let _ = fs::File::open(root).and_then(|folder| folder.sync_all());
345	Ok(file)
346}
347
348/// What [`settle`] did in a tree's folder.
349#[derive(Debug, PartialEq, Eq)]
350pub enum Settled {
351	/// It wrote the file that names the library, over one that was there.
352	Written(PathBuf),
353	/// It took away a file that the commands there do not need, and that would take them over.
354	TakenAway(PathBuf),
355	/// Nothing: no file is needed, and none was there.
356	Nothing,
357}
358
359/// Settles the `.nib` file in the tree's folder `root`, as commands there need it to find the
360/// library in `library`: writes the file that names it where they would not find it
361/// otherwise, as [`needed`] says, and else takes away what they would read as one, such as a
362/// file copied with the folder, which would take them over; of a link to a file, the link
363/// goes, not what it links to. A folder in its place stays, such as the library's own where
364/// the tree's folder is the library's.
365///
366/// # Errors
367///
368/// Returns [`PointerError::InTheWay`] if a file is needed and something else is in its place,
369/// and [`PointerError::NotWritten`] or [`PointerError::NotTakenAway`] if the file system
370/// fails.
371pub 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	// What `nearest` reads, links followed; deleting a link deletes the link alone.
380	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}