use std::fs;
use std::io::{self, Read, Write};
use std::path::{Component, Display, Path, PathBuf};
use nibkeep_base::SpaceId;
use crate::{Library, NodeError, Tree, resolved_path};
pub const LIBRARY_DATA: &str = ".nib";
const NAMES: &str = "library: ";
const MOST: u64 = 64 * 1024;
#[derive(Debug, thiserror::Error)]
pub enum PointerError {
#[error("{} should name the library of the tree in its folder, but {why}", .file.display())]
Bad {
file: PathBuf,
why: String,
},
#[error(
"{} names the library in {}, which keeps no tree in that folder on this device",
.file.display(),
.library.display()
)]
Stray {
file: PathBuf,
library: PathBuf,
},
#[error(
"{} is no file: the file there names the library of a tree outside the library's folder",
.0.display()
)]
InTheWay(PathBuf),
#[error(
"{} could not be written: {error}; the tree is there, and nib init {} in the library's folder writes the file again",
.file.display(),
folder_of(.file)
)]
NotWritten {
file: PathBuf,
error: io::Error,
},
#[error(
"{} could not be deleted: {error}; the tree is there, and once the file is gone, commands in {} find the library",
.file.display(),
folder_of(.file)
)]
NotTakenAway {
file: PathBuf,
error: io::Error,
},
#[error(transparent)]
Library(#[from] NodeError),
}
#[derive(Debug)]
pub struct Found {
pub folder: PathBuf,
pub named_in: Option<PathBuf>,
}
impl Found {
#[must_use]
pub const fn library(folder: PathBuf) -> Self {
Self {
folder,
named_in: None,
}
}
}
#[must_use]
pub fn resolved_as_far_as_it_exists(folder: PathBuf) -> PathBuf {
let mut rest = Vec::new();
let mut existing = folder.as_path();
loop {
if let Ok(mut resolved) = resolved_path(existing) {
for part in rest.into_iter().rev() {
match part {
Component::ParentDir => {
resolved.pop();
}
Component::CurDir => {}
part => resolved.push(part),
}
}
return resolved;
}
let mut parts = existing.components();
match parts.next_back() {
Some(last) if !parts.as_path().as_os_str().is_empty() => {
rest.push(last);
existing = parts.as_path();
}
_ => return folder,
}
}
}
#[must_use]
pub fn holds_library(folder: &Path) -> bool {
let data = folder.join(LIBRARY_DATA);
data.is_dir() && Library::exists(&data)
}
#[must_use]
pub fn folder_of(file: &Path) -> Display<'_> {
file.parent().unwrap_or(file).display()
}
pub fn nearest(here: &Path, ceiling: Option<&Path>) -> Result<Option<Found>, PointerError> {
for folder in here
.ancestors()
.take_while(|folder| ceiling != Some(*folder))
{
let data = folder.join(LIBRARY_DATA);
if data.is_dir() {
if Library::exists(&data) {
return Ok(Some(Found::library(resolved_as_far_as_it_exists(
folder.to_owned(),
))));
}
} else if data.is_file() {
let named = named(&data, ceiling)?;
return Ok(Some(Found {
folder: named,
named_in: Some(data),
}));
}
}
Ok(None)
}
fn named(file: &Path, ceiling: Option<&Path>) -> Result<PathBuf, PointerError> {
let bad = |why: String| PointerError::Bad {
file: file.to_owned(),
why,
};
let mut text = String::new();
fs::File::open(file)
.and_then(|opened| opened.take(MOST).read_to_string(&mut text))
.map_err(|error| bad(format!("it cannot be read: {error}")))?;
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
let line = text
.strip_suffix('\n')
.map_or(text, |line| line.strip_suffix('\r').unwrap_or(line));
let Some(named) = line
.strip_prefix(NAMES)
.filter(|named| !named.contains(['\n', '\r']))
else {
return Err(bad(format!("it is not one line, {NAMES}FOLDER")));
};
let named = PathBuf::from(named);
if !named.is_absolute() {
return Err(bad(format!("{} is not a full path", named.display())));
}
if let Some(ceiling) = ceiling {
let ceiling = resolved_as_far_as_it_exists(ceiling.to_owned());
let below = resolved_as_far_as_it_exists(named.clone());
if below == ceiling || !below.starts_with(&ceiling) {
return Err(bad(format!(
"{} is not below {}, which NIBKEEP_CEILING names",
named.display(),
ceiling.display()
)));
}
}
if !holds_library(&named) {
return Err(bad(format!(
"{} holds no library; run nib init {} in the library's folder, its new one if it moved",
named.display(),
folder_of(file)
)));
}
Ok(resolved_as_far_as_it_exists(named))
}
pub fn tree_rooted_at(
library: &Library,
folder: &Path,
) -> Result<Option<(SpaceId, Tree)>, NodeError> {
for space in library.spaces() {
if let Some(tree) = library.tree_at(space, folder)?
&& tree.root.as_deref() == Some(folder)
{
return Ok(Some((space, tree)));
}
}
Ok(None)
}
pub fn check(
library: &Library,
found: &Found,
starting: Option<&Path>,
) -> Result<(), PointerError> {
let Some(file) = &found.named_in else {
return Ok(());
};
let folder = resolved_as_far_as_it_exists(file.parent().unwrap_or(file).to_owned());
let started_here = starting
.is_some_and(|starting| resolved_as_far_as_it_exists(starting.to_owned()) == folder);
if started_here || tree_rooted_at(library, &folder)?.is_some() {
return Ok(());
}
Err(PointerError::Stray {
file: file.clone(),
library: found.folder.clone(),
})
}
#[must_use]
pub fn needed(root: &Path, library: &Path, ceiling: Option<&Path>) -> bool {
let ceiling = ceiling.map(|ceiling| resolved_as_far_as_it_exists(ceiling.to_owned()));
for folder in root
.ancestors()
.take_while(|folder| ceiling.as_deref() != Some(*folder))
{
let data = folder.join(LIBRARY_DATA);
if data.is_dir() {
if Library::exists(&data) {
return resolved_as_far_as_it_exists(folder.to_owned()) != library;
}
} else if folder != root && data.is_file() {
return true;
}
}
true
}
#[must_use]
pub fn names(root: &Path, library: &Path) -> bool {
named(&root.join(LIBRARY_DATA), None).is_ok_and(|named| named == library)
}
pub fn check_place(root: &Path) -> Result<(), PointerError> {
let file = root.join(LIBRARY_DATA);
match fs::symlink_metadata(&file) {
Ok(metadata) if !metadata.is_file() => Err(PointerError::InTheWay(file)),
_ => Ok(()),
}
}
pub fn write(root: &Path, library: &Path) -> Result<PathBuf, PointerError> {
check_place(root)?;
let file = root.join(LIBRARY_DATA);
let text = format!("{NAMES}{}\n", library.display());
fs::File::create(&file)
.and_then(|mut opened| {
opened.write_all(text.as_bytes())?;
opened.sync_all()
})
.map_err(|error| PointerError::NotWritten {
file: file.clone(),
error,
})?;
let _ = fs::File::open(root).and_then(|folder| folder.sync_all());
Ok(file)
}
#[derive(Debug, PartialEq, Eq)]
pub enum Settled {
Written(PathBuf),
TakenAway(PathBuf),
Nothing,
}
pub fn settle(
root: &Path,
library: &Path,
ceiling: Option<&Path>,
) -> Result<Settled, PointerError> {
if needed(root, library, ceiling) {
return write(root, library).map(Settled::Written);
}
let file = root.join(LIBRARY_DATA);
if !file.is_file() {
return Ok(Settled::Nothing);
}
match fs::remove_file(&file) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Settled::Nothing),
Err(error) => return Err(PointerError::NotTakenAway { file, error }),
}
let _ = fs::File::open(root).and_then(|folder| folder.sync_all());
Ok(Settled::TakenAway(file))
}