use std::fs::{self, File};
use std::io::{self, Read as _, Write as _};
use std::path::{Component, Path, PathBuf};
#[cfg(test)]
mod tests;
pub(crate) fn read_capped(path: &Path, limit: usize) -> io::Result<Vec<u8>> {
let limit = u64::try_from(limit).unwrap_or(u64::MAX);
let mut bytes = Vec::new();
File::open(path)?.take(limit).read_to_end(&mut bytes)?;
Ok(bytes)
}
pub(crate) fn rust_files(dir: &Path) -> io::Result<Vec<PathBuf>> {
let mut found = Vec::new();
let mut dirs = vec![dir.to_path_buf()];
while let Some(dir) = dirs.pop() {
for entry in fs::read_dir(&dir)? {
let entry = entry?;
let kind = entry.file_type()?;
let path = entry.path();
if kind.is_dir() {
dirs.push(path);
} else if kind.is_file() && path.extension().is_some_and(|ext| ext == "rs") {
found.push(path);
}
}
}
found.sort();
Ok(found)
}
pub(crate) fn write_new(path: &Path, text: &str) -> io::Result<()> {
let mut file = File::options().write(true).create_new(true).open(path)?;
let written = file
.write_all(text.as_bytes())
.and_then(|()| file.sync_all());
drop(file);
written.inspect_err(|_| {
let _ = fs::remove_file(path);
})
}
pub(crate) fn replace(path: &Path, text: &str) -> io::Result<()> {
let path = fs::canonicalize(path)?;
let mode = fs::metadata(&path)?.permissions();
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(".starmap-new");
let new = path.with_file_name(name);
let _ = fs::remove_file(&new);
write_new(&new, text)
.and_then(|()| fs::set_permissions(&new, mode))
.and_then(|()| fs::rename(&new, &path))
.inspect_err(|_| {
let _ = fs::remove_file(&new);
})
}
pub(crate) fn exists(path: &Path) -> bool {
path.exists()
}
pub(crate) fn is_file(path: &Path) -> bool {
match fs::metadata(path) {
Ok(found) => !found.is_dir(),
Err(_) => fs::symlink_metadata(path).is_ok(),
}
}
pub(crate) fn canonical(path: &Path) -> io::Result<PathBuf> {
fs::canonicalize(path)
}
pub(crate) fn lexical(path: &Path) -> io::Result<PathBuf> {
let absolute = std::path::absolute(path)?;
let mut lexical = PathBuf::new();
for component in absolute.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
lexical.pop();
}
component => lexical.push(component),
}
}
Ok(lexical)
}