navid/veins / 30fe17c70c010a5e92632420896efee72e1759dbfafc31a68078b9daa1039935 / veinsrs/src/core.rs

core.rs

← veinsrs/src · 34714 bytes · raw · download

use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use crate::error::{Error, Result};
use crate::platform;

pub fn is_flag(argument: &str) -> bool {
    !argument.is_empty() && argument.starts_with('-')
}

pub fn trim_str(text: &str) -> &str {
    text.trim_matches(|character| {
        character == ' ' || character == '\t' || character == '\r' || character == '\n'
    })
}

pub fn trim_bytes(text: &[u8]) -> &[u8] {
    let mut start = 0;
    let mut end = text.len();
    while start < end && matches!(text[start], b' ' | b'\t' | b'\r' | b'\n') {
        start += 1;
    }
    while end > start && matches!(text[end - 1], b' ' | b'\t' | b'\r' | b'\n') {
        end -= 1;
    }
    &text[start..end]
}

pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {
    platform::path_from_bytes(bytes)
}

pub fn path_to_bytes(path: &Path) -> Vec<u8> {
    platform::path_to_bytes(path)
}

pub fn path_display(path: &Path) -> String {
    platform::path_display(path)
}

pub fn read_file_opt(path: &Path, maximum: u64) -> Option<Vec<u8>> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        let mut file = fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)
            .open(path)
            .ok()?;
        let metadata = file.metadata().ok()?;
        if !metadata.is_file() {
            return None;
        }
        if maximum != 0 && metadata.len() > maximum {
            return None;
        }
        let length = usize::try_from(metadata.len()).ok()?;
        if length == 0 {
            let mut data = Vec::new();
            file.read_to_end(&mut data).ok()?;
            return Some(data);
        }
        let mut data = vec![0u8; length];
        file.read_exact(&mut data).ok()?;
        Some(data)
    }
    #[cfg(not(unix))]
    {
        let metadata = fs::symlink_metadata(path).ok()?;
        if !metadata.is_file() {
            return None;
        }
        if maximum != 0 && metadata.len() > maximum {
            return None;
        }
        let mut file = fs::File::open(path).ok()?;
        let mut data = Vec::with_capacity(usize::try_from(metadata.len()).unwrap_or(0));
        file.read_to_end(&mut data).ok()?;
        Some(data)
    }
}

pub fn read_file_range(path: &Path, offset: u64, length: usize) -> Option<Vec<u8>> {
    use std::io::{Seek, SeekFrom};
    let mut file = fs::File::open(path).ok()?;
    file.seek(SeekFrom::Start(offset)).ok()?;
    let mut data = vec![0u8; length];
    let mut done = 0;
    while done < length {
        match file.read(&mut data[done..]) {
            Ok(0) => break,
            Ok(count) => done += count,
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(_) => return None,
        }
    }
    data.truncate(done);
    Some(data)
}

pub fn read_file(path: &Path, maximum: u64) -> Result<Vec<u8>> {
    read_file_opt(path, maximum).ok_or_else(|| Error::io(format!("cannot read {}", path.display())))
}

fn create_parent(path: &Path) -> bool {
    match path.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => fs::create_dir_all(parent).is_ok(),
        _ => true,
    }
}

pub fn write_file(path: &Path, data: &[u8]) -> bool {
    let mut options = fs::OpenOptions::new();
    options.write(true).create(true).truncate(true);
    let file = match options.open(path) {
        Ok(file) => Some(file),
        Err(_) => {
            if !create_parent(path) {
                return false;
            }
            options.open(path).ok()
        }
    };
    let Some(mut file) = file else {
        return false;
    };
    file.write_all(data).is_ok() && file.flush().is_ok()
}

pub fn append_file(path: &Path, data: &[u8]) -> bool {
    let mut options = fs::OpenOptions::new();
    options.create(true).append(true);
    let file = match options.open(path) {
        Ok(file) => Some(file),
        Err(_) => {
            if !create_parent(path) {
                return false;
            }
            options.open(path).ok()
        }
    };
    let Some(mut file) = file else {
        return false;
    };
    file.write_all(data).is_ok() && file.flush().is_ok()
}

fn sync_file(path: &Path) -> bool {
    platform::sync_file(path).is_ok()
}

fn sync_directory(path: &Path) {
    platform::sync_directory(path);
}

pub fn write_atomic(tmp_path: &Path, final_path: &Path, data: &[u8]) -> bool {
    if let Some(parent) = tmp_path.parent()
        && !parent.as_os_str().is_empty()
        && fs::create_dir_all(parent).is_err()
    {
        return false;
    }
    if let Some(parent) = final_path.parent()
        && !parent.as_os_str().is_empty()
        && fs::create_dir_all(parent).is_err()
    {
        return false;
    }
    if !write_file(tmp_path, data) {
        return false;
    }
    if !sync_file(tmp_path) {
        let _ = fs::remove_file(tmp_path);
        return false;
    }
    if fs::rename(tmp_path, final_path).is_err() {
        let _ = fs::remove_file(tmp_path);
        return false;
    }
    if let Some(parent) = final_path.parent() {
        sync_directory(parent);
    }
    true
}

pub fn write_atomic_name(final_path: &Path, data: &[u8]) -> bool {
    let parent = final_path.parent().unwrap_or_else(|| Path::new(""));
    let name = final_path
        .file_name()
        .map(|value| value.to_string_lossy().into_owned())
        .unwrap_or_default();
    let temporary = parent.join(format!(".{name}.tmp.{}", random_u64()));
    write_atomic(&temporary, final_path, data)
}

pub fn ensure_directory(path: &Path) -> bool {
    fs::create_dir_all(path).is_ok()
}

pub fn remove_file(path: &Path) -> bool {
    fs::remove_file(path).is_ok()
}

pub fn remove_tree(path: &Path) -> bool {
    fs::remove_dir_all(path).is_ok()
}

pub fn list_directory(path: &Path) -> Vec<Vec<u8>> {
    let mut names = Vec::new();
    let Ok(entries) = fs::read_dir(path) else {
        return names;
    };
    for entry in entries.flatten() {
        names.push(platform::os_string_to_bytes(entry.file_name()));
    }
    names
}

pub fn same_or_under(child: &Path, parent: &Path) -> bool {
    let Ok(child) = fs::canonicalize(child) else {
        return false;
    };
    let Ok(parent) = fs::canonicalize(parent) else {
        return false;
    };
    child.starts_with(parent)
}

pub fn basename_string(path: &Path) -> String {
    path.file_name()
        .map(|value| value.to_string_lossy().into_owned())
        .unwrap_or_default()
}

pub fn path_read_symlink(path: &Path) -> Option<Vec<u8>> {
    fs::read_link(path)
        .ok()
        .map(|target| platform::path_to_bytes(&target))
}

#[derive(Clone, Copy)]
pub struct StatInfo {
    pub kind: u8,
    pub executable: bool,
    pub size: u64,
    pub mtime_ns: u64,
    pub inode: u64,
}

pub fn stat_path(path: &Path) -> Option<StatInfo> {
    let metadata = fs::symlink_metadata(path).ok()?;
    let file_type = metadata.file_type();
    let kind = if file_type.is_symlink() {
        3
    } else if file_type.is_dir() {
        2
    } else if file_type.is_file() {
        1
    } else {
        return None;
    };
    Some(StatInfo {
        kind,
        executable: platform::executable(&metadata),
        size: metadata.len(),
        mtime_ns: platform::mtime_ns(&metadata),
        inode: platform::inode(&metadata),
    })
}

thread_local! {
    static REPO_CONFIG: std::cell::RefCell<Option<(PathBuf, Vec<u8>)>> =
        const { std::cell::RefCell::new(None) };
}

fn repo_config_data(root: &Path) -> Option<Vec<u8>> {
    let path = root.join(".veins").join("config");
    REPO_CONFIG.with(|slot| {
        let mut slot = slot.borrow_mut();
        if let Some((cached_path, data)) = slot.as_ref()
            && *cached_path == path
        {
            return Some(data.clone());
        }
        let data = read_file_opt(&path, 0)?;
        *slot = Some((path, data.clone()));
        Some(data)
    })
}

fn clear_repo_config_cache() {
    REPO_CONFIG.with(|slot| *slot.borrow_mut() = None);
}

pub fn repo_config_value(root: &Path, key: &str) -> Option<String> {
    let data = repo_config_data(root)?;
    let text = String::from_utf8_lossy(&data);
    for raw in text.lines() {
        let line = trim_str(raw);
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((name, value)) = line.split_once('=') else {
            continue;
        };
        if trim_str(name) == key {
            return Some(trim_str(value).to_string());
        }
    }
    None
}

fn config_without_key(data: &[u8], key: &str) -> Vec<u8> {
    let text = String::from_utf8_lossy(data);
    let mut output = String::new();
    let lines: Vec<&str> = text.lines().collect();
    for (index, raw) in lines.iter().enumerate() {
        let line = trim_str(raw);
        let mut skip = false;
        if !line.is_empty()
            && !line.starts_with('#')
            && let Some((name, _)) = line.split_once('=')
        {
            skip = trim_str(name) == key;
        }
        if !skip {
            output.push_str(raw);
            if index + 1 < lines.len() || text.ends_with('\n') {
                output.push('\n');
            }
        }
    }
    output.into_bytes()
}

pub fn repo_config_set(root: &Path, key: &str, value: &str) -> bool {
    let path = root.join(".veins").join("config");
    let mut output = repo_config_data(root)
        .map(|data| config_without_key(&data, key))
        .unwrap_or_default();
    output.extend_from_slice(key.as_bytes());
    output.extend_from_slice(b" = ");
    output.extend_from_slice(value.as_bytes());
    output.push(b'\n');
    let written = write_file(&path, &output);
    clear_repo_config_cache();
    written
}

pub fn repo_config_remove(root: &Path, key: &str) -> bool {
    let path = root.join(".veins").join("config");
    let output = repo_config_data(root)
        .map(|data| config_without_key(&data, key))
        .unwrap_or_default();
    let written = write_file(&path, &output);
    clear_repo_config_cache();
    written
}

pub fn repo_config_bool(root: &Path, key: &str, fallback: bool) -> bool {
    let Some(value) = repo_config_value(root, key) else {
        return fallback;
    };
    let value = value.split('#').next().unwrap_or("").trim();
    matches!(value, "true" | "1" | "yes" | "on")
}

fn user_config_path() -> Option<PathBuf> {
    let home = env::var_os("HOME")?;
    if home.is_empty() {
        return None;
    }
    Some(
        PathBuf::from(home)
            .join(".local")
            .join("config")
            .join("veins")
            .join("veins.toml"),
    )
}

fn unquote_toml(raw: &str) -> Option<String> {
    let raw = trim_str(raw);
    if raw.len() >= 2 {
        let first = raw.as_bytes()[0];
        let last = raw.as_bytes()[raw.len() - 1];
        if (first == b'\'' && last == b'\'') || (first == b'"' && last == b'"') {
            let quote = first;
            let mut output = String::new();
            let bytes = raw.as_bytes();
            let mut index = 1;
            while index + 1 < bytes.len() {
                let byte = bytes[index];
                if quote == b'"' && byte == b'\\' && index + 2 < bytes.len() {
                    match bytes[index + 1] {
                        b'"' => output.push('"'),
                        b'\\' => output.push('\\'),
                        b'n' => output.push('\n'),
                        b'r' => output.push('\r'),
                        b't' => output.push('\t'),
                        other => {
                            output.push('\\');
                            output.push(other as char);
                        }
                    }
                    index += 2;
                } else {
                    output.push(byte as char);
                    index += 1;
                }
            }
            return Some(output);
        }
    }
    if raw.is_empty() {
        return None;
    }
    Some(raw.to_string())
}

fn user_config_full_key(section: &str, key: &str) -> String {
    if section.is_empty() {
        key.to_string()
    } else {
        format!("{section}.{key}")
    }
}

fn user_config_entries_inner() -> BTreeMap<String, String> {
    let mut output = BTreeMap::new();
    let Some(path) = user_config_path() else {
        return output;
    };
    let Some(data) = read_file_opt(&path, 0) else {
        return output;
    };
    let text = String::from_utf8_lossy(&data);
    let mut section = String::new();
    for raw in text.lines() {
        let line = trim_str(raw);
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some(rest) = line.strip_prefix('[') {
            if let Some(close) = rest.find(']') {
                section = trim_str(&rest[..close]).to_string();
            }
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let value = value.split('#').next().unwrap_or("");
        if let Some(decoded) = unquote_toml(value) {
            output.insert(user_config_full_key(&section, trim_str(key)), decoded);
        }
    }
    output
}

pub fn user_config_entries() -> BTreeMap<String, String> {
    user_config_entries_inner()
}

pub fn user_config_value(key: &str) -> Option<String> {
    user_config_entries_inner().remove(key)
}

pub fn user_config_author_name() -> Option<String> {
    user_config_value("user.name")
}

pub fn user_config_author_email() -> Option<String> {
    user_config_value("user.email")
}

fn toml_quote(value: &str) -> String {
    let mut output = String::from("\"");
    for character in value.chars() {
        match character {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '\n' => output.push_str("\\n"),
            '\r' => output.push_str("\\r"),
            '\t' => output.push_str("\\t"),
            other => output.push(other),
        }
    }
    output.push('"');
    output
}

fn update_user_config(key: &str, value: Option<&str>) -> bool {
    if key.is_empty() {
        return false;
    }
    let Some(path) = user_config_path() else {
        return false;
    };
    let lines: Vec<String> = read_file_opt(&path, 0)
        .map(|data| {
            String::from_utf8_lossy(&data)
                .lines()
                .map(|line| line.to_string())
                .collect()
        })
        .unwrap_or_default();
    let mut output = Vec::new();
    let mut section = String::new();
    for line in lines {
        let trimmed = trim_str(&line);
        if let Some(rest) = trimmed.strip_prefix('[') {
            if let Some(close) = rest.find(']') {
                section = trim_str(&rest[..close]).to_string();
            }
            output.push(line);
            continue;
        }
        let Some((name, _)) = trimmed.split_once('=') else {
            output.push(line);
            continue;
        };
        if trimmed.is_empty() || trimmed.starts_with('#') {
            output.push(line);
            continue;
        }
        if user_config_full_key(&section, trim_str(name)) != key {
            output.push(line);
        }
    }
    if let Some(value) = value {
        output.insert(0, format!("{key} = {}", toml_quote(value)));
    } else {
        while output.last().is_some_and(|line| trim_str(line).is_empty()) {
            output.pop();
        }
    }
    let mut body = output.join("\n");
    if !output.is_empty() {
        body.push('\n');
    }
    write_file(&path, body.as_bytes())
}

pub fn user_config_set(key: &str, value: &str) -> bool {
    update_user_config(key, Some(value))
}

pub fn user_config_remove(key: &str) -> bool {
    update_user_config(key, None)
}

pub fn shell_quote_arg(value: &str) -> String {
    platform::shell_quote(value)
}

pub fn editor_command(root: &Path) -> String {
    for key in ["editor", "core.editor"] {
        if let Some(value) = user_config_value(key)
            && !value.is_empty()
        {
            return value;
        }
    }
    if let Some(value) = repo_config_value(root, "editor")
        && !value.is_empty()
    {
        return value;
    }
    for name in ["VN_EDITOR", "VISUAL", "EDITOR"] {
        if let Ok(value) = env::var(name)
            && !value.is_empty()
        {
            return value;
        }
    }
    platform::default_editor().to_string()
}

pub fn run_editor(root: &Path, paths: &[String], message_file: Option<&Path>) -> bool {
    let mut command = editor_command(root);
    for path in paths {
        command.push(' ');
        command.push_str(&shell_quote_arg(path));
    }
    if let Some(file) = message_file {
        command.push(' ');
        command.push_str(&shell_quote_arg(&path_display(file)));
    }
    platform::shell(&command)
        .status()
        .is_ok_and(|status| status.success())
}

pub fn stdin_is_terminal() -> bool {
    platform::stdin_is_terminal()
}

pub fn colors_enabled() -> bool {
    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ENABLED.get_or_init(|| {
        if env::var_os("NO_COLOR").is_some() {
            return false;
        }
        let forced =
            env::var_os("FORCE_COLOR").is_some_and(|value| !value.is_empty() && value != "0");
        if forced {
            return true;
        }
        if !stdout_is_terminal() {
            return false;
        }
        !env::var("TERM").is_ok_and(|term| term == "dumb")
    })
}

pub fn stdout_is_terminal() -> bool {
    platform::stdout_is_terminal()
}

pub fn stderr_is_terminal() -> bool {
    platform::stderr_is_terminal()
}

pub fn pager_command(root: &Path) -> String {
    for key in ["pager", "core.pager"] {
        if let Some(value) = user_config_value(key)
            && !value.is_empty()
        {
            return value;
        }
    }
    if let Some(value) = repo_config_value(root, "pager")
        && !value.is_empty()
    {
        return value;
    }
    for name in ["VN_PAGER", "PAGER"] {
        if let Ok(value) = env::var(name)
            && !value.is_empty()
        {
            return value;
        }
    }
    platform::default_pager().to_string()
}

pub fn run_pager(root: &Path, text: &str) -> bool {
    if !stdout_is_terminal() {
        print!("{text}");
        return true;
    }
    let file = env::temp_dir().join(format!("vn-pager-{}.txt", random_u64()));
    if !write_file(&file, text.as_bytes()) {
        print!("{text}");
        return false;
    }
    let command = format!(
        "{} {}",
        pager_command(root),
        shell_quote_arg(&path_display(&file))
    );
    let ok = platform::shell(&command)
        .status()
        .is_ok_and(|status| status.success());
    let _ = fs::remove_file(&file);
    if !ok {
        print!("{text}");
    }
    ok
}

pub fn current_bookmark_name(root: &Path) -> Option<String> {
    repo_config_value(root, "bookmark.current")
}

pub fn set_current_bookmark(root: &Path, name: &str) -> bool {
    if name.is_empty() {
        repo_config_remove(root, "bookmark.current")
    } else {
        repo_config_set(root, "bookmark.current", name)
    }
}

pub fn clear_current_bookmark(root: &Path) -> bool {
    repo_config_remove(root, "bookmark.current")
}

pub fn random_u64() -> u64 {
    let mut value = [0u8; 8];
    if let Ok(mut file) = fs::File::open("/dev/urandom")
        && file.read_exact(&mut value).is_ok()
    {
        return u64::from_le_bytes(value);
    }
    let mut hasher = blake3::Hasher::new();
    hasher.update(&crate::time::now_millis().to_le_bytes());
    hasher.update(&std::process::id().to_le_bytes());
    hasher.update(format!("{:?}", std::time::Instant::now()).as_bytes());
    let digest = hasher.finalize();
    let mut bytes = [0u8; 8];
    bytes.copy_from_slice(&digest.as_bytes()[..8]);
    u64::from_le_bytes(bytes)
}

impl From<std::ffi::OsString> for Error {
    fn from(value: std::ffi::OsString) -> Self {
        Error::new(value.to_string_lossy())
    }
}

#[derive(Clone, Default)]
pub struct IgnoreRule {
    pub pattern: String,
    pub negated: bool,
    pub dir_only: bool,
    pub anchored: bool,
    pub has_slash: bool,
    pub base: String,
}

#[derive(Clone, Default)]
pub struct IgnoreRules {
    pub items: Vec<IgnoreRule>,
}

pub fn ignore_empty() -> IgnoreRules {
    IgnoreRules::default()
}

fn ignore_add_line(rules: &mut IgnoreRules, base: &str, input: &str) {
    let line = trim_str(input);
    if line.is_empty() || line.starts_with('#') {
        return;
    }
    let mut negated = false;
    let mut start = 0;
    if line.starts_with('!') {
        negated = true;
        start = 1;
    }
    if start >= line.len() {
        return;
    }
    let bytes = line.as_bytes();
    let mut end = bytes.len();
    let mut dir_only = false;
    if bytes[end - 1] == b'/' {
        dir_only = true;
        end -= 1;
    }
    if start >= end {
        return;
    }
    let mut anchored = false;
    if bytes[start] == b'/' {
        anchored = true;
        start += 1;
    }
    if start >= end {
        return;
    }
    let pattern = &line[start..end];
    rules.items.push(IgnoreRule {
        pattern: pattern.to_string(),
        negated,
        dir_only,
        anchored,
        has_slash: pattern.contains('/'),
        base: base.to_string(),
    });
}

pub fn ignore_load_file(rules: &mut IgnoreRules, root: &Path, base: &str, name: &str) {
    let directory = if base.is_empty() {
        root.to_path_buf()
    } else {
        root.join(base)
    };
    let Some(data) = read_file_opt(&directory.join(name), 0) else {
        return;
    };
    let text = String::from_utf8_lossy(&data);
    for line in text.lines() {
        ignore_add_line(rules, base, line);
    }
}

pub fn ignore_load_root(rules: &mut IgnoreRules, root: &Path) {
    ignore_load_file(rules, root, "", ".vnexclude");
    ignore_load_file(rules, root, "", ".gitignore");
}

#[derive(Clone, Copy)]
struct GlobState {
    pi: usize,
    ti: usize,
}

/// LIFO of match states that keeps small searches off the heap.
struct GlobStack {
    inline: [GlobState; 128],
    spilled: Vec<GlobState>,
    length: usize,
}

impl GlobStack {
    fn new() -> Self {
        Self {
            inline: [GlobState { pi: 0, ti: 0 }; 128],
            spilled: Vec::new(),
            length: 0,
        }
    }

    fn push(&mut self, state: GlobState) {
        if self.length < self.inline.len() {
            self.inline[self.length] = state;
            self.length += 1;
        } else {
            self.spilled.push(state);
        }
    }

    fn pop(&mut self) -> Option<GlobState> {
        if let Some(state) = self.spilled.pop() {
            return Some(state);
        }
        if self.length == 0 {
            return None;
        }
        self.length -= 1;
        Some(self.inline[self.length])
    }
}

pub fn glob_match(pattern: &str, text: &str) -> bool {
    let pattern = pattern.as_bytes();
    let text = text.as_bytes();
    const MAX_WORK: usize = 1_000_000;
    fn push(stack: &mut GlobStack, work: &mut usize, state: GlobState) -> bool {
        if *work >= MAX_WORK {
            return false;
        }
        *work += 1;
        stack.push(state);
        true
    }
    let mut stack = GlobStack::new();
    let mut work = 0usize;
    if !push(&mut stack, &mut work, GlobState { pi: 0, ti: 0 }) {
        return false;
    }
    while let Some(state) = stack.pop() {
        let p = state.pi;
        let t = state.ti;
        if p >= pattern.len() {
            if t >= text.len() {
                return true;
            }
            continue;
        }
        let pc = pattern[p];
        if pc == b'*' {
            let double = p + 1 < pattern.len() && pattern[p + 1] == b'*';
            if double {
                let next = p + 2;
                if next < pattern.len() && pattern[next] == b'/' {
                    let after = next + 1;
                    let mut j = t;
                    loop {
                        if !push(&mut stack, &mut work, GlobState { pi: after, ti: j }) {
                            return false;
                        }
                        if j >= text.len() {
                            break;
                        }
                        if text[j] == b'/' {
                            j += 1;
                            continue;
                        }
                        j += 1;
                        while j < text.len() && text[j] != b'/' {
                            j += 1;
                        }
                    }
                } else {
                    let mut j = t;
                    loop {
                        if !push(&mut stack, &mut work, GlobState { pi: next, ti: j }) {
                            return false;
                        }
                        if j >= text.len() {
                            break;
                        }
                        j += 1;
                    }
                }
            } else {
                let mut j = t;
                loop {
                    if !push(&mut stack, &mut work, GlobState { pi: p + 1, ti: j }) {
                        return false;
                    }
                    if j >= text.len() || text[j] == b'/' {
                        break;
                    }
                    j += 1;
                }
            }
            continue;
        }
        if t >= text.len() {
            continue;
        }
        if pc == b'?' {
            if text[t] != b'/' {
                let _ = push(
                    &mut stack,
                    &mut work,
                    GlobState {
                        pi: p + 1,
                        ti: t + 1,
                    },
                );
            }
            continue;
        }
        if pc == text[t] {
            let _ = push(
                &mut stack,
                &mut work,
                GlobState {
                    pi: p + 1,
                    ti: t + 1,
                },
            );
        }
    }
    false
}

fn relative_to<'a>(base: &str, path: &'a str) -> Option<&'a str> {
    if base.is_empty() {
        return Some(path);
    }
    if path.len() <= base.len() || !path.starts_with(base) {
        return None;
    }
    if path.as_bytes()[base.len()] != b'/' {
        return None;
    }
    Some(&path[base.len() + 1..])
}

fn rule_matches(rule: &IgnoreRule, path: &str, is_dir: bool) -> bool {
    let Some(relative) = relative_to(&rule.base, path) else {
        return false;
    };
    if relative.is_empty() || (rule.dir_only && !is_dir) {
        return false;
    }
    if !rule.has_slash && !rule.anchored {
        let mut start = 0;
        loop {
            let end = relative[start..]
                .find('/')
                .map(|offset| start + offset)
                .unwrap_or(relative.len());
            if glob_match(&rule.pattern, &relative[start..end]) {
                return true;
            }
            if end >= relative.len() {
                break;
            }
            start = end + 1;
        }
        return false;
    }
    glob_match(&rule.pattern, relative)
}

pub fn ignore_ignored(rules: &IgnoreRules, path: &str, is_dir: bool) -> bool {
    let mut ignored = false;
    for rule in &rules.items {
        if rule_matches(rule, path, is_dir) {
            ignored = !rule.negated;
        }
    }
    ignored
}

pub fn ignore_path_ignored(root: &Path, path: &str) -> bool {
    let mut rules = ignore_empty();
    ignore_load_root(&mut rules, root);
    for (index, byte) in path.bytes().enumerate() {
        if byte == b'/' {
            let base = &path[..index];
            ignore_load_file(&mut rules, root, base, ".vnexclude");
            ignore_load_file(&mut rules, root, base, ".gitignore");
        }
    }
    for (index, byte) in path.bytes().enumerate() {
        if byte == b'/' && ignore_ignored(&rules, &path[..index], true) {
            return true;
        }
    }
    ignore_ignored(&rules, path, false)
}

const PROGRESS_WIDTH: usize = 24;

fn progress_enabled() -> bool {
    for name in ["NO_PROGRESS", "VN_NO_PROGRESS"] {
        if env::var_os(name).is_some_and(|value| !value.is_empty() && value != "0") {
            return false;
        }
    }
    if env::var_os("VN_PROGRESS").is_some_and(|value| !value.is_empty() && value != "0") {
        return true;
    }
    if env::var("TERM").is_ok_and(|term| term == "dumb") {
        return false;
    }
    stderr_is_terminal()
}

fn styled_info_prefix(color: bool) -> &'static str {
    if color {
        "\r\x1b[2K\x1b[1m\x1b[36minfo\x1b[0m: "
    } else {
        "\r\x1b[2Kinfo: "
    }
}

struct ProgressState {
    total: usize,
    done: usize,
    last_done: usize,
    last_total: usize,
    last_draw: Option<std::time::Instant>,
    drawn: bool,
    finished: bool,
}

pub struct Progress {
    label: String,
    enabled: bool,
    state: std::sync::Mutex<ProgressState>,
}

impl Progress {
    pub fn new(label: impl Into<String>, total: usize) -> Self {
        Self {
            label: label.into(),
            enabled: progress_enabled(),
            state: std::sync::Mutex::new(ProgressState {
                total,
                done: 0,
                last_done: usize::MAX,
                last_total: usize::MAX,
                last_draw: None,
                drawn: false,
                finished: false,
            }),
        }
    }

    pub fn set_total(&self, total: usize) {
        if let Ok(mut state) = self.state.lock() {
            state.total = total;
            self.refresh(&mut state, true);
        }
    }

    pub fn update(&self, done: usize, force: bool) {
        if let Ok(mut state) = self.state.lock() {
            state.done = done;
            self.refresh(&mut state, force);
        }
    }

    pub fn advance(&self, amount: usize) {
        if let Ok(mut state) = self.state.lock() {
            state.done = state.done.saturating_add(amount);
            self.refresh(&mut state, false);
        }
    }

    pub fn finish(&self) {
        let Ok(mut state) = self.state.lock() else {
            return;
        };
        if !self.enabled || state.finished {
            return;
        }
        state.finished = true;
        if state.total > 0 {
            if state.done < state.total {
                state.done = state.total;
            }
            if !state.drawn || state.last_done != state.done || state.last_total != state.total {
                self.draw(&mut state);
            }
            eprintln!();
        } else if state.drawn {
            eprint!("\r\x1b[2K");
            let _ = std::io::stderr().flush();
        }
        state.drawn = false;
    }

    pub fn clear(&self) {
        let Ok(mut state) = self.state.lock() else {
            return;
        };
        if self.enabled && state.drawn {
            eprint!("\r\x1b[2K");
            let _ = std::io::stderr().flush();
        }
        state.drawn = false;
        state.finished = true;
    }

    fn refresh(&self, state: &mut ProgressState, force: bool) {
        if !self.enabled || state.finished {
            return;
        }
        let now = std::time::Instant::now();
        let complete = state.total > 0 && state.done >= state.total;
        if !force
            && !complete
            && state
                .last_draw
                .is_some_and(|last| now.duration_since(last) < std::time::Duration::from_millis(66))
        {
            return;
        }
        state.last_draw = Some(now);
        self.draw(state);
        state.drawn = true;
    }

    fn draw(&self, state: &mut ProgressState) {
        let color = colors_enabled();
        let mut line = String::with_capacity(128);
        line.push_str(styled_info_prefix(color));
        line.push_str(&self.label);
        line.push_str("  ");
        if state.total > 0 {
            let filled = std::cmp::min(
                PROGRESS_WIDTH,
                ((state.done as u128 * PROGRESS_WIDTH as u128) / state.total as u128) as usize,
            );
            line.push('[');
            if filled >= PROGRESS_WIDTH {
                if color {
                    line.push_str("\x1b[32m");
                }
                for _ in 0..PROGRESS_WIDTH {
                    line.push('=');
                }
            } else {
                let head = if filled == 0 { 1 } else { filled };
                if color {
                    line.push_str("\x1b[32m");
                }
                for _ in 0..head.saturating_sub(1) {
                    line.push('=');
                }
                line.push('>');
                if color {
                    line.push_str("\x1b[0m");
                }
                for _ in head..PROGRESS_WIDTH {
                    line.push(' ');
                }
            }
            if color {
                line.push_str("\x1b[0m");
            }
            line.push(']');
            if color {
                line.push_str(" \x1b[36m");
            } else {
                line.push(' ');
            }
            line.push_str(&(state.done * 100 / state.total).min(100).to_string());
            line.push('%');
            if color {
                line.push_str("\x1b[0m\x1b[2m");
            }
            line.push(' ');
            line.push_str(&state.done.to_string());
            line.push('/');
            line.push_str(&state.total.to_string());
            if color {
                line.push_str("\x1b[0m");
            }
        } else {
            const FRAMES: [char; 4] = ['|', '/', '-', '\\'];
            let frame = FRAMES[state.done % 4];
            if color {
                line.push_str("\x1b[36m");
                line.push(frame);
                line.push_str("\x1b[0m\x1b[2m");
            } else {
                line.push(frame);
            }
            line.push(' ');
            line.push_str(&state.done.to_string());
            if color {
                line.push_str("\x1b[0m");
            }
        }
        eprint!("{line}");
        let _ = std::io::stderr().flush();
        state.last_done = state.done;
        state.last_total = state.total;
    }
}

impl Drop for Progress {
    fn drop(&mut self) {
        let Ok(state) = self.state.lock() else {
            return;
        };
        if !self.enabled || !state.drawn || state.finished {
            return;
        }
        eprint!("\r\x1b[2K");
        let _ = std::io::stderr().flush();
    }
}