curd-editor 0.6.0

A small terminal code editor: projects with a file tree, git status, tabs, quick open and language-server support
//! What git knows about the project's files: which are modified, staged,
//! new or ignored, and which branch is checked out.
//!
//! This asks the `git` command rather than reading the repository itself,
//! so it always agrees with what `git status` would say.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

#[cfg(test)]
mod tests;

/// The state of a file or folder. Later ones win when a folder holds files
/// in different states, so a folder shows the most pressing one.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum FileStatus {
    /// Left out of git by a `.gitignore`.
    Ignored,
    /// A new file git has not been told about.
    Untracked,
    /// Changed, and added to the next commit with `git add`.
    Staged,
    /// Changed since the last commit, and not staged yet.
    Modified,
    /// Left in conflict by a merge.
    Conflict,
}

#[derive(Debug, Default, PartialEq)]
pub struct GitInfo {
    /// The checked-out branch.
    pub branch: String,
    /// The state of each path git reported, by absolute path. Files that
    /// are committed and unchanged are not listed.
    entries: HashMap<PathBuf, FileStatus>,
    /// The most pressing state among the files inside each folder.
    folders: HashMap<PathBuf, FileStatus>,
}

impl GitInfo {
    /// Reads the output of `git status --porcelain=v1 -z --branch --ignored`
    /// for the repository whose top folder is `top`.
    pub fn parse(output: &str, top: &Path) -> Self {
        let mut info = Self::default();
        let mut fields = output.split('\0');
        while let Some(field) = fields.next() {
            if let Some(branch) = field.strip_prefix("## ") {
                info.branch = parse_branch(branch);
                continue;
            }
            // Each entry is two status letters, a space, and the path.
            let (Some(code), Some(path)) = (field.get(..2), field.get(3..)) else {
                continue;
            };
            let mut letters = code.chars();
            let (index, tree) = (letters.next().unwrap_or(' '), letters.next().unwrap_or(' '));
            if index == 'R' || index == 'C' {
                // A rename or copy is followed by the old path: skip it.
                fields.next();
            }
            let status = match (index, tree) {
                ('?', '?') => FileStatus::Untracked,
                ('!', '!') => FileStatus::Ignored,
                ('U', _) | (_, 'U') | ('A', 'A') | ('D', 'D') => FileStatus::Conflict,
                (_, ' ') => FileStatus::Staged,
                _ => FileStatus::Modified,
            };
            // Whole folders are reported with a trailing slash.
            let path = top.join(path.trim_end_matches('/'));
            if status != FileStatus::Ignored {
                for folder in path.ancestors().skip(1).take_while(|folder| folder.starts_with(top))
                {
                    let summary = info.folders.entry(folder.to_path_buf()).or_insert(status);
                    *summary = status.max(*summary);
                }
            }
            info.entries.insert(path, status);
        }
        info
    }

    /// The state of the file or folder at `path` (absolute). `None` means
    /// it is committed and unchanged.
    pub fn status_of(&self, path: &Path) -> Option<FileStatus> {
        if let Some(status) = self.entries.get(path).or(self.folders.get(path)) {
            return Some(*status);
        }
        // Git reports a new or ignored folder once, not file by file:
        // everything inside it is in the same state.
        path.ancestors()
            .skip(1)
            .find_map(|folder| self.entries.get(folder))
            .filter(|status| matches!(status, FileStatus::Untracked | FileStatus::Ignored))
            .copied()
    }
}

/// The branch name from the first line of `git status --branch`, which
/// looks like `main...origin/main [ahead 1]`.
fn parse_branch(line: &str) -> String {
    let line = line.strip_prefix("No commits yet on ").unwrap_or(line);
    if line.starts_with("HEAD (no branch)") {
        return "detached".into();
    }
    let name = line.split("...").next().unwrap_or(line);
    name.split(' ').next().unwrap_or(name).to_string()
}

/// Runs git in `dir` and returns what it printed, or `None` if git is not
/// installed, `dir` is not in a repository, or the command failed.
fn run(dir: &Path, args: &[&str]) -> Option<String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
        .ok()?;
    output
        .status
        .success()
        .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
}

/// The git state of the repository `dir` is in, if it is in one.
pub fn load(dir: &Path) -> Option<GitInfo> {
    let top = run(dir, &["rev-parse", "--show-toplevel"])?;
    let status = run(
        dir,
        &["status", "--porcelain=v1", "-z", "--branch", "--ignored"],
    )?;
    Some(GitInfo::parse(&status, Path::new(top.trim_end())))
}

/// Every file in the project that is not ignored, relative to `dir`.
pub fn list_files(dir: &Path) -> Option<Vec<String>> {
    let output = run(
        dir,
        &["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
    )?;
    Some(
        output
            .split('\0')
            .filter(|path| !path.is_empty())
            .map(String::from)
            .collect(),
    )
}