use std::fs;
use std::io;
use std::path::{Path, PathBuf};
pub fn write_cwd_file(cwd: &Path, cwd_file_path: &Path) -> io::Result<()> {
if cwd.to_str().is_none() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"cwd is not valid UTF-8",
));
}
fs::write(cwd_file_path, crate::pathfmt::display(cwd))
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn write_cwd_file_round_trips() {
let dir = tempfile::tempdir().expect("tempdir");
let out = dir.path().join("cwd.txt");
let cwd = PathBuf::from("/some/test/path");
write_cwd_file(&cwd, &out).expect("write_cwd_file");
let contents = std::fs::read_to_string(&out).expect("read");
assert_eq!(contents, "/some/test/path");
}
#[test]
fn write_cwd_file_creates_file() {
let dir = tempfile::tempdir().expect("tempdir");
let out = dir.path().join("new_file.txt");
assert!(!out.exists());
let cwd = PathBuf::from("/tmp");
write_cwd_file(&cwd, &out).expect("write");
assert!(out.exists());
}
#[test]
#[cfg(windows)]
fn write_cwd_file_strips_windows_verbatim_prefix() {
let dir = tempfile::tempdir().expect("tempdir");
let out = dir.path().join("cwd.txt");
let cwd = PathBuf::from(r"\\?\C:\Windows\System32");
write_cwd_file(&cwd, &out).expect("write_cwd_file");
let contents = std::fs::read_to_string(&out).expect("read");
assert_eq!(contents, r"C:\Windows\System32");
}
#[test]
#[cfg(windows)]
fn write_cwd_file_strips_windows_verbatim_unc_prefix() {
let dir = tempfile::tempdir().expect("tempdir");
let out = dir.path().join("cwd.txt");
let cwd = PathBuf::from(r"\\?\UNC\server\share");
write_cwd_file(&cwd, &out).expect("write_cwd_file");
let contents = std::fs::read_to_string(&out).expect("read");
assert_eq!(contents, r"\\server\share");
}
}
use serde::{Deserialize, Serialize};
const MAX_RECENT_DIRS: usize = 50;
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct RecentDirs {
pub paths: Vec<PathBuf>,
}
impl RecentDirs {
pub fn load(file_path: &Path) -> Self {
if let Ok(content) = fs::read_to_string(file_path) {
if let Ok(recent) = toml::from_str(&content) {
return recent;
}
}
Self::default()
}
pub fn save(&self, file_path: &Path) {
if let Ok(content) = toml::to_string_pretty(self) {
let _ = fs::write(file_path, content);
}
}
pub fn visit(&mut self, path: PathBuf) {
self.paths.retain(|p| p != &path);
self.paths.insert(0, path);
self.paths.truncate(MAX_RECENT_DIRS);
}
}