rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Where the rules read the project's files from. A change that is not checked out (a pull
//! request, another branch, an old commit) is read from its commit, so the rules see the code
//! under review and not whatever happens to be on disk.

use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;

use super::git;

/// Files larger than this are not worth reading.
const MAX_FILE: u64 = 1_000_000;
const MAX_SCANNED: usize = 4000;
const SKIP: &[&str] = &["node_modules", "target", "vendor", ".git", "dist", "build", "storage", ".next", ".svelte-kit"];

#[derive(Clone, Debug, Default)]
pub enum Tree {
    /// No files to read: a diff on its own.
    #[default]
    None,
    Disk(PathBuf),
    Commit {
        root: PathBuf,
        /// Path to (blob id, size) of every regular file.
        files: Arc<BTreeMap<String, (String, u64)>>,
    },
}

impl Tree {
    pub fn commit(root: &Path, sha: &str) -> Result<Tree, String> {
        let list = git::output(root, &["ls-tree", "-r", "-z", "-l", "--full-tree", sha])?;
        let files = list.split('\0').filter_map(parse_entry).collect();
        Ok(Tree::Commit { root: root.to_path_buf(), files: Arc::new(files) })
    }

    /// The repository folder, for things that are never committed (installed tools).
    pub fn disk_root(&self) -> Option<&Path> {
        match self {
            Tree::None => None,
            Tree::Disk(root) | Tree::Commit { root, .. } => Some(root),
        }
    }

    pub fn is_file(&self, rel: &str) -> bool {
        match self {
            Tree::None => false,
            Tree::Disk(root) => root.join(rel).is_file(),
            Tree::Commit { files, .. } => files.contains_key(normal(rel)),
        }
    }

    pub fn is_dir(&self, rel: &str) -> bool {
        match self {
            Tree::None => false,
            Tree::Disk(root) => root.join(rel).is_dir(),
            Tree::Commit { files, .. } => {
                let prefix = format!("{}/", normal(rel));
                files.range(prefix.clone()..).next().is_some_and(|(p, _)| p.starts_with(&prefix))
            }
        }
    }

    pub fn read(&self, rel: &str) -> Option<String> {
        match self {
            Tree::None => None,
            Tree::Disk(root) => std::fs::read_to_string(root.join(rel)).ok(),
            Tree::Commit { root, files } => {
                let (blob, size) = files.get(normal(rel))?;
                (*size < MAX_FILE).then(|| git::output(root, &["cat-file", "blob", blob]).ok())?
            }
        }
    }

    /// The text files under `dir` with one of the extensions, as (path, content). Skips
    /// dependency and build folders, and stops after a few thousand files.
    pub fn scan(&self, dir: &str, exts: &[&str]) -> Vec<(String, String)> {
        let dir = normal(dir);
        match self {
            Tree::None => Vec::new(),
            Tree::Disk(root) => {
                let mut out = Vec::new();
                let start = if dir.is_empty() { root.clone() } else { root.join(dir) };
                walk(root, &start, exts, &mut out);
                out
            }
            Tree::Commit { root, files } => {
                let wanted: Vec<(&String, &String)> = files
                    .iter()
                    .filter(|(path, (_, size))| *size < MAX_FILE && under(path, dir) && scannable(path, dir, exts))
                    .take(MAX_SCANNED)
                    .map(|(path, (blob, _))| (path, blob))
                    .collect();
                read_blobs(root, &wanted)
            }
        }
    }
}

fn normal(rel: &str) -> &str {
    let rel = rel.strip_prefix("./").unwrap_or(rel);
    if rel == "." { "" } else { rel.trim_end_matches('/') }
}

fn under(path: &str, dir: &str) -> bool {
    dir.is_empty() || path.strip_prefix(dir).is_some_and(|rest| rest.starts_with('/'))
}

fn extension(path: &str) -> String {
    super::rules::ext(path)
}

/// Whether the folders below `dir` are ones worth looking in, and the extension is wanted.
fn scannable(path: &str, dir: &str, exts: &[&str]) -> bool {
    let below = path[dir.len()..].trim_start_matches('/');
    let mut parts: Vec<&str> = below.split('/').collect();
    parts.pop();
    parts.iter().all(|p| !SKIP.contains(p) && !p.starts_with('.')) && exts.contains(&extension(path).as_str())
}

/// `<mode> <type> <id> <size>\t<path>` from `git ls-tree -l`. Links and submodules are left out.
fn parse_entry(entry: &str) -> Option<(String, (String, u64))> {
    let (meta, path) = entry.split_once('\t')?;
    let mut parts = meta.split_whitespace();
    let (mode, kind, id, size) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
    (kind == "blob" && mode.starts_with("100")).then(|| (path.to_string(), (id.to_string(), size.parse().unwrap_or(0))))
}

/// Many blobs with one git process. Files that are not UTF-8 are left out.
fn read_blobs(root: &Path, wanted: &[(&String, &String)]) -> Vec<(String, String)> {
    let mut out = Vec::new();
    if wanted.is_empty() {
        return out;
    }
    let child = git::command(root).args(["cat-file", "--batch"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn();
    let Ok(mut child) = child else { return out };
    let (Some(mut stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else { return out };
    let ids: String = wanted.iter().map(|(_, id)| format!("{id}\n")).collect();
    // Written from another thread: git answers while it is still being asked.
    let writer = std::thread::spawn(move || {
        let _ = stdin.write_all(ids.as_bytes());
    });
    let mut reader = BufReader::new(stdout);
    for (path, _) in wanted {
        let mut header = String::new();
        if reader.read_line(&mut header).unwrap_or(0) == 0 {
            break;
        }
        let Some(size) = header.split_whitespace().nth(2).and_then(|s| s.parse::<usize>().ok()) else { continue };
        // The content is followed by a newline of git's own.
        let mut body = vec![0; size + 1];
        if reader.read_exact(&mut body).is_err() {
            break;
        }
        body.pop();
        if let Ok(text) = String::from_utf8(body) {
            out.push(((*path).clone(), text));
        }
    }
    let _ = writer.join();
    let _ = child.wait();
    out
}

fn walk(root: &Path, dir: &Path, exts: &[&str], out: &mut Vec<(String, String)>) {
    let Ok(entries) = std::fs::read_dir(dir) else { return };
    for e in entries.flatten() {
        if out.len() >= MAX_SCANNED {
            return;
        }
        let path = e.path();
        let name = e.file_name().to_string_lossy().into_owned();
        let Ok(ty) = e.file_type() else { continue };
        if ty.is_dir() {
            if !SKIP.contains(&name.as_str()) && !name.starts_with('.') {
                walk(root, &path, exts, out);
            }
        } else if ty.is_file()
            && exts.contains(&extension(&name).as_str())
            && e.metadata().is_ok_and(|m| m.len() < MAX_FILE)
            && let Ok(text) = std::fs::read_to_string(&path)
        {
            let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
            out.push((rel, text));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::review::testutil::Scratch;

    #[test]
    fn a_commit_is_read_even_when_the_disk_has_moved_on() {
        let s = Scratch::new("tree-commit");
        git::testing::init(&s.0);
        s.write("src/a.rs", "committed\n");
        s.write("src/deep/b.rs", "also\n");
        s.write("src/node_modules/c.rs", "skipped\n");
        s.write("notes.txt", "other\n");
        git::testing::commit(&s.0, "one");
        s.write("src/a.rs", "changed on disk\n");
        s.write("src/new.rs", "not committed\n");
        let tree = Tree::commit(&s.0, "HEAD").unwrap();
        assert_eq!(tree.read("src/a.rs").as_deref(), Some("committed\n"));
        assert_eq!(tree.read("./src/a.rs").as_deref(), Some("committed\n"));
        assert!(tree.is_file("notes.txt") && tree.is_dir("src") && tree.is_dir("src/deep"));
        assert!(!tree.is_file("src/new.rs") && !tree.is_dir("sr") && !tree.is_dir("notes.txt"));
        let found = tree.scan("src", &["rs"]);
        let paths: Vec<&str> = found.iter().map(|(p, _)| p.as_str()).collect();
        assert_eq!(paths, ["src/a.rs", "src/deep/b.rs"]);
        assert_eq!(found[0].1, "committed\n");
        assert_eq!(tree.scan(".", &["rs"]).len(), 2);
    }
}