rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A checkout's `.git` files (`.git`, `HEAD`, `commondir`), read without
//! running git, as the session index groups sessions by repository
//! (`session::Workspace`), the TUI's status line names a branch, and
//! `rho/fs/look` names projects and checkouts. Each is read bounded and
//! only when it is a regular file, so a FIFO or a device another user puts
//! in a shared folder never blocks or floods the reader.

use std::{
    fs::{File, Metadata, OpenOptions},
    io::{self, ErrorKind, Read as _},
    path::{Path, PathBuf},
};

/// The most of a git pointer file read: a path, which Linux caps at 4096
/// bytes (`PATH_MAX`), after a short tag. rho-ui reads them the same.
const SMALL_FILE: u64 = 4096 + 64;

/// The git dir of `dir` when it is a work tree's top: its `.git` folder,
/// or the one its `.git` file names (`gitdir: <path>`, relative to `dir`),
/// as in a linked worktree or a submodule. That one need not be there.
pub(crate) fn git_dir_at(dir: &Path) -> Option<PathBuf> {
    let dot_git = dir.join(".git");
    if dot_git.is_dir() {
        return Some(dot_git);
    }
    let pointer = read_small(&dot_git)?;
    // As git reads it: `gitdir: ` exactly, then a path.
    let target = pointer.lines().next()?.strip_prefix("gitdir: ")?.trim();
    if target.is_empty() {
        return None;
    }
    // An absolute target replaces `dir`.
    Some(dir.join(target))
}

/// The start of the regular file at `path`, up to [`SMALL_FILE`], as git's
/// pointer files are read. Nothing for anything else, such as a FIFO,
/// which would block, or `/dev/zero`, which never ends.
pub(crate) fn read_small(path: &Path) -> Option<String> {
    let (file, _) = open_regular(path).ok()??;
    let mut text = String::new();
    file.take(SMALL_FILE).read_to_string(&mut text).ok()?;
    Some(text)
}

/// Opens `path` to read, with its metadata, when it is a regular file
/// through any symlink; `None` when nothing is there or something else is.
/// What `path` names is checked before opening it, so a device or a FIFO
/// is never opened, and again from what was opened, so nothing swapped in
/// between is read. On Unix the open neither waits, as a FIFO swapped in
/// would for a writer, nor takes a terminal as the daemon's own; the file
/// is then read blocking, as a regular file is.
pub(crate) fn open_regular(path: &Path) -> io::Result<Option<(File, Metadata)>> {
    match std::fs::metadata(path) {
        Ok(metadata) if metadata.is_file() => {}
        Ok(_) => return Ok(None),
        Err(error) if is_missing(&error) => return Ok(None),
        Err(error) => return Err(error),
    }
    let mut options = OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        options.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY);
    }
    let file = match options.open(path) {
        Ok(file) => file,
        // Gone since it was checked.
        Err(error) if is_missing(&error) => return Ok(None),
        Err(error) => return Err(error),
    };
    let metadata = file.metadata()?;
    if !metadata.is_file() {
        return Ok(None);
    }
    #[cfg(unix)]
    blocking_reads(&file)?;
    Ok(Some((file, metadata)))
}

/// Whether `error` says nothing is at the path, as when a part of it is a
/// file.
pub(crate) fn is_missing(error: &io::Error) -> bool {
    matches!(error.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory)
}

/// Clears the `O_NONBLOCK` `open_regular` opened `file` with, which is
/// regular, so no read of it answers "try again": a filesystem may honor
/// the flag for a regular file, as Linux did for a mandatory lock.
#[cfg(unix)]
fn blocking_reads(file: &File) -> io::Result<()> {
    use std::os::fd::AsRawFd as _;
    let fd = file.as_raw_fd();
    // SAFETY: fcntl reads the flags of `fd`, which `file` keeps open for
    // the call; it takes no pointers.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if flags == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: as above, setting the flags read less `O_NONBLOCK`.
    if unsafe { libc::fcntl(fd, libc::F_SETFL, flags & !libc::O_NONBLOCK) } == -1 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}