use std::path::Path;
use crate::daemon;
pub(crate) fn current_uid() -> u32 {
unsafe { libc::getuid() }
}
pub(crate) fn chown_to_me(path: &Path, recursive: bool) -> String {
let flag = if recursive { " -R" } else { "" };
format!("sudo chown{flag} {} {}", current_uid(), quoted(path))
}
pub(crate) fn reclaim_private_file(path: &Path) -> String {
format!("{} && chmod 600 {}", chown_to_me(path, false), quoted(path))
}
pub(crate) fn quoted(path: &Path) -> String {
daemon::shell_word(&path.to_string_lossy())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chown_hands_the_quoted_path_to_this_user() {
let uid = current_uid();
let path = Path::new("/home/u/my home/.second-brain");
assert_eq!(
chown_to_me(path, false),
format!("sudo chown {uid} '/home/u/my home/.second-brain'")
);
assert_eq!(
chown_to_me(path, true),
format!("sudo chown -R {uid} '/home/u/my home/.second-brain'")
);
}
#[test]
fn a_private_file_is_chowned_then_closed() {
let uid = current_uid();
let path = Path::new("/home/u/.second-brain/api.token");
assert_eq!(
reclaim_private_file(path),
format!(
"sudo chown {uid} /home/u/.second-brain/api.token && chmod 600 /home/u/.second-brain/api.token"
)
);
}
}