Damson/src/trash.rs
astar76 11c1a7808b Build the syntax definitions into the app
Highlighting relied on the syntax-highlighting package, so removing it
left every file uncoloured. The 462 definitions now live in assets/syntax
and are compressed into the binary at build time, unpacked per language
when used. User .xml files still add to or replace them, and the licence
each file declares is recorded in assets/syntax/LICENSES.md.

Also moves files to the trash without needing gio.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 20:35:27 -06:00

96 lines
4 KiB
Rust

//! The desktop trash, following the freedesktop.org spec, so files can be put back from any file
//! manager.
use std::io::{Error, ErrorKind, Result, Write};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
fn trash_dir() -> Result<PathBuf> {
dirs::data_dir().map(|d| d.join("Trash")).ok_or_else(|| Error::other("no home folder"))
}
/// `YYYY-MM-DDThh:mm:ss` in UTC from days since 1970, as the spec's DeletionDate needs a timestamp.
fn timestamp(secs: u64) -> String {
let (days, rest) = ((secs / 86_400) as i64, secs % 86_400);
// civil-from-days, Howard Hinnant's algorithm
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let (d, m) = (doy - (153 * mp + 2) / 5 + 1, if mp < 10 { mp + 3 } else { mp - 9 });
let y = yoe + era * 400 + (m <= 2) as i64;
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}", rest / 3600, rest % 3600 / 60, rest % 60)
}
fn encode(p: &Path) -> String {
let mut s = String::new();
for b in p.to_string_lossy().bytes() {
if b.is_ascii_alphanumeric() || b"/-_.~".contains(&b) { s.push(b as char) } else { s.push_str(&format!("%{b:02X}")) }
}
s
}
pub fn move_to_trash(p: &Path) -> Result<()> {
move_into(p, &trash_dir()?)
}
fn move_into(p: &Path, trash: &Path) -> Result<()> {
let p = std::fs::canonicalize(p)?;
let (files, info) = (trash.join("files"), trash.join("info"));
std::fs::create_dir_all(&files)?;
std::fs::create_dir_all(&info)?;
let name = p.file_name().ok_or_else(|| Error::other("no file name"))?.to_string_lossy().into_owned();
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs());
let text = format!("[Trash Info]\nPath={}\nDeletionDate={}\n", encode(&p), timestamp(secs));
// creating the .trashinfo first claims the name, so two trashings can't collide
for i in 1..10_000 {
let stem = if i == 1 { name.clone() } else { format!("{name}.{i}") };
let entry = info.join(format!("{stem}.trashinfo"));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&entry) {
Ok(mut f) => {
f.write_all(text.as_bytes())?;
return std::fs::rename(&p, files.join(&stem)).map_err(|e| {
let _ = std::fs::remove_file(&entry);
if e.kind() == ErrorKind::CrossesDevices { Error::other("it's on a different drive from your trash") } else { e }
});
}
Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Err(Error::other("too many files with that name in the trash"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dates_are_right() {
assert_eq!(timestamp(0), "1970-01-01T00:00:00");
assert_eq!(timestamp(1_709_210_096), "2024-02-29T12:34:56");
}
#[test]
fn same_name_twice_stays_separate_and_records_where_it_was() {
let dir = std::env::temp_dir().join(format!("damson-trash-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let trash = dir.join("Trash");
std::fs::create_dir_all(dir.join("a b")).unwrap();
for n in ["one", "two"] {
let f = dir.join("a b/note.txt");
std::fs::write(&f, n).unwrap();
move_into(&f, &trash).unwrap();
assert!(!f.exists());
}
assert_eq!(std::fs::read_to_string(trash.join("files/note.txt")).unwrap(), "one");
assert_eq!(std::fs::read_to_string(trash.join("files/note.txt.2")).unwrap(), "two");
let info = std::fs::read_to_string(trash.join("info/note.txt.trashinfo")).unwrap();
assert!(info.starts_with("[Trash Info]\nPath=/"), "{info}");
assert!(info.contains("a%20b/note.txt"), "{info}");
assert!(info.contains("DeletionDate=2"), "{info}");
std::fs::remove_dir_all(dir).unwrap();
}
}