rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The folders `rho/fs/make_folder` makes and `rho/fs/remove_empty_folder`
//! removes.

use std::{io::ErrorKind, path::Path};

use rho_protocol::{methods::HostPath, RpcError};

use super::{failed, host_path, make_root};

/// The most names `make_folder` tries, `name` through `name-10000`, before
/// it says they were all taken.
//
// A tripwire, not a budget: rho-ui makes a lead's or a scratch session's
// folder here by its slug, among a few hundred siblings at most in
// practice. It only stops a filesystem that answers "already exists" for
// every name from looping forever.
const MAX_NAME_TRIES: u32 = 10_000;

/// Makes `parent` with its parents and, with a `name`, the first of
/// `name`, `name-2`, `name-3`, … free in it, each taken by making it so
/// two clients never get the same one: what `make_folder` answers. Anything
/// at a name, a dangling symlink included, takes it. `name` was checked
/// ([`super::check_name`]).
pub(super) fn make_folder(parent: &Path, name: Option<&str>) -> Result<HostPath, RpcError> {
    let root = make_root(parent)?;
    // Whatever is made in it can be named only if it can.
    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()
    )))
}

/// Removes the folder at `path` when it is empty, as
/// `remove_empty_folder` asks; one that isn't stays, and the call fails.
/// Never recursive.
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}")))
}