navid/veins / bc0b02d957b7af60232a5b91bf4caefba5dfba19c68970ec43e5c39830934f19 / veinsrs/src/cli/worktree_cmd.rs

worktree_cmd.rs

← veinsrs/src/cli · 23983 bytes · raw · download

use std::collections::HashSet;
use std::fs;
use std::path::Path;

use crate::core;
use crate::error::{Error, Result};
use crate::identity;
use crate::object::commit;
use crate::object::path::valid_path;
use crate::object::tree::{self, KIND_SUBTREE, TreeEntry};
use crate::object::{TYPE_COMMIT, TYPE_TREE};
use crate::store::Txn;
use crate::store::graph;
use crate::store::layout;
use crate::store::ops;
use crate::store::reader::Store;
use crate::worktree::pathspec;
use crate::worktree::snapshot;

use super::output;

pub fn remove(arguments: &[String]) -> Result<u8> {
    let mut delete_mode = false;
    let mut operands = Vec::new();
    let mut end_flags = false;
    for argument in arguments {
        if !end_flags && argument == "--" {
            end_flags = true;
        } else if !end_flags && argument == "-delete" {
            delete_mode = true;
        } else if !end_flags && core::is_flag(argument) {
            return Err(Error::new(format!("unknown flag: {argument}")));
        } else {
            operands.push(argument.clone());
        }
    }
    if operands.is_empty() {
        return Err(Error::new("rm requires at least one path"));
    }
    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;
    snapshot::run(&root)?;
    let normalized = normalize_operands(&root, &operands)?;
    run_removal(&root, &normalized, delete_mode)
}

fn normalize_operands(root: &Path, operands: &[String]) -> Result<Vec<String>> {
    let cwd = pathspec::cwd_relative(root)
        .ok_or_else(|| Error::new("cannot determine current directory"))?;
    let mut normalized = Vec::new();
    for argument in operands {
        let Some(normalized_path) = pathspec::pathspec_normalize(root, &cwd, argument) else {
            return Err(Error::new(format!(
                "path is outside the repository: {argument}"
            )));
        };
        if normalized_path.is_empty() || !valid_path(normalized_path.as_bytes()) {
            return Err(Error::new(format!("invalid path: {argument}")));
        }
        normalized.push(normalized_path);
    }
    Ok(normalized)
}

fn starts_with_child(path: &[u8], parent: &[u8]) -> bool {
    path.len() > parent.len() && path.starts_with(parent) && path[parent.len()] == b'/'
}

fn literal_matches(operand: &[u8], path: &[u8]) -> bool {
    path == operand || starts_with_child(path, operand)
}

fn glob_matches(operand: &str, path: &[u8]) -> bool {
    let text = String::from_utf8_lossy(path);
    if core::glob_match(operand, &text) {
        return true;
    }
    for (index, byte) in path.iter().enumerate() {
        if *byte == b'/' && core::glob_match(operand, &String::from_utf8_lossy(&path[..index])) {
            return true;
        }
    }
    false
}

fn operand_matches(operand: &str, path: &[u8]) -> bool {
    if operand.contains('*') || operand.contains('?') {
        glob_matches(operand, path)
    } else {
        literal_matches(operand.as_bytes(), path)
    }
}

fn subtree_affected(prefix: &[u8], removes: &[Vec<u8>]) -> bool {
    if prefix.is_empty() {
        return !removes.is_empty();
    }
    removes.iter().any(|remove| {
        prefix == remove.as_slice()
            || starts_with_child(remove, prefix)
            || starts_with_child(prefix, remove)
    })
}

fn path_removed(path: &[u8], removes: &[Vec<u8>]) -> bool {
    removes
        .iter()
        .any(|remove| path == remove.as_slice() || starts_with_child(path, remove))
}

fn empty_tree_id(txn: &mut Txn) -> Result<crate::object::id::Id> {
    Ok(txn.add_object(TYPE_TREE, tree::encode(&[])?))
}

fn filter_tree(
    txn: &mut Txn,
    store: &mut Store,
    tree_id: crate::object::id::Id,
    prefix: &[u8],
    removes: &[Vec<u8>],
    depth: usize,
) -> Result<Option<crate::object::id::Id>> {
    if depth > crate::object::MAX_TREE_DEPTH || !subtree_affected(prefix, removes) {
        return Ok(Some(tree_id));
    }
    let Some(body) = store.body(tree_id, TYPE_TREE)? else {
        return Ok(Some(tree_id));
    };
    let Ok(decoded) = tree::decode(&body) else {
        return Ok(Some(tree_id));
    };
    let mut entries = Vec::with_capacity(decoded.entries.len());
    for entry in decoded.entries {
        let full = crate::object::path::join(prefix, &entry.name);
        if path_removed(&full, removes) {
            continue;
        }
        if entry.kind == KIND_SUBTREE && subtree_affected(&full, removes) {
            if let Some(child) = filter_tree(txn, store, entry.target, &full, removes, depth + 1)? {
                entries.push(TreeEntry {
                    name: entry.name,
                    kind: entry.kind,
                    target: child,
                });
            }
        } else {
            entries.push(entry);
        }
    }
    if entries.is_empty() {
        return Ok(None);
    }
    Ok(Some(txn.add_object(TYPE_TREE, tree::encode(&entries)?)))
}

fn delete_paths(root: &Path, removes: &[Vec<u8>]) -> u8 {
    let mut failed = 0;
    for relative in removes {
        let path = root.join(core::path_from_bytes(relative));
        if fs::remove_file(&path).is_err() {
            failed += 1;
        } else {
            prune_parents(root, relative);
        }
    }
    if failed > 0 {
        output::warning_prefix();
        println!("could not delete {failed} path(s) from disk");
        1
    } else {
        0
    }
}

fn prune_parents(root: &Path, relative: &[u8]) {
    let mut end = relative.len();
    while let Some(position) = relative[..end].iter().rposition(|byte| *byte == b'/') {
        let path = root.join(core::path_from_bytes(&relative[..position]));
        if fs::remove_dir(&path).is_err() {
            break;
        }
        end = position;
    }
}

fn run_removal(root: &Path, operands: &[String], delete_mode: bool) -> Result<u8> {
    let mut store = Store::open(root)?;
    let mut txn = Txn::begin(root, &mut store)?;
    let working_copy =
        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;
    let loaded = graph::load_commit(&mut store, working_copy)?
        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;
    let entries = tree::flatten(&mut store, loaded.root_tree)?;
    let mut matched = vec![false; operands.len()];
    let mut removes = Vec::new();
    let mut seen = HashSet::new();
    for entry in &entries {
        for (index, operand) in operands.iter().enumerate() {
            if operand_matches(operand, &entry.path) {
                matched[index] = true;
                if seen.insert(entry.path.clone()) {
                    removes.push(entry.path.clone());
                }
            }
        }
    }
    for (index, value) in matched.iter().enumerate() {
        if !value {
            return Err(Error::new(format!(
                "path is not tracked: {}",
                operands[index]
            )));
        }
    }
    if !delete_mode {
        for relative in &removes {
            if !core::ignore_path_ignored(root, &String::from_utf8_lossy(relative)) {
                output::warning_prefix();
                println!(
                    "{} is not ignored and will be re-added on the next snapshot",
                    String::from_utf8_lossy(relative)
                );
            }
        }
    }
    let new_root = filter_tree(&mut txn, &mut store, loaded.root_tree, b"", &removes, 0)?
        .unwrap_or_else(|| empty_tree_id(&mut txn).unwrap_or_default());
    if new_root == loaded.root_tree {
        return Err(Error::new("no tracked paths to remove"));
    }
    let signature = identity::signature(root);
    let mut commit = loaded;
    commit.root_tree = new_root;
    commit.committer = signature;
    commit.renames_state = commit::RENAMES_RECORDED;
    commit.renames.clear();
    let encoded = commit::encode(&commit);
    let new_id = txn.add_object(TYPE_COMMIT, encoded);
    ops::remove_head(txn.view_mut(), working_copy);
    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);
    ops::set_workspace(txn.view_mut(), new_id);
    ops::rebuild_heads(txn.view_mut());
    txn.finish("rm")?;
    mark_native(root, new_id);
    let mut status = 0;
    if delete_mode {
        status = delete_paths(root, &removes);
    }
    output::info_prefix();
    println!("untracked {} path(s)", removes.len());
    Ok(status)
}

fn mark_native(root: &Path, id: crate::object::id::Id) {
    let path = layout::git_map_dir(root).join("native");
    core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes());
}

pub fn move_path(arguments: &[String]) -> Result<u8> {
    let mut operands = Vec::new();
    let mut end_flags = false;
    for argument in arguments {
        if !end_flags && argument == "--" {
            end_flags = true;
        } else if !end_flags && core::is_flag(argument) {
            return Err(Error::new(format!("unknown flag: {argument}")));
        } else {
            operands.push(argument.clone());
        }
    }
    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;
    snapshot::run(&root)?;
    if operands.len() != 2 {
        return Err(Error::new("mv requires a source and a destination"));
    }
    let cwd = pathspec::cwd_relative(&root)
        .ok_or_else(|| Error::new("cannot determine current directory"))?;
    let source = pathspec::pathspec_normalize(&root, &cwd, &operands[0])
        .ok_or_else(|| Error::new("invalid path"))?;
    let destination = pathspec::pathspec_normalize(&root, &cwd, &operands[1])
        .ok_or_else(|| Error::new("invalid path"))?;
    let source_path = root.join(core::path_from_bytes(source.as_bytes()));
    let destination_path = root.join(core::path_from_bytes(destination.as_bytes()));
    if core::stat_path(&source_path).is_none() {
        return Err(Error::new(format!("not a tracked path: {source}")));
    }
    if core::stat_path(&destination_path).is_some() {
        return Err(Error::new(format!(
            "destination already exists: {destination}"
        )));
    }
    if let Some((parent, _)) = destination.rsplit_once('/') {
        if !core::ensure_directory(&root.join(parent)) {
            return Err(Error::new("cannot create destination directory"));
        }
    }
    fs::rename(&source_path, &destination_path).map_err(|_| Error::new("cannot move path"))?;
    snapshot::run(&root)?;
    Ok(0)
}

pub fn exclude(arguments: &[String]) -> Result<u8> {
    let mut operands = Vec::new();
    let mut end_flags = false;
    for argument in arguments {
        if !end_flags && argument == "--" {
            end_flags = true;
        } else if !end_flags && core::is_flag(argument) {
            return Err(Error::new(format!("unknown flag: {argument}")));
        } else {
            operands.push(argument.clone());
        }
    }
    if operands.is_empty() {
        return Err(Error::new("ex requires at least one pattern"));
    }
    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;
    let cwd = pathspec::cwd_relative(&root)
        .ok_or_else(|| Error::new("cannot determine current directory"))?;
    let mut patterns = Vec::new();
    for argument in &operands {
        let Some(normalized) = pathspec::pathspec_normalize(&root, &cwd, argument) else {
            return Err(Error::new(format!(
                "pattern is outside the repository: {argument}"
            )));
        };
        if normalized.is_empty() || !valid_path(normalized.as_bytes()) {
            return Err(Error::new(format!(
                "{argument}\nnot a valid exclude pattern"
            )));
        }
        patterns.push(normalized);
    }
    let path = root.join(".vnexclude");
    let data = core::read_file_opt(&path, 0).unwrap_or_default();
    let text = String::from_utf8_lossy(&data);
    let mut additions = String::new();
    let mut added = Vec::new();
    for pattern in &patterns {
        if text.lines().any(|line| core::trim_str(line) == pattern)
            || added.iter().any(|value| value == pattern)
        {
            continue;
        }
        if additions.is_empty() && !data.is_empty() && !data.ends_with(b"\n") {
            additions.push('\n');
        }
        added.push(pattern.clone());
        additions.push_str(pattern);
        additions.push('\n');
    }
    if added.is_empty() {
        output::info_prefix();
        println!("no new exclude rules");
        return Ok(0);
    }
    if !core::append_file(&path, additions.as_bytes()) {
        return Err(Error::new("cannot write .vnexclude"));
    }
    output::info_prefix();
    println!("added {} exclude rule(s)", added.len());
    Ok(0)
}

pub fn edit(arguments: &[String]) -> Result<u8> {
    let mut paths = Vec::new();
    let mut end_flags = false;
    for argument in arguments {
        if !end_flags && argument == "--" {
            end_flags = true;
        } else if !end_flags && core::is_flag(argument) {
            return Err(Error::new(format!("unknown flag: {argument}")));
        } else {
            paths.push(argument.clone());
        }
    }
    if paths.is_empty() {
        paths.push(".".to_string());
    }
    let root =
        layout::discover(Path::new(".")).unwrap_or_else(|_| std::env::current_dir().unwrap());
    if !core::run_editor(&root, &paths, None) {
        return Err(Error::new("editor exited with an error"));
    }
    Ok(0)
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Attr {
    Gen,
    Txt,
    Bin,
    Lf,
    Crlf,
    Cr,
}

fn parse_attr(name: &str) -> Option<Attr> {
    match name {
        "gen" => Some(Attr::Gen),
        "txt" => Some(Attr::Txt),
        "bin" => Some(Attr::Bin),
        "lf" => Some(Attr::Lf),
        "crlf" => Some(Attr::Crlf),
        "cr" => Some(Attr::Cr),
        _ => None,
    }
}

fn canonical(attr: Attr) -> &'static str {
    match attr {
        Attr::Gen => "gen",
        Attr::Txt => "txt",
        Attr::Bin => "bin",
        Attr::Lf => "eol:lf",
        Attr::Crlf => "eol:crlf",
        Attr::Cr => "eol:cr",
    }
}

fn is_attr_token(token: &str, attr: Attr) -> bool {
    match attr {
        Attr::Gen => token == "gen" || token == "-gen",
        Attr::Txt => token == "txt" || token == "-txt",
        Attr::Bin => token == "bin" || token == "-bin",
        Attr::Lf => token == "eol:lf",
        Attr::Crlf => token == "eol:crlf",
        Attr::Cr => token == "eol:cr",
    }
}

fn clears_token(token: &str, attr: Attr) -> bool {
    match attr {
        Attr::Gen => is_attr_token(token, Attr::Gen),
        Attr::Txt | Attr::Bin => matches!(token, "txt" | "-txt" | "bin" | "-bin"),
        Attr::Lf | Attr::Crlf | Attr::Cr => {
            matches!(token, "eol:lf" | "eol:crlf" | "eol:cr" | "-eol")
        }
    }
}

struct Line {
    text: String,
    eol: String,
    is_rule: bool,
    pattern: String,
    attrs: Vec<String>,
}

fn tokenize(line: &str) -> Vec<String> {
    line.split(|character| character == ' ' || character == '\t')
        .filter(|value| !value.is_empty())
        .map(|value| value.to_string())
        .collect()
}

fn parse_lines(data: &str) -> Vec<Line> {
    let mut lines = Vec::new();
    let mut start = 0;
    while start < data.len() {
        let newline = data[start..].find('\n').map(|offset| start + offset);
        let mut line = Line {
            text: String::new(),
            eol: String::new(),
            is_rule: false,
            pattern: String::new(),
            attrs: Vec::new(),
        };
        match newline {
            None => {
                line.text = data[start..].to_string();
                start = data.len();
            }
            Some(position) => {
                let mut body = &data[start..position];
                if let Some(value) = body.strip_suffix('\r') {
                    body = value;
                    line.eol = "\r\n".to_string();
                } else {
                    line.eol = "\n".to_string();
                }
                line.text = body.to_string();
                start = position + 1;
            }
        }
        let trimmed = core::trim_str(&line.text);
        if !trimmed.is_empty() && !trimmed.starts_with('#') {
            let tokens = tokenize(trimmed);
            if !tokens.is_empty() {
                line.is_rule = true;
                line.pattern = tokens[0].clone();
                line.attrs = tokens[1..].to_vec();
            }
        }
        lines.push(line);
    }
    lines
}

fn canonical_line(line: &Line) -> String {
    let mut output = line.pattern.clone();
    for attr in &line.attrs {
        output.push(' ');
        output.push_str(attr);
    }
    output
}

fn serialize(lines: &[Line], removed: &[bool]) -> String {
    let kept: Vec<usize> = (0..lines.len())
        .filter(|index| !removed.get(*index).copied().unwrap_or(false))
        .collect();
    let mut output = String::new();
    for (position, index) in kept.iter().enumerate() {
        let line = &lines[*index];
        if line.is_rule {
            output.push_str(&canonical_line(line));
        } else {
            output.push_str(&line.text);
        }
        if position + 1 < kept.len() {
            output.push_str(if line.eol.is_empty() { "\n" } else { &line.eol });
        } else {
            output.push_str(&line.eol);
        }
    }
    if !output.is_empty() && !output.ends_with('\n') {
        output.push('\n');
    }
    output
}

fn collect_operands(arguments: &[String]) -> Result<Vec<String>> {
    let mut operands = Vec::new();
    let mut end_flags = false;
    for argument in arguments {
        if !end_flags && argument == "--" {
            end_flags = true;
        } else if !end_flags && core::is_flag(argument) {
            return Err(Error::new(format!("unknown flag: {argument}")));
        } else {
            operands.push(argument.clone());
        }
    }
    Ok(operands)
}

fn normalize_patterns(root: &Path, arguments: &[String]) -> Result<Vec<String>> {
    let cwd = pathspec::cwd_relative(root)
        .ok_or_else(|| Error::new("cannot determine current directory"))?;
    let mut patterns = Vec::new();
    for argument in arguments {
        let Some(normalized) = pathspec::pathspec_normalize(root, &cwd, argument) else {
            return Err(Error::new(format!(
                "{argument}\nnot a valid attribute pattern"
            )));
        };
        if normalized.is_empty()
            || !valid_path(normalized.as_bytes())
            || normalized.contains([' ', '\t', '\r', '\n'])
            || normalized.starts_with('#')
        {
            return Err(Error::new(format!(
                "{argument}\nnot a valid attribute pattern"
            )));
        }
        patterns.push(normalized);
    }
    Ok(patterns)
}

fn read_attribs(path: &Path) -> Result<String> {
    match core::read_file_opt(path, 0) {
        Some(data) => Ok(String::from_utf8_lossy(&data).into_owned()),
        None if path.exists() => Err(Error::new("cannot read .vnattribs")),
        None => Ok(String::new()),
    }
}

fn attr_set(attr: Attr, arguments: &[String]) -> Result<u8> {
    let operands = collect_operands(arguments)?;
    if operands.is_empty() {
        return Err(Error::new(format!(
            "attr {} requires at least one glob",
            canonical(attr)
        )));
    }
    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;
    let patterns = normalize_patterns(&root, &operands)?;
    let path = root.join(".vnattribs");
    let data = read_attribs(&path)?;
    let mut lines = parse_lines(&data);
    let mut changed = 0;
    for pattern in &patterns {
        let target = lines
            .iter()
            .enumerate()
            .filter(|(_, line)| line.is_rule && &line.pattern == pattern)
            .map(|(index, _)| index)
            .last();
        let mut attrs = Vec::new();
        if let Some(index) = target {
            for token in &lines[index].attrs {
                if !clears_token(token, attr) {
                    attrs.push(token.clone());
                }
            }
        }
        attrs.push(canonical(attr).to_string());
        if let Some(index) = target {
            if lines[index].attrs == attrs {
                continue;
            }
            lines[index].attrs = attrs;
        } else {
            if lines.last().is_some_and(|line| line.eol.is_empty()) {
                lines.last_mut().unwrap().eol = "\n".to_string();
            }
            lines.push(Line {
                text: String::new(),
                eol: "\n".to_string(),
                is_rule: true,
                pattern: pattern.clone(),
                attrs,
            });
        }
        changed += 1;
    }
    if changed == 0 {
        output::info_prefix();
        println!("no new attribute rules");
        return Ok(0);
    }
    if !core::write_atomic_name(&path, serialize(&lines, &[]).as_bytes()) {
        return Err(Error::new("cannot write .vnattribs"));
    }
    output::info_prefix();
    println!("updated {changed} attribute rule(s)");
    Ok(0)
}

fn attr_remove(arguments: &[String]) -> Result<u8> {
    let mut operands = collect_operands(arguments)?;
    if operands.len() < 2 {
        return Err(Error::new(
            "usage: vn attr rm <gen|txt|bin|lf|crlf|cr> <glob>...",
        ));
    }
    let Some(attr) = parse_attr(&operands[0]) else {
        return Err(Error::new(format!("unknown attribute: {}", operands[0])));
    };
    operands.remove(0);
    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;
    let patterns = normalize_patterns(&root, &operands)?;
    let path = root.join(".vnattribs");
    let data = read_attribs(&path)?;
    let mut lines = parse_lines(&data);
    let mut removed = vec![false; lines.len()];
    let mut changed = 0;
    for pattern in &patterns {
        for index in 0..lines.len() {
            if removed[index] || !lines[index].is_rule || &lines[index].pattern != pattern {
                continue;
            }
            let attrs: Vec<String> = lines[index]
                .attrs
                .iter()
                .filter(|token| !is_attr_token(token, attr))
                .cloned()
                .collect();
            if attrs.len() == lines[index].attrs.len() {
                continue;
            }
            if attrs.is_empty() {
                removed[index] = true;
            } else {
                lines[index].attrs = attrs;
            }
            changed += 1;
        }
    }
    if changed == 0 {
        output::info_prefix();
        println!("no matching attribute rules");
        return Ok(0);
    }
    if !core::write_atomic_name(&path, serialize(&lines, &removed).as_bytes()) {
        return Err(Error::new("cannot write .vnattribs"));
    }
    output::info_prefix();
    println!("removed {changed} attribute rule(s)");
    Ok(0)
}

fn attr_list(arguments: &[String]) -> Result<u8> {
    let operands = collect_operands(arguments)?;
    if !operands.is_empty() {
        return Err(Error::new("usage: vn attr ls"));
    }
    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;
    let data = read_attribs(&root.join(".vnattribs"))?;
    for line in parse_lines(&data) {
        if line.is_rule {
            println!("{}", canonical_line(&line));
        }
    }
    Ok(0)
}

pub fn attr(arguments: &[String]) -> Result<u8> {
    let Some(sub) = arguments.first() else {
        output::error_prefix();
        println!("attr requires a subcommand");
        println!("run 'vn help attr' for details");
        return Ok(1);
    };
    match sub.as_str() {
        "ls" => attr_list(&arguments[1..]),
        "rm" => attr_remove(&arguments[1..]),
        value => match parse_attr(value) {
            Some(attr) => attr_set(attr, &arguments[1..]),
            None => Err(Error::new(format!("unknown attr subcommand: {value}"))),
        },
    }
}