rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! What `rho/git/repos` reads of a folder's repository from its `.git`
//! files alone, as rho-ui reads one on its own machine: the top of its work
//! tree, what `HEAD` names and `origin`'s URL. Running git for them took 3
//! processes a folder, each ~9.5 ms through a version manager's shim.
//!
//! Each answer is the one git gives, or [`AskGit`] wherever git could
//! decide otherwise, and the caller runs git: for a repository another user
//! owns (`safe.directory`), one with extensions or a work tree elsewhere, a
//! search that meets a bare repository, a `HEAD` or branch git might not
//! read as written, a config that includes others or holds a line this does
//! not read as git surely would, and on Windows, where git checks owners by
//! SID. Only the repository's own config is read: an `origin` that only the
//! global or system config names is not seen, nor a global config so broken
//! git stops.

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

use rho_protocol::{
    methods::{GitHead, GitRepo},
    ClientEnvironment,
};

use super::canonical;
use crate::git::{is_missing, open_regular, read_small};

/// The files alone could answer otherwise than git: ask git.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct AskGit;

/// The work tree a folder is in, as its `.git` files say.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Checkout {
    /// Its top, resolved, as `rev-parse --show-toplevel` names it.
    pub(super) top: PathBuf,
    pub(super) repo: GitRepo,
}

/// Variables in git's environment that change what it finds or reads: a
/// search stopped early, config given another way, or, for root, the user
/// whose repositories it takes as its own. [`crate::git::LOCATION_ENV`]
/// are removed from it.
const GIT_READS_OTHERWISE: &[&str] = &[
    "GIT_CEILING_DIRECTORIES",
    "GIT_CONFIG",
    "GIT_CONFIG_COUNT",
    "GIT_CONFIG_PARAMETERS",
    "GIT_DISCOVERY_ACROSS_FILESYSTEM",
    "GIT_TEST_ASSUME_DIFFERENT_OWNER",
    "SUDO_UID",
];

/// The most of a repository's config read; a longer one is git's to read.
//
// The largest of the 28 repository configs under one developer's home was
// 19 KB, mostly `[branch]` sections (2026-12-03). A tripwire: past it the
// folder is answered by git, as before, only slower.
const CONFIG_BYTES: u64 = 1 << 20;

/// Reads folders' `.git` files for git running with an environment the
/// files can answer for; see [`Files::for_environment`].
#[derive(Clone, Copy, Debug)]
pub(super) struct Files(());

impl Files {
    /// A reader for git running with `environment`, unless git there reads
    /// otherwise than the files say: on Windows, where git checks owners by
    /// SID, which this does not read, or with any of
    /// [`GIT_READS_OTHERWISE`].
    pub(super) fn for_environment(environment: &ClientEnvironment) -> Option<Self> {
        let moved = environment
            .iter()
            .any(|(name, _)| GIT_READS_OTHERWISE.contains(&name));
        (cfg!(unix) && !moved).then_some(Self(()))
    }

    /// The work tree `folder` is in, which git running in `folder` would
    /// find; `None` when git would find none, as for a folder that is gone
    /// or is a file, which git cannot start in.
    pub(super) fn read(self, folder: &Path) -> Result<Option<Checkout>, AskGit> {
        let real = match canonical(folder) {
            Ok(real) => real,
            Err(error) if is_missing(&error) => return Ok(None),
            Err(_) => return Err(AskGit),
        };
        // Through `.`, so a folder git cannot enter is git's to judge.
        let Some(start) = stat(&real.join("."))? else {
            return Ok(None);
        };
        for dir in real.ancestors() {
            let here = stat(dir)?.ok_or(AskGit)?;
            // Git stops its search at a mount, finding no repository.
            if !same_device(&here, &start) {
                return Ok(None);
            }
            if let Some(dot_git) = stat(&dir.join(".git"))? {
                return checkout(dir, &here, &dot_git).map(Some);
            }
            // A bare repository, or a git dir itself.
            if stat(&dir.join("HEAD"))?.is_some() {
                return Err(AskGit);
            }
        }
        Ok(None)
    }
}

/// The work tree at `top` (its metadata `top_metadata`), whose `.git` is
/// `dot_git`, as git reads it once its search found `.git` there.
fn checkout(top: &Path, top_metadata: &Metadata, dot_git: &Metadata) -> Result<Checkout, AskGit> {
    let dot_git_path = top.join(".git");
    // Before reading anything another user could have put there.
    if !owned_by_me(top_metadata) || !is_mine(&dot_git_path)? {
        return Err(AskGit);
    }
    let git_dir = if dot_git.is_dir() {
        dot_git_path.clone()
    } else {
        // A linked worktree's or a submodule's: `gitdir: <path>`, relative
        // to the top.
        top.join(pointer(&dot_git_path, "gitdir: ")?)
    };
    stat(&git_dir)?.filter(Metadata::is_dir).ok_or(AskGit)?;
    if !is_mine(&git_dir)? {
        return Err(AskGit);
    }
    // A linked worktree's git dir names the one its repository's worktrees
    // share, relative to itself.
    let commondir = git_dir.join("commondir");
    let linked = stat(&commondir)?.is_some();
    let common_dir = if linked {
        git_dir.join(pointer(&commondir, "")?)
    } else {
        git_dir.clone()
    };
    for part in ["objects", "refs"] {
        stat(&common_dir.join(part))?
            .filter(Metadata::is_dir)
            .ok_or(AskGit)?;
    }
    let head = head(&git_dir, &common_dir)?;
    let config_path = common_dir.join("config");
    // Git reads a repository with no config as one with an empty one.
    let config = match stat(&config_path)? {
        None => Config::default(),
        Some(_) => {
            let (file, metadata) = open_regular(&config_path)
                .map_err(|_| AskGit)?
                .ok_or(AskGit)?;
            if metadata.len() > CONFIG_BYTES {
                return Err(AskGit);
            }
            let mut text = String::new();
            file.take(CONFIG_BYTES)
                .read_to_string(&mut text)
                .map_err(|_| AskGit)?;
            parse_config(&text).ok_or(AskGit)?
        }
    };
    let not_bare = config.bare.as_deref().is_none_or(|bare| {
        ["false", "no", "off", "0"].contains(&bare.to_ascii_lowercase().as_str())
    });
    // Version 1 differs only in reading extensions, which git decides.
    let format_known = config
        .format_version
        .as_deref()
        .is_none_or(|version| version == "0" || version == "1");
    let work_tree_here = match &config.work_tree {
        None => true,
        Some(work_tree) => {
            !linked && canonical(&git_dir.join(work_tree)).is_ok_and(|work_tree| work_tree == top)
        }
    };
    // Git reads no `core.bare` in a linked worktree, as a bare
    // repository's worktree.
    if !(linked || not_bare) || !format_known || config.extensions || !work_tree_here {
        return Err(AskGit);
    }
    Ok(Checkout {
        top: top.to_path_buf(),
        repo: GitRepo::new(Some(head), config.origin_url),
    })
}

/// The path a git pointer file at `path` holds after `tag`, as git reads
/// it: the file is that one line, ended by a newline or not. Git refuses
/// one padded with blanks or holding more lines, so that is its to judge.
fn pointer(path: &Path, tag: &str) -> Result<String, AskGit> {
    let text = read_small(path).ok_or(AskGit)?;
    let line = text.strip_suffix('\n').unwrap_or(&text);
    let target = line.strip_prefix(tag).ok_or(AskGit)?;
    let plain = !target.is_empty()
        && !target.contains(['\n', '\r'])
        && target.trim_matches([' ', '\t']) == target;
    plain.then(|| target.to_owned()).ok_or(AskGit)
}

/// What the `HEAD` in `git_dir` names, as `symbolic-ref -q HEAD` or else
/// `rev-parse -q --verify HEAD` prints it. A branch git might not read as
/// one, as a symbolic ref it follows or a ref file it cannot read, is git's
/// to name.
fn head(git_dir: &Path, common_dir: &Path) -> Result<GitHead, AskGit> {
    let path = git_dir.join("HEAD");
    // An old git's symlinked `HEAD`, which names its branch by its target.
    if is_symlink(&path)? {
        return Err(AskGit);
    }
    let text = read_small(&path).ok_or(AskGit)?;
    let head = head_as_written(&text).ok_or(AskGit)?;
    if let GitHead::Branch { reference } = &head {
        let dirs: &[&Path] = if git_dir == common_dir {
            &[git_dir]
        } else {
            &[git_dir, common_dir]
        };
        for dir in dirs {
            if !is_plain_branch(&dir.join(reference))? {
                return Err(AskGit);
            }
        }
    }
    Ok(head)
}

/// Whether the loose ref at `path`, if any, leaves its name the branch
/// `symbolic-ref` prints: none there, as for an unborn or packed branch, a
/// folder, which git passes over, or a file holding a whole commit. Git
/// follows a symbolic ref, as a file or a symlink, and fails on a file it
/// cannot read, as an empty one after a crash.
fn is_plain_branch(path: &Path) -> Result<bool, AskGit> {
    let metadata = match std::fs::symlink_metadata(path) {
        Ok(metadata) => metadata,
        Err(error) if is_missing(&error) => return Ok(true),
        Err(_) => return Err(AskGit),
    };
    if metadata.is_dir() {
        return Ok(true);
    }
    if !metadata.is_file() {
        return Ok(false);
    }
    let text = read_small(path).ok_or(AskGit)?;
    Ok(matches!(
        head_as_written(&text),
        Some(GitHead::Detached { .. })
    ))
}

/// A `HEAD` file's text, when it is one line naming a ref (`ref:
/// refs/...`) or a whole commit, as git writes it. Stricter than
/// `machine_fs::parse_head`, which names what a `HEAD` looks like.
fn head_as_written(text: &str) -> Option<GitHead> {
    let line = text.strip_suffix('\n').unwrap_or(text);
    if let Some(reference) = line.strip_prefix("ref: ") {
        return is_plain_ref(reference).then(|| GitHead::Branch {
            reference: reference.to_owned(),
        });
    }
    let commit = line.len() == 40 && line.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
    commit.then(|| GitHead::Detached {
        commit: line.to_owned(),
    })
}

/// Whether `reference` is a ref under `refs/` whose name git surely takes
/// (`git check-ref-format`): parts of ASCII letters, digits and `-_+.`,
/// none empty, starting or ending with `.` or ending with `.lock`, and no
/// `..`. Git names no branch for a `HEAD` naming one it refuses; a name
/// past these is its to judge.
fn is_plain_ref(reference: &str) -> bool {
    reference.starts_with("refs/")
        && !reference.contains("..")
        && reference.split('/').all(|part| {
            !part.is_empty()
                && !part.starts_with('.')
                && !part.ends_with('.')
                && !part.ends_with(".lock")
                && part
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || "-_+.".contains(c))
        })
}

/// What `repos` reads of a repository's config, each the last value given.
#[derive(Debug, Default, PartialEq, Eq)]
struct Config {
    /// `core.repositoryformatversion`.
    format_version: Option<String>,
    /// `core.bare`.
    bare: Option<String>,
    /// `core.worktree`.
    work_tree: Option<String>,
    /// Whether it has an `[extensions]` section.
    extensions: bool,
    /// `remote.origin.url`.
    origin_url: Option<String>,
}

/// A config file's `text` as git reads it, as far as [`Config`] goes;
/// `None` for any line this does not read as git surely would, such as an
/// include, a quoted or escaped value, or a legacy `[section.sub]` header.
fn parse_config(text: &str) -> Option<Config> {
    let mut config = Config::default();
    let mut section: Option<(String, Option<&str>)> = None;
    for line in text.lines() {
        let line = line.trim_start_matches([' ', '\t']);
        if is_blank(line) {
            continue;
        }
        if let Some(header) = line.strip_prefix('[') {
            let (header, rest) = header.split_once(']')?;
            if !is_blank(rest) {
                return None;
            }
            let (name, subsection) = match header.split_once([' ', '\t']) {
                None => (header, None),
                Some((name, quoted)) => {
                    let quoted = quoted.trim_start_matches([' ', '\t']);
                    let subsection = quoted.strip_prefix('"')?.strip_suffix('"')?;
                    if subsection.contains(['"', '\\']) {
                        return None;
                    }
                    (name, Some(subsection))
                }
            };
            if name.is_empty() || !name.chars().all(is_name_char) {
                return None;
            }
            let name = name.to_ascii_lowercase();
            if name == "include" || name == "includeif" {
                return None;
            }
            config.extensions |= name == "extensions";
            section = Some((name, subsection));
            continue;
        }
        let end = line.find(|c| !is_name_char(c)).unwrap_or(line.len());
        let (key, rest) = line.split_at(end);
        if !key.starts_with(|c: char| c.is_ascii_alphabetic()) {
            return None;
        }
        let (name, subsection) = section.as_ref()?;
        let rest = rest.trim_start_matches([' ', '\t']);
        // `key` alone is true: for one of these keys, git's to read. Git
        // refuses anything else after a key but `=`, a comment included.
        let value = if rest.is_empty() {
            None
        } else {
            Some(plain_value(rest.strip_prefix('=')?)?)
        };
        let slot = match (
            name.as_str(),
            *subsection,
            key.to_ascii_lowercase().as_str(),
        ) {
            ("core", None, "repositoryformatversion") => &mut config.format_version,
            ("core", None, "bare") => &mut config.bare,
            ("core", None, "worktree") => &mut config.work_tree,
            ("remote", Some("origin"), "url") => &mut config.origin_url,
            _ => continue,
        };
        *slot = Some(value?);
    }
    Some(config)
}

/// A value after its `=`, unquoted: git's, less a comment and the blanks
/// around it, with the ones within kept. `None` for one with a quote, an
/// escape, a continued line, or a control character, such as a tab or a
/// lone carriage return, which git rewrites.
fn plain_value(value: &str) -> Option<String> {
    let value = value.split(['#', ';']).next().unwrap_or_default();
    let value = value.trim_matches([' ', '\t']);
    if value.contains(['"', '\\']) || value.contains(char::is_control) {
        return None;
    }
    Some(value.to_owned())
}

/// A config line part that is empty or a comment.
fn is_blank(rest: &str) -> bool {
    let rest = rest.trim_start_matches([' ', '\t']);
    rest.is_empty() || rest.starts_with(['#', ';'])
}

/// A character of a section or key name.
fn is_name_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '-'
}

/// What is at `path`, through any symlink: `None` when nothing is, and an
/// error git might read otherwise, as a folder it may not search, its to
/// judge.
fn stat(path: &Path) -> Result<Option<Metadata>, AskGit> {
    match std::fs::metadata(path) {
        Ok(metadata) => Ok(Some(metadata)),
        Err(error) if is_missing(&error) => Ok(None),
        Err(_) => Err(AskGit),
    }
}

/// Whether `path` is a symlink, read without following it.
fn is_symlink(path: &Path) -> Result<bool, AskGit> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) => Ok(metadata.is_symlink()),
        Err(error) if is_missing(&error) => Ok(false),
        Err(_) => Err(AskGit),
    }
}

/// Whether the daemon's user owns `path`, both the link and what it names
/// when it is a symlink, so the answer holds whichever git checks.
fn is_mine(path: &Path) -> Result<bool, AskGit> {
    let link = std::fs::symlink_metadata(path).map_err(|_| AskGit)?;
    let target = stat(path)?.ok_or(AskGit)?;
    Ok(owned_by_me(&link) && owned_by_me(&target))
}

/// Whether the daemon's user owns what `metadata` is of, as git checks the
/// work tree, its `.git` and its git dir before reading them.
#[cfg(unix)]
fn owned_by_me(metadata: &Metadata) -> bool {
    use std::os::unix::fs::MetadataExt as _;
    // SAFETY: geteuid has no arguments or memory-safety preconditions.
    metadata.uid() == unsafe { libc::geteuid() }
}

/// Not reached: [`Files::for_environment`] leaves Windows to git.
#[cfg(not(unix))]
fn owned_by_me(_: &Metadata) -> bool {
    false
}

/// Whether two folders are on one filesystem.
#[cfg(unix)]
fn same_device(one: &Metadata, other: &Metadata) -> bool {
    use std::os::unix::fs::MetadataExt as _;
    one.dev() == other.dev()
}

/// Not reached: [`Files::for_environment`] leaves Windows to git.
#[cfg(not(unix))]
fn same_device(_: &Metadata, _: &Metadata) -> bool {
    false
}

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