use std::{io::ErrorKind, path::Path};
use rho_protocol::{methods::HostPath, RpcError};
use super::{failed, host_path, make_root};
const MAX_NAME_TRIES: u32 = 10_000;
pub(super) fn make_folder(parent: &Path, name: Option<&str>) -> Result<HostPath, RpcError> {
let root = make_root(parent)?;
let root_path = host_path(&root)?;
let Some(name) = name else {
return Ok(root_path);
};
for n in 1..=MAX_NAME_TRIES {
let dest = if n == 1 {
root.join(name)
} else {
root.join(format!("{name}-{n}"))
};
match std::fs::create_dir(&dest) {
Ok(()) => return host_path(&dest),
Err(error) if error.kind() == ErrorKind::AlreadyExists => {}
Err(error) => return Err(failed(format!("Couldn't make {}: {error}", dest.display()))),
}
}
Err(failed(format!(
"Couldn't make a free folder for {name} in {}: {MAX_NAME_TRIES} names were taken",
root.display()
)))
}
pub(super) fn remove_empty_folder(path: &HostPath) -> Result<(), RpcError> {
std::fs::remove_dir(path.as_str())
.map_err(|error| failed(format!("Couldn't remove {path}: {error}")))
}