use std::path::{Path, PathBuf};
pub const PDB_PATH: &str = "PIONEER/rekordbox/export.pdb";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Volume {
pub path: PathBuf,
pub label: String,
pub rekordbox: bool,
}
#[must_use]
pub fn rekordbox_volumes() -> Vec<Volume> {
let mut found: Vec<Volume> = candidates()
.into_iter()
.filter(|path| path.join(PDB_PATH).is_file())
.map(|path| Volume {
label: label_of(&path),
path,
rekordbox: true,
})
.collect();
found.sort_by(|left, right| left.path.cmp(&right.path));
found.dedup_by(|left, right| left.path == right.path);
found
}
#[must_use]
pub fn local_volumes() -> Vec<Volume> {
let mut found = rekordbox_volumes();
for path in candidates() {
if found.iter().any(|volume| volume.path == path) || !is_mount_point(&path) {
continue;
}
found.push(Volume {
label: label_of(&path),
path,
rekordbox: false,
});
}
found.sort_by(|left, right| left.path.cmp(&right.path));
found
}
fn is_mount_point(path: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
let (Ok(own), Some(parent)) = (std::fs::symlink_metadata(path), path.parent()) else {
return false;
};
own.is_dir() && std::fs::metadata(parent).is_ok_and(|parent| parent.dev() != own.dev())
}
fn candidates() -> Vec<PathBuf> {
let mut roots = vec![PathBuf::from("/media"), PathBuf::from("/Volumes")];
if let Ok(user) = std::env::var("USER")
&& !user.is_empty()
{
roots.push(PathBuf::from("/media").join(&user));
roots.push(PathBuf::from("/run/media").join(&user));
}
let mut volumes = Vec::new();
for root in roots {
let Ok(listing) = std::fs::read_dir(&root) else {
continue;
};
for entry in listing.flatten() {
if entry.path().is_dir() {
volumes.push(entry.path());
}
}
}
volumes
}
pub fn label_of(mount_point: &Path) -> String {
let fallback = mount_point
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let Some(device) = device_at(mount_point) else {
return fallback;
};
let Ok(listing) = std::fs::read_dir("/dev/disk/by-label") else {
return fallback;
};
for entry in listing.flatten() {
if entry
.path()
.canonicalize()
.is_ok_and(|target| target == device)
{
return unescape(&entry.file_name().to_string_lossy());
}
}
fallback
}
pub fn size_of(mount_point: &Path) -> Option<(u64, u64)> {
let stats = rustix::fs::statvfs(mount_point).ok()?;
let block = stats.f_frsize;
Some((
stats.f_blocks.checked_mul(block)?,
stats.f_bavail.checked_mul(block)?,
))
}
fn device_at(mount_point: &Path) -> Option<PathBuf> {
let table = std::fs::read_to_string("/proc/self/mounts").ok()?;
for line in table.lines() {
let mut fields = line.split(' ');
let device = fields.next()?;
let Some(at) = fields.next() else { continue };
if Path::new(&unescape(at)) == mount_point {
return Path::new(device).canonicalize().ok();
}
}
None
}
fn unescape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let bytes = text.as_bytes();
let mut index = 0;
while index < bytes.len() {
if bytes.get(index) == Some(&b'\\')
&& let Some(digits) = text.get(index + 1..index + 4)
&& let Ok(value) = u8::from_str_radix(digits, 8)
{
out.push(char::from(value));
index += 4;
continue;
}
if let Some(rest) = text.get(index..)
&& let Some(character) = rest.chars().next()
{
out.push(character);
index += character.len_utf8();
} else {
break;
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn octal_escapes_are_decoded() {
assert_eq!(unescape("/media/MY\\040SET"), "/media/MY SET");
assert_eq!(unescape("plain"), "plain");
assert_eq!(unescape("a\\b"), "a\\b");
assert_eq!(unescape("trailing\\"), "trailing\\");
}
#[test]
fn a_directory_is_a_mount_point_only_on_a_device_of_its_own() {
assert!(!is_mount_point(Path::new("/")));
assert!(!is_mount_point(Path::new(env!("CARGO_MANIFEST_DIR"))));
assert!(!is_mount_point(Path::new("/nonexistent/volume")));
for volume in local_volumes() {
assert!(
volume.rekordbox || is_mount_point(&volume.path),
"{} is neither",
volume.path.display()
);
}
}
#[test]
fn a_volumes_size_is_its_filesystems() {
let (total, free) = size_of(Path::new("/")).expect("the root filesystem has a size");
assert!(total > 0);
assert!(free <= total, "{free} free of {total}");
assert_eq!(size_of(Path::new("/nonexistent/volume")), None);
}
#[test]
fn a_label_falls_back_to_the_mount_point_name() {
assert_eq!(label_of(Path::new("/nonexistent/NHK_2024")), "NHK_2024");
}
#[test]
fn scanning_a_machine_with_no_sticks_finds_none_rather_than_failing() {
for volume in rekordbox_volumes() {
assert!(
volume.path.join(PDB_PATH).is_file(),
"{} was returned without an export.pdb",
volume.path.display()
);
}
}
}