navid/veins / ac26a51bd7b5f4a22beb0ca203a433857c68b337b79aa5ce14683290ab9ae3a7 / veinsrs/src/worktree/attributes.rs

attributes.rs

← veinsrs/src/worktree · 6355 bytes · raw · download

use std::path::Path;

use crate::core;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AttributeEol {
    None,
    Lf,
    Crlf,
    Cr,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AttributeText {
    Auto,
    Text,
    Binary,
}

#[derive(Clone, Copy)]
pub struct PathAttributes {
    pub generated: bool,
    pub text: AttributeText,
    pub eol: AttributeEol,
}

impl Default for PathAttributes {
    fn default() -> Self {
        Self {
            generated: false,
            text: AttributeText::Auto,
            eol: AttributeEol::None,
        }
    }
}

#[derive(Clone)]
struct Rule {
    pattern: String,
    has_slash: bool,
    generated_set: bool,
    generated: bool,
    text_set: bool,
    text: AttributeText,
    eol_set: bool,
    eol: AttributeEol,
}

#[derive(Clone, Default)]
pub struct AttributeRules {
    rules: Vec<Rule>,
    mtime_ns: i64,
}

fn next_token<'a>(text: &'a str, position: &mut usize) -> &'a str {
    while *position < text.len() && matches!(text.as_bytes()[*position], b' ' | b'\t') {
        *position += 1;
    }
    let start = *position;
    while *position < text.len() && !matches!(text.as_bytes()[*position], b' ' | b'\t') {
        *position += 1;
    }
    &text[start..*position]
}

fn basename(path: &str) -> &str {
    path.rsplit_once('/').map(|(_, name)| name).unwrap_or(path)
}

fn rule_matches(pattern: &str, has_slash: bool, path: &str) -> bool {
    core::glob_match(pattern, path) || (!has_slash && core::glob_match(pattern, basename(path)))
}

fn parse_eol(value: &str) -> AttributeEol {
    match value {
        "lf" => AttributeEol::Lf,
        "crlf" => AttributeEol::Crlf,
        "cr" => AttributeEol::Cr,
        _ => AttributeEol::None,
    }
}

impl AttributeRules {
    pub fn load(root: &Path) -> Self {
        let mut rules = Self::default();
        let path = root.join(".vnattribs");
        if let Some(info) = core::stat_path(&path) {
            rules.mtime_ns = info.mtime_ns as i64;
        }
        let Some(data) = core::read_file_opt(&path, 0) else {
            return rules;
        };
        let text = String::from_utf8_lossy(&data);
        for raw in text.lines() {
            let line = core::trim_str(raw);
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let mut position = 0;
            let pattern = next_token(line, &mut position);
            if pattern.is_empty() {
                continue;
            }
            let mut rule = Rule {
                pattern: pattern.to_string(),
                has_slash: pattern.contains('/'),
                generated_set: false,
                generated: false,
                text_set: false,
                text: AttributeText::Auto,
                eol_set: false,
                eol: AttributeEol::None,
            };
            while position < line.len() {
                let token = next_token(line, &mut position);
                if token.is_empty() {
                    break;
                }
                match token {
                    "gen" => {
                        rule.generated_set = true;
                        rule.generated = true;
                    }
                    "-gen" => {
                        rule.generated_set = true;
                        rule.generated = false;
                    }
                    "txt" => {
                        rule.text_set = true;
                        rule.text = AttributeText::Text;
                    }
                    "bin" => {
                        rule.text_set = true;
                        rule.text = AttributeText::Binary;
                    }
                    "-txt" | "-bin" => {
                        rule.text_set = true;
                        rule.text = AttributeText::Auto;
                    }
                    "-eol" => {
                        rule.eol_set = true;
                        rule.eol = AttributeEol::None;
                    }
                    value if value.starts_with("eol:") => {
                        let value = &value[4..];
                        if matches!(value, "lf" | "crlf" | "cr") {
                            rule.eol_set = true;
                            rule.eol = parse_eol(value);
                        }
                    }
                    _ => {}
                }
            }
            rules.rules.push(rule);
        }
        rules
    }

    pub fn lookup(&self, path: &str) -> PathAttributes {
        let mut attributes = PathAttributes::default();
        for rule in &self.rules {
            if !rule_matches(&rule.pattern, rule.has_slash, path) {
                continue;
            }
            if rule.generated_set {
                attributes.generated = rule.generated;
            }
            if rule.text_set {
                attributes.text = rule.text;
            }
            if rule.eol_set {
                attributes.eol = rule.eol;
            }
        }
        attributes
    }

    pub fn changed_since(&self, cache_written_ms: i64) -> bool {
        if cache_written_ms <= 0 {
            return true;
        }
        if self.mtime_ns == 0 {
            return false;
        }
        self.mtime_ns > cache_written_ms * 1_000_000
    }
}

pub fn normalize_eol(data: &[u8], eol: AttributeEol) -> Vec<u8> {
    let (first, second) = match eol {
        AttributeEol::None => return data.to_vec(),
        AttributeEol::Lf => (b'\n', 0),
        AttributeEol::Crlf => (b'\r', b'\n'),
        AttributeEol::Cr => (b'\r', 0),
    };
    let mut output = Vec::with_capacity(data.len());
    let mut index = 0;
    while index < data.len() {
        let byte = data[index];
        if byte == b'\r' {
            if index + 1 < data.len() && data[index + 1] == b'\n' {
                index += 1;
            }
            output.push(first);
            if second != 0 {
                output.push(second);
            }
        } else if byte == b'\n' {
            output.push(first);
            if second != 0 {
                output.push(second);
            }
        } else {
            output.push(byte);
        }
        index += 1;
    }
    output
}

pub fn attributes_of<'a>(rules: &'a AttributeRules, path: &[u8]) -> PathAttributes {
    rules.lookup(&String::from_utf8_lossy(path))
}