rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The `rho/fs/*` host calls on the daemon's machine (`docs/protocol.md`,
//! "Files on the daemon's machine"): rho-ui's reading and making of
//! folders and files, which it ran over ssh as shell scripts, ported from
//! the Rust twins it ran on its own machine. Each call is logged with the
//! paths it names, never what a file holds.
//!
//! This module answers the calls and keeps what other host calls on the
//! machine share with them; `look`, `files`, `read` and `folders` do the
//! work.

use std::{
    ffi::OsStr,
    fs::Metadata,
    io,
    path::{Path, PathBuf},
    time::UNIX_EPOCH,
};

use rho_protocol::{
    methods::{
        FsFilesParams, FsFilesResponse, FsIsFileParams, FsIsFileResponse, FsLookParams,
        FsLookResponse, FsMakeFolderParams, FsMakeFolderResponse, FsRead, FsReadParams,
        FsRemoveEmptyFolderParams, FsRemoveEmptyFolderResponse, GitHead, HostPath, FS_FILES,
        FS_IS_FILE, FS_LOOK, FS_MAKE_FOLDER, FS_READ, FS_REMOVE_EMPTY_FOLDER,
    },
    Caller, ErrorCode, FsService, RpcError,
};

use super::machine::{
    blocking, failed, host_path, log_call, log_call_counted, spawn_stream, Machine,
};
use crate::{
    paths::{is_plain_windows_name, without_verbatim_prefix, without_verbatim_unc},
    session::Workspace,
};

mod files;
mod folders;
mod look;
mod read;

/// What a `HEAD` holds in a reftable repository, which keeps its refs in
/// tables: a stub naming a branch no ref can be, so older git fails on it.
const REFTABLE_HEAD: &str = "ref: refs/heads/.invalid";

impl FsService for Machine {
    async fn look(&self, caller: Caller, params: FsLookParams) -> Result<FsLookResponse, RpcError> {
        let FsLookParams { resolve, list, .. } = params;
        log_call(&caller, FS_LOOK, resolve.iter().chain(&list));
        blocking(move || {
            let resolved = resolve.map(|path| look::resolve_folder(Path::new(path.as_str())));
            let listing = list.map(|path| look::list_folder(Path::new(path.as_str())));
            FsLookResponse::new(resolved, listing)
        })
        .await
    }

    async fn files(
        &self,
        caller: Caller,
        params: FsFilesParams,
    ) -> Result<FsFilesResponse, RpcError> {
        log_call(&caller, FS_FILES, [&params.folder]);
        let folder = PathBuf::from(params.folder.as_str());
        if !tokio::fs::metadata(&folder)
            .await
            .is_ok_and(|metadata| metadata.is_dir())
        {
            return Err(not_a_folder(&params.folder));
        }
        let environment = self.login_environment().await;
        let stream = files::list_files(&caller, folder, environment, params.limit).await?;
        Ok(FsFilesResponse::new(stream))
    }

    async fn read(&self, caller: Caller, params: FsReadParams) -> Result<FsRead, RpcError> {
        log_call(&caller, FS_READ, [&params.folder, &params.path]);
        read::read(&caller, params).await
    }

    async fn is_file(
        &self,
        caller: Caller,
        params: FsIsFileParams,
    ) -> Result<FsIsFileResponse, RpcError> {
        let FsIsFileParams { paths, .. } = params;
        log_call_counted(&caller, FS_IS_FILE, &paths);
        let is_file = blocking(move || {
            paths
                .iter()
                .map(|path| Path::new(path.as_str()).is_file())
                .collect::<Vec<_>>()
        })
        .await?;
        Ok(FsIsFileResponse::new(is_file))
    }

    async fn make_folder(
        &self,
        caller: Caller,
        params: FsMakeFolderParams,
    ) -> Result<FsMakeFolderResponse, RpcError> {
        log_call(&caller, FS_MAKE_FOLDER, [&params.parent]);
        let FsMakeFolderParams { parent, name, .. } = params;
        if let Some(name) = &name {
            check_name(name)?;
        }
        let path =
            blocking(move || folders::make_folder(Path::new(parent.as_str()), name.as_deref()))
                .await??;
        Ok(FsMakeFolderResponse::new(path))
    }

    async fn remove_empty_folder(
        &self,
        caller: Caller,
        params: FsRemoveEmptyFolderParams,
    ) -> Result<FsRemoveEmptyFolderResponse, RpcError> {
        log_call(&caller, FS_REMOVE_EMPTY_FOLDER, [&params.path]);
        let FsRemoveEmptyFolderParams { path, .. } = params;
        blocking(move || folders::remove_empty_folder(&path)).await??;
        Ok(FsRemoveEmptyFolderResponse::default())
    }
}

fn not_a_folder(folder: &HostPath) -> RpcError {
    failed(format!("{folder} isn't a folder."))
}

/// `path` resolved, through any symlinks, as the calls answer it: with no
/// Windows verbatim prefix, a share's included, as a client canonicalizes
/// its own paths to compare them with these.
pub(super) fn canonical(path: &Path) -> io::Result<PathBuf> {
    crate::paths::canonicalize(path).map(without_verbatim_unc)
}

/// Makes `folder` with its parents, answering it with its symlinks
/// resolved: the folder `make_folder` makes in, and a clone's.
pub(super) fn make_root(folder: &Path) -> Result<PathBuf, RpcError> {
    std::fs::create_dir_all(folder)
        .map_err(|error| failed(format!("Couldn't make {}: {error}", folder.display())))?;
    canonical(folder)
        .map_err(|error| failed(format!("Couldn't open {}: {error}", folder.display())))
}

/// When `metadata`'s file last changed, in nanoseconds since the Unix
/// epoch: the stamp `rho/fs/read` answers and `rho/git/repos` gives an
/// icon, so a client compares the two.
pub(super) fn modified_ns(metadata: &Metadata) -> Option<u64> {
    metadata
        .modified()
        .ok()
        .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
        .and_then(|since| u64::try_from(since.as_nanos()).ok())
}

/// The project of the folder `real`, which is resolved: the main checkout
/// of the git repository it is in or, for a bare repository's worktree,
/// which has no main checkout, the worktree itself; outside a repository,
/// `real`. The repository is the one the daemon groups sessions by
/// ([`Workspace::resolve`]), read from the `.git` files alone with no git
/// process, so a `.git` file that names no git dir there is passed over for
/// the repository above it.
pub(super) fn project_root(real: &Path) -> PathBuf {
    let workspace = Workspace::resolve(real);
    if !workspace.is_git() {
        return real.to_path_buf();
    }
    // A bare repository's folder is named otherwise.
    let has_main_checkout = workspace
        .repo
        .file_name()
        .is_some_and(|name| name == ".git");
    let project = match workspace.repo.parent() {
        Some(main) if has_main_checkout => main,
        _ => &workspace.worktree,
    };
    // `Workspace` resolves as the standard library does, verbatim on Windows.
    without_verbatim_unc(without_verbatim_prefix(project.to_path_buf()))
}

/// What a `HEAD` file's first line names: `ref: <ref>` a branch, anything
/// else a commit; nothing for a reftable repository's, whose `HEAD` is in
/// its tables.
pub(super) fn parse_head(head: &str) -> Option<GitHead> {
    let head = head.lines().next()?.trim();
    if head == REFTABLE_HEAD {
        return None;
    }
    match head.strip_prefix("ref:") {
        Some(reference) => Some(GitHead::Branch {
            reference: reference.trim().to_owned(),
        }),
        None if head.is_empty() => None,
        None => Some(GitHead::Detached {
            commit: head.to_owned(),
        }),
    }
}

/// Refuses a `make_folder` name that is not one path part this machine
/// can make a folder by.
pub(super) fn check_name(name: &str) -> Result<(), RpcError> {
    if is_folder_name(name, cfg!(windows)) {
        Ok(())
    } else {
        Err(RpcError::new(
            ErrorCode::InvalidParams,
            format!("the folder name {name:?} isn't one path part this machine can make"),
        ))
    }
}

/// Whether `name` is one path part a folder can be made by, on Windows
/// when `windows`. There it also holds none of the characters Windows
/// refuses in a name, names no device, such as `con` or `nul.txt`, which
/// would open the device, and ends in neither a dot nor a space, which
/// Windows trims, making another folder than the one named.
fn is_folder_name(name: &str, windows: bool) -> bool {
    const SEPARATORS: [char; 3] = ['/', '\\', '\0'];
    /// What Windows allows in no file name, besides the separators and the
    /// control characters.
    const NOT_ON_WINDOWS: [char; 7] = [':', '<', '>', '"', '|', '?', '*'];
    let one_part = !matches!(name, "" | "." | "..") && !name.contains(SEPARATORS);
    let windows_takes = !windows
        || (!name.contains(NOT_ON_WINDOWS)
            && !name.contains(|c: char| matches!(c, '\u{1}'..='\u{1f}'))
            && is_plain_windows_name(OsStr::new(name)));
    one_part && windows_takes
}

#[cfg(test)]
#[path = "machine_fs_tests.rs"]
mod tests;