curd-editor 0.8.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, selection, search and replace, a git menu, and language-server colours, errors and completion
//! 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"],
    )?;
    // The same spelling of the folder as the rest of the editor uses: on
    // Windows git writes it differently, and nothing would match.
    let top = PathBuf::from(top.trim_end());
    let top = std::fs::canonicalize(&top).unwrap_or(top);
    Some(GitInfo::parse(&status, &top))
}

/// 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(),
    )
}

/// The lines of the file at `path` as they were in the last commit, or
/// `None` if the file is not in the last commit (or not in git at all).
pub fn committed_lines(path: &Path) -> Option<Vec<String>> {
    let name = path.file_name()?.to_str()?;
    // `./` makes git read the name relative to the folder it runs in.
    let text = run(path.parent()?, &["show", &format!("HEAD:./{name}")])?;
    Some(text.lines().map(String::from).collect())
}

/// Runs a git command that changes something (stage, commit, switch, push)
/// in `dir`. On failure, returns what git said went wrong.
///
/// Git is never allowed to ask a question on the terminal, which the editor
/// is drawing on: a command that needs a password fails instead.
pub fn action(dir: &Path, args: &[&str]) -> Result<(), String> {
    let mut command = Command::new("git");
    command
        .arg("-C")
        .arg(dir)
        .args(args)
        .stdin(Stdio::null())
        .env("GIT_TERMINAL_PROMPT", "0");
    if std::env::var_os("GIT_SSH_COMMAND").is_none() {
        command.env("GIT_SSH_COMMAND", "ssh -o BatchMode=yes");
    }
    let output = command.output().map_err(|_| "git is not installed".to_string())?;
    if output.status.success() {
        return Ok(());
    }
    // The reason is usually the last thing git printed.
    let said = |bytes: &[u8]| {
        String::from_utf8_lossy(bytes)
            .lines()
            .rev()
            .map(str::trim)
            .find(|line| !line.is_empty() && !line.starts_with("hint:"))
            .map(String::from)
    };
    Err(said(&output.stderr)
        .or_else(|| said(&output.stdout))
        .unwrap_or_else(|| "git failed".into()))
}

/// Pushes the checked-out branch. A branch that has never been pushed is
/// sent to `origin` and set to follow it there.
pub fn push(dir: &Path) -> Result<(), String> {
    if run(dir, &["rev-parse", "--abbrev-ref", "@{upstream}"]).is_some() {
        action(dir, &["push"])
    } else {
        action(dir, &["push", "--set-upstream", "origin", "HEAD"])
    }
}

/// The branches that can be switched to: the local ones, then those that
/// only exist on a remote (by the name they would get here).
pub fn branches(dir: &Path) -> Vec<String> {
    let format = "--format=%(refname)";
    let output = run(dir, &["for-each-ref", format, "refs/heads", "refs/remotes"]);
    parse_branches(&output.unwrap_or_default())
}

fn parse_branches(output: &str) -> Vec<String> {
    let mut names: Vec<String> = Vec::new();
    for line in output.lines() {
        let name = match line.strip_prefix("refs/heads/") {
            Some(name) => Some(name),
            // `refs/remotes/origin/name`: drop the remote's own name.
            None => line
                .strip_prefix("refs/remotes/")
                .and_then(|name| name.split_once('/'))
                .map(|(_, name)| name)
                .filter(|name| *name != "HEAD"),
        };
        if let Some(name) = name
            && !names.iter().any(|known| known == name)
        {
            names.push(name.to_string());
        }
    }
    names
}