navid/veins / 83508482911f348af86cb892949a35bdce0d6b2f949b4a0faab7cba9a499fb82 / veinsrs/src/worktree/snapshot.rs

snapshot.rs

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

use std::fs;
use std::path::{Path, PathBuf};

use rayon::prelude::*;

use crate::core::{self, IgnoreRules};
use crate::error::{Error, Result};
use crate::identity;
use crate::object::blob;
use crate::object::commit::{self, Commit, Rename};
use crate::object::id::Id;
use crate::object::path;
use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_SUBTREE, TreeEntry};
use crate::object::{TYPE_COMMIT, TYPE_TREE};
use crate::store::Txn;
use crate::store::graph;
use crate::store::ops;
use crate::store::reader::Store;
use crate::store::writer::Writer;
use crate::time;
use crate::worktree::attributes::{self, AttributeEol, AttributeRules, AttributeText};
use crate::worktree::stat_cache::{self, Cache, CacheEntry};

pub fn run(root: &Path) -> Result<bool> {
    let mut store = Store::open(root)?;
    run_with(root, &mut store)
}

fn name_ends_with(name: &[u8], suffix: &[u8]) -> bool {
    name.len() >= suffix.len() && &name[name.len() - suffix.len()..] == suffix
}

fn sidecar_base(name: &[u8]) -> Option<Vec<u8>> {
    if name_ends_with(name, b".base") && name.len() > 5 {
        return Some(name[..name.len() - 5].to_vec());
    }
    if name_ends_with(name, b".ours") && name.len() > 5 {
        return Some(name[..name.len() - 5].to_vec());
    }
    if name_ends_with(name, b".theirs") && name.len() > 7 {
        return Some(name[..name.len() - 7].to_vec());
    }
    let mut digits = 0;
    while digits < name.len() && name[name.len() - 1 - digits].is_ascii_digit() {
        digits += 1;
    }
    if digits > 0 {
        let stem = &name[..name.len() - digits];
        if stem.len() > 5 && name_ends_with(stem, b".base") {
            return Some(stem[..stem.len() - 5].to_vec());
        }
        if stem.len() > 7 && name_ends_with(stem, b".theirs") {
            return Some(stem[..stem.len() - 7].to_vec());
        }
    }
    None
}

fn join_rel(base: &[u8], name: &[u8]) -> Vec<u8> {
    path::join(base, name)
}

struct BuildState {
    failed: bool,
}

enum PlanKind {
    Conflict,
    Directory,
    Symlink,
    File,
}

struct Plan {
    kind: PlanKind,
    name: Vec<u8>,
    rel: Vec<u8>,
    path: PathBuf,
    info: core::StatInfo,
    target: Option<Id>,
    child_old: Option<Id>,
    executable: bool,
    needs_read: bool,
    trusted: bool,
}

fn build_dir(
    txn: &mut Txn,
    store: &mut Store,
    root: &Path,
    base: &[u8],
    old_tree_id: Option<Id>,
    base_rules: &IgnoreRules,
    attributes: &AttributeRules,
    cache_valid: bool,
    cache: &Cache,
    new_cache: &mut Vec<CacheEntry>,
    now_ms: i64,
    state: &mut BuildState,
    depth: usize,
) -> Result<Option<Id>> {
    if depth > crate::object::MAX_TREE_DEPTH {
        state.failed = true;
        return Ok(None);
    }

    let mut local = base_rules.clone();
    let base_text = String::from_utf8_lossy(base);
    core::ignore_load_file(&mut local, root, &base_text, ".vnexclude");
    core::ignore_load_file(&mut local, root, &base_text, ".gitignore");

    let old_tree = match old_tree_id {
        Some(id) => {
            let body = store.body(id, TYPE_TREE)?.ok_or_else(|| {
                Error::new(format!(
                    "missing tree {} at {}",
                    id.to_hex(),
                    String::from_utf8_lossy(base)
                ))
            })?;
            match tree::decode(&body).ok() {
                Some(tree) => Some(tree),
                None => {
                    state.failed = true;
                    return Ok(None);
                }
            }
        }
        None => None,
    };

    let directory = if base.is_empty() {
        root.to_path_buf()
    } else {
        root.join(core::path_from_bytes(base))
    };
    if !directory.is_dir() {
        state.failed = true;
        return Ok(None);
    }

    let mut names = core::list_directory(&directory);
    names.sort();

    let infos: Vec<Option<core::StatInfo>> = if names.len() >= 256 {
        names
            .par_iter()
            .map(|name| core::stat_path(&directory.join(core::path_from_bytes(name))))
            .collect()
    } else {
        names
            .iter()
            .map(|name| core::stat_path(&directory.join(core::path_from_bytes(name))))
            .collect()
    };

    let mut plans: Vec<Plan> = Vec::with_capacity(names.len());
    for (index, name) in names.iter().enumerate() {
        if name == b".veins" || name == b".git" {
            continue;
        }
        let Some(info) = infos[index] else {
            continue;
        };
        if let Some(tree) = &old_tree
            && let Some(sidecar) = sidecar_base(name)
        {
            if let Some(found) = tree::find_entry(tree, &sidecar) {
                if tree.entries[found].kind == KIND_CONFLICT {
                    continue;
                }
            }
        }
        let relative = join_rel(base, name);
        let relative_text = String::from_utf8_lossy(&relative);
        let is_dir = info.kind == 2;
        let ignored = core::ignore_ignored(&local, &relative_text, is_dir);
        let old_index = old_tree
            .as_ref()
            .and_then(|tree| tree::find_entry(tree, name));
        if let Some(found) = old_index
            && old_tree.as_ref().unwrap().entries[found].kind == KIND_CONFLICT
        {
            plans.push(Plan {
                kind: PlanKind::Conflict,
                name: name.clone(),
                rel: relative,
                path: directory.join(core::path_from_bytes(name)),
                info,
                target: Some(old_tree.as_ref().unwrap().entries[found].target),
                child_old: None,
                executable: false,
                needs_read: false,
                trusted: false,
            });
            continue;
        }
        if ignored && old_index.is_none() {
            continue;
        }
        let mut plan = Plan {
            kind: if is_dir {
                PlanKind::Directory
            } else if info.kind == 3 {
                PlanKind::Symlink
            } else {
                PlanKind::File
            },
            name: name.clone(),
            rel: relative,
            path: directory.join(core::path_from_bytes(name)),
            info,
            target: None,
            child_old: None,
            executable: info.executable,
            needs_read: false,
            trusted: false,
        };
        if is_dir {
            if let Some(found) = old_index {
                let entry = &old_tree.as_ref().unwrap().entries[found];
                if entry.kind == KIND_SUBTREE {
                    plan.child_old = Some(entry.target);
                }
            }
        } else if info.kind == 1 {
            if cache_valid
                && let Some(entry) = stat_cache::lookup(cache, &plan.rel)
                && stat_cache::matches(
                    entry,
                    &fs::symlink_metadata(&plan.path)?,
                    plan.executable,
                    now_ms,
                    cache.written_ms,
                )
            {
                plan.target = Some(entry.target);
                plan.trusted = entry.trusted;
            }
            plan.needs_read = plan.target.is_none();
        }
        plans.push(plan);
    }

    let jobs: Vec<usize> = plans
        .iter()
        .enumerate()
        .filter(|(_, plan)| matches!(plan.kind, PlanKind::File) && plan.needs_read)
        .map(|(index, _)| index)
        .collect();
    let job_bytes: u64 = jobs.iter().map(|index| plans[*index].info.size).sum();

    let built: Vec<Option<blob::BlobBuild>> = if job_bytes >= 1_000_000 {
        jobs.par_iter()
            .map(|index| read_build(&plans[*index].path, &plans[*index].rel, attributes))
            .collect()
    } else {
        jobs.iter()
            .map(|index| read_build(&plans[*index].path, &plans[*index].rel, attributes))
            .collect()
    };

    for (job, build) in jobs.iter().zip(built) {
        let Some(build) = build else {
            state.failed = true;
            return Ok(None);
        };
        for object in build.objects {
            txn.add_known(object.kind, object.id, object.body);
        }
        plans[*job].target = Some(build.root);
    }

    let mut entries = Vec::with_capacity(plans.len());
    for plan in plans {
        match plan.kind {
            PlanKind::Conflict => {
                if let Some(target) = plan.target {
                    entries.push(TreeEntry {
                        name: plan.name,
                        kind: KIND_CONFLICT,
                        target,
                    });
                }
            }
            PlanKind::Directory => {
                let child = build_dir(
                    txn,
                    store,
                    root,
                    &plan.rel,
                    plan.child_old,
                    &local,
                    attributes,
                    cache_valid,
                    cache,
                    new_cache,
                    now_ms,
                    state,
                    depth + 1,
                )?;
                if state.failed {
                    return Ok(None);
                }
                if let Some(child) = child {
                    entries.push(TreeEntry {
                        name: plan.name,
                        kind: KIND_SUBTREE,
                        target: child,
                    });
                }
            }
            PlanKind::Symlink => {
                let Some(target) = core::path_read_symlink(&plan.path) else {
                    state.failed = true;
                    return Ok(None);
                };
                let Some(build) = read_blob_from_bytes(txn, &target) else {
                    state.failed = true;
                    return Ok(None);
                };
                entries.push(TreeEntry {
                    name: plan.name,
                    kind: tree::KIND_SYMLINK,
                    target: build,
                });
                new_cache.push(CacheEntry {
                    path: plan.rel,
                    size: plan.info.size,
                    mtime_ns: plan.info.mtime_ns,
                    inode: plan.info.inode,
                    kind: plan.info.kind,
                    executable: false,
                    target: build,
                    trusted: false,
                });
            }
            PlanKind::File => {
                let Some(target) = plan.target else {
                    state.failed = true;
                    return Ok(None);
                };
                new_cache.push(CacheEntry {
                    path: plan.rel,
                    size: plan.info.size,
                    mtime_ns: plan.info.mtime_ns,
                    inode: plan.info.inode,
                    kind: plan.info.kind,
                    executable: plan.executable,
                    target,
                    trusted: plan.trusted,
                });
                entries.push(TreeEntry {
                    name: plan.name,
                    kind: if plan.executable {
                        tree::KIND_EXECUTABLE
                    } else {
                        tree::KIND_FILE
                    },
                    target,
                });
            }
        }
    }

    if entries.is_empty() {
        return Ok(None);
    }
    Ok(Some(txn.add_object(TYPE_TREE, tree::encode(&entries)?)))
}

fn read_build(
    path: &Path,
    relative: &[u8],
    attributes: &AttributeRules,
) -> Option<blob::BlobBuild> {
    let data = core::read_file_opt(path, 0)?;
    let path_attributes = attributes.lookup(&String::from_utf8_lossy(relative));
    if path_attributes.eol != AttributeEol::None && path_attributes.text != AttributeText::Binary {
        Some(blob::build(&attributes::normalize_eol(
            &data,
            path_attributes.eol,
        )))
    } else {
        Some(blob::build(&data))
    }
}

fn read_blob_from_bytes(txn: &mut Txn, data: &[u8]) -> Option<Id> {
    let build = blob::build(data);
    for object in build.objects {
        txn.add_known(object.kind, object.id, object.body);
    }
    Some(build.root)
}

pub fn run_with(root: &Path, store: &mut Store) -> Result<bool> {
    let mut txn = Txn::begin(root, store)?;
    let working_copy = ops::working_copy_id(txn.view());
    let old_commit = match working_copy {
        Some(id) => Some(
            graph::load_commit(store, id)?
                .ok_or_else(|| Error::new("missing working-copy commit"))?,
        ),
        None => None,
    };
    let old_tree = old_commit.as_ref().map(|commit| commit.root_tree);
    let old_empty = match &old_commit {
        Some(commit) if commit.parents.len() == 1 => graph::load_commit(store, commit.parents[0])?
            .is_some_and(|parent| parent.root_tree == commit.root_tree),
        _ => false,
    };

    let mut rules = core::ignore_empty();
    core::ignore_load_root(&mut rules, root);
    let cache = stat_cache::load(root);
    let attributes = AttributeRules::load(root);
    let cache_valid = !attributes.changed_since(cache.written_ms);
    let now_ms = time::now_millis();
    let mut new_cache = Vec::new();
    let mut state = BuildState { failed: false };
    let built = build_dir(
        &mut txn,
        store,
        root,
        b"",
        old_tree,
        &rules,
        &attributes,
        cache_valid,
        &cache,
        &mut new_cache,
        now_ms,
        &mut state,
        0,
    )?;
    let new_root = match built {
        Some(id) => id,
        None if !state.failed => txn.add_object(TYPE_TREE, tree::encode(&[])?),
        None => return Err(Error::new("failed to build working-copy tree")),
    };

    if old_tree == Some(new_root) {
        stat_cache::save(root, &mut new_cache, now_ms)?;
        return Ok(false);
    }

    let committer = identity::signature(root);
    let (parents, change_id, message, author, extra) = match &old_commit {
        Some(commit) => (
            commit.parents.clone(),
            commit.change_id,
            commit.message.clone(),
            if old_empty {
                committer.clone()
            } else {
                commit.author.clone()
            },
            commit.extra.clone(),
        ),
        None => (
            Vec::new(),
            identity::random_change_id(),
            Vec::new(),
            committer.clone(),
            Vec::new(),
        ),
    };

    let mut renames = old_commit
        .as_ref()
        .map(|commit| commit.renames.clone())
        .unwrap_or_default();
    if let Some(old) = old_tree {
        let mut detected = detect_renames(store, txn.writer(), old, new_root)?;
        renames.append(&mut detected);
    }
    renames.sort_by(|left, right| {
        left.parent_index
            .cmp(&right.parent_index)
            .then_with(|| left.to_path.cmp(&right.to_path))
    });

    let new_commit = Commit {
        version: 1,
        parents,
        root_tree: new_root,
        change_id,
        author,
        committer,
        message,
        renames_state: commit::RENAMES_RECORDED,
        renames,
        extra,
    };
    let encoded = commit::encode(&new_commit);
    let commit_id = txn.add_object(TYPE_COMMIT, encoded);

    if let Some(old_id) = working_copy {
        ops::remove_head(txn.view_mut(), old_id);
        ops::move_bookmarks(txn.view_mut(), old_id, commit_id);
    }
    if let Some(current) = core::current_bookmark_name(root)
        && ops::find_bookmark(txn.view(), current.as_bytes()).is_some()
    {
        ops::set_bookmark_target(txn.view_mut(), current.as_bytes(), commit_id);
    }
    ops::set_workspace(txn.view_mut(), commit_id);
    ops::rebuild_heads(txn.view_mut());
    txn.finish("snapshot")?;
    store.refresh()?;
    mark_native(root, commit_id)?;
    stat_cache::save(root, &mut new_cache, now_ms)?;
    Ok(true)
}

fn flatten_any(
    store: &mut Store,
    writer: Option<&Writer>,
    tree_id: Id,
    prefix: &mut Vec<u8>,
    output: &mut Vec<FlatEntry>,
    depth: usize,
) -> Result<()> {
    if depth > crate::object::MAX_TREE_DEPTH {
        return Err(Error::new("tree nesting too deep"));
    }
    let body = match writer.and_then(|writer| writer.find_cached(TYPE_TREE, tree_id)) {
        Some(body) => body.to_vec(),
        None => store
            .body(tree_id, TYPE_TREE)?
            .ok_or_else(|| Error::new(format!("missing tree {}", tree_id.to_hex())))?,
    };
    let tree = tree::decode(&body)?;
    for entry in tree.entries {
        let old_length = prefix.len();
        if !prefix.is_empty() {
            prefix.push(b'/');
        }
        prefix.extend_from_slice(&entry.name);
        if entry.kind == KIND_SUBTREE {
            flatten_any(store, writer, entry.target, prefix, output, depth + 1)?;
        } else {
            output.push(FlatEntry {
                path: prefix.clone(),
                kind: entry.kind,
                target: entry.target,
            });
        }
        prefix.truncate(old_length);
    }
    Ok(())
}

fn detect_renames(
    store: &mut Store,
    writer: &Writer,
    old_tree: Id,
    new_tree: Id,
) -> Result<Vec<Rename>> {
    if let Some(found) = crate::merge::rename::detect(store, writer, old_tree, new_tree)? {
        return Ok(found);
    }
    let mut old_entries = Vec::new();
    flatten_any(store, None, old_tree, &mut Vec::new(), &mut old_entries, 0)?;
    let mut new_entries = Vec::new();
    flatten_any(
        store,
        Some(writer),
        new_tree,
        &mut Vec::new(),
        &mut new_entries,
        0,
    )?;
    old_entries.sort_by(|left, right| left.path.cmp(&right.path));
    new_entries.sort_by(|left, right| left.path.cmp(&right.path));
    let deleted: Vec<&FlatEntry> = old_entries
        .iter()
        .filter(|entry| tree::find_flat(&new_entries, &entry.path).is_none())
        .collect();
    let added: Vec<&FlatEntry> = new_entries
        .iter()
        .filter(|entry| tree::find_flat(&old_entries, &entry.path).is_none())
        .collect();
    let mut used_old = vec![false; deleted.len()];
    let mut used_new = vec![false; added.len()];
    let mut renames = Vec::new();
    for (old_index, old) in deleted.iter().enumerate() {
        if used_old[old_index] {
            continue;
        }
        for (new_index, new) in added.iter().enumerate() {
            if used_new[new_index] {
                continue;
            }
            if old.target == new.target {
                renames.push(Rename {
                    parent_index: 0,
                    kind: 0,
                    from_path: old.path.clone(),
                    to_path: new.path.clone(),
                });
                used_old[old_index] = true;
                used_new[new_index] = true;
                break;
            }
        }
    }
    Ok(renames)
}

fn mark_native(root: &Path, id: Id) -> Result<()> {
    let path = crate::store::layout::git_map_dir(root).join("native");
    if core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes()) {
        Ok(())
    } else {
        Err(Error::new("cannot write native marker"))
    }
}

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