navid/veins / bc0b02d957b7af60232a5b91bf4caefba5dfba19c68970ec43e5c39830934f19 / veinsrs/src/worktree/checkout.rs

checkout.rs

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

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use rayon::prelude::*;

use crate::core;
use crate::error::{Error, Result};
use crate::object::conflict::{self, Conflict, ConflictValue};
use crate::object::id::Id;
use crate::object::path::valid_checkout_path;
use crate::object::tree::{self, FlatEntry};
use crate::store::Txn;
use crate::store::graph;
use crate::store::layout;
use crate::store::ops;
use crate::store::reader::Store;
use crate::worktree::attributes::{self, AttributeEol, AttributeRules, AttributeText};
use crate::worktree::snapshot;
use crate::worktree::stat_cache::{self, CacheEntry};

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

    let view = ops::current_view(root, &mut store)?
        .ok_or_else(|| Error::new("no operation state; import a repository first"))?;
    let target = graph::resolve_revision(&mut store, &view, revision)?
        .ok_or_else(|| Error::new(format!("unknown revision: {revision}")))?;
    let target_commit =
        graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?;

    let bookmark_checkout = !revision.is_empty()
        && revision != "@"
        && ops::find_bookmark(&view, revision.as_bytes()).is_some();
    let detach_bookmark = !revision.is_empty() && revision != "@" && !bookmark_checkout;

    let working_copy = ops::working_copy_id(&view);
    let old_root = match working_copy {
        Some(id) => graph::load_commit(&mut store, id)?.map(|commit| commit.root_tree),
        None => None,
    };

    if old_root != Some(target_commit.root_tree) {
        materialize(root, &mut store, old_root, target_commit.root_tree)?;
    }

    if working_copy != Some(target) {
        let already_empty_child = match working_copy {
            Some(id) => graph::load_commit(&mut store, id)?.is_some_and(|commit| {
                commit.parents.len() == 1
                    && commit.parents[0] == target
                    && commit.root_tree == target_commit.root_tree
                    && commit.message.is_empty()
            }),
            None => false,
        };
        if !already_empty_child {
            let mut txn = Txn::begin(root, &mut store)?;
            if let Some(old_id) = working_copy {
                ops::remove_head(txn.view_mut(), old_id);
            }
            let child = create_working_copy_commit(&mut txn, &mut store, target)?;
            ops::set_workspace(txn.view_mut(), child);
            ops::rebuild_heads(txn.view_mut());
            txn.finish("checkout")?;
        }
    }
    if bookmark_checkout {
        core::set_current_bookmark(root, revision);
    } else if detach_bookmark {
        core::clear_current_bookmark(root);
    }
    Ok(())
}

fn create_working_copy_commit(txn: &mut Txn, store: &mut Store, parent: Id) -> Result<Id> {
    let loaded = graph::load_commit(store, parent)?
        .ok_or_else(|| Error::new("cannot read parent commit"))?;
    let signature = crate::identity::signature(store.root());
    let commit = crate::object::commit::Commit {
        version: 1,
        parents: vec![parent],
        root_tree: loaded.root_tree,
        change_id: crate::identity::random_change_id(),
        author: signature.clone(),
        committer: signature,
        message: Vec::new(),
        renames_state: crate::object::commit::RENAMES_RECORDED,
        renames: Vec::new(),
        extra: Vec::new(),
    };
    Ok(txn.add_object(
        crate::object::TYPE_COMMIT,
        crate::object::commit::encode(&commit),
    ))
}

fn sidecar_suffixes() -> Vec<String> {
    let mut suffixes = vec![
        ".base".to_string(),
        ".ours".to_string(),
        ".theirs".to_string(),
    ];
    for number in 2..=64 {
        suffixes.push(format!(".base{number}"));
        suffixes.push(format!(".theirs{number}"));
    }
    suffixes
}

fn remove_any(path: &Path) -> Result<()> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.is_dir() && !metadata.file_type().is_symlink() {
        fs::remove_dir_all(path)?;
    } else {
        fs::remove_file(path)?;
    }
    Ok(())
}

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

fn remove_tracked_path(root: &Path, relative: &[u8]) -> Result<()> {
    let path = root.join(core::path_from_bytes(relative));
    match fs::symlink_metadata(&path) {
        Ok(_) => {
            remove_any(&path)?;
            prune_empty_parents(root, relative)?;
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => return Err(error.into()),
    }
    Ok(())
}

fn delete_sidecars(root: &Path, path: &[u8]) -> Result<()> {
    for suffix in sidecar_suffixes() {
        let mut full = path.to_vec();
        full.extend_from_slice(suffix.as_bytes());
        remove_tracked_path(root, &full)?;
    }
    Ok(())
}

fn has_symlink_component(root: &Path, relative: &[u8]) -> bool {
    let mut current = root.to_path_buf();
    let mut start = 0;
    for index in 0..relative.len() {
        if relative[index] != b'/' {
            continue;
        }
        if index == start {
            return true;
        }
        current = current.join(core::path_from_bytes(&relative[start..index]));
        if core::stat_path(&current).is_some_and(|info| info.kind == 3) {
            return true;
        }
        start = index + 1;
    }
    false
}

fn ensure_safe_dirs(root: &Path, relative: &[u8]) -> Result<()> {
    if relative.is_empty() {
        return Ok(());
    }
    let mut current = root.to_path_buf();
    let mut start = 0;
    for index in 0..=relative.len() {
        let at_end = index == relative.len();
        if !at_end && relative[index] != b'/' {
            continue;
        }
        let component = &relative[start..index];
        if component.is_empty() {
            return Err(Error::new("empty path component"));
        }
        if at_end {
            break;
        }
        current = current.join(core::path_from_bytes(component));
        match fs::symlink_metadata(&current) {
            Ok(metadata) => {
                if metadata.file_type().is_symlink() || !metadata.is_dir() {
                    return Err(Error::new("unsafe path component"));
                }
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                fs::create_dir(&current)?;
            }
            Err(error) => return Err(error.into()),
        }
        start = index + 1;
    }
    Ok(())
}

fn write_bytes(root: &Path, relative: &[u8], data: &[u8], executable: bool) -> Result<()> {
    if !valid_checkout_path(relative) || has_symlink_component(root, relative) {
        return Err(Error::new(format!(
            "invalid checkout path: {}",
            String::from_utf8_lossy(relative)
        )));
    }
    ensure_safe_dirs(root, relative)?;
    let path = root.join(core::path_from_bytes(relative));
    if let Ok(metadata) = fs::symlink_metadata(&path) {
        if metadata.is_dir() && !metadata.file_type().is_symlink() {
            return Err(Error::new("checkout path collides with a directory"));
        }
        if metadata.file_type().is_symlink() {
            fs::remove_file(&path)?;
        }
    }
    if !core::write_file(&path, data) {
        return Err(Error::new("cannot write checkout file"));
    }
    let mode = if executable { 0o755 } else { 0o644 };
    fs::set_permissions(&path, fs::Permissions::from_mode(mode))?;
    Ok(())
}

fn write_symlink(root: &Path, relative: &[u8], target: &[u8]) -> Result<()> {
    if !valid_checkout_path(relative) || has_symlink_component(root, relative) {
        return Err(Error::new("invalid checkout path"));
    }
    ensure_safe_dirs(root, relative)?;
    let path = root.join(core::path_from_bytes(relative));
    if let Ok(metadata) = fs::symlink_metadata(&path) {
        if metadata.is_dir() && !metadata.file_type().is_symlink() {
            return Err(Error::new("checkout path collides with a directory"));
        }
        remove_any(&path)?;
    }
    std::os::unix::fs::symlink(core::path_from_bytes(target), &path)?;
    Ok(())
}

fn write_entry(
    store: &Store,
    root: &Path,
    entry: &FlatEntry,
    attributes: &AttributeRules,
) -> Result<()> {
    let data =
        graph::read_blob_loaded(store, entry.target)?.ok_or_else(|| Error::new("missing blob"))?;
    if entry.kind == tree::KIND_SYMLINK {
        return write_symlink(root, &entry.path, &data);
    }
    let path_attributes = attributes.lookup(&String::from_utf8_lossy(&entry.path));
    if path_attributes.eol != AttributeEol::None && path_attributes.text != AttributeText::Binary {
        let normalized = attributes::normalize_eol(&data, path_attributes.eol);
        write_bytes(
            root,
            &entry.path,
            &normalized,
            entry.kind == tree::KIND_EXECUTABLE,
        )
    } else {
        write_bytes(
            root,
            &entry.path,
            &data,
            entry.kind == tree::KIND_EXECUTABLE,
        )
    }
}

fn delete_stale(root: &Path, old_entries: &[FlatEntry], new_entries: &[FlatEntry]) -> Result<()> {
    for entry in old_entries {
        if entry.kind == tree::KIND_SUBMODULE {
            continue;
        }
        if tree::find_flat(new_entries, &entry.path).is_some() {
            continue;
        }
        remove_tracked_path(root, &entry.path)?;
        if entry.kind == tree::KIND_CONFLICT {
            delete_sidecars(root, &entry.path)?;
        }
    }
    Ok(())
}

fn load_conflict(store: &mut Store, id: Id) -> Result<Option<Conflict>> {
    let Some(body) = store.body(id, crate::object::TYPE_CONFLICT)? else {
        return Ok(None);
    };
    Ok(Some(conflict::decode(&body)?))
}

fn write_tree_side(
    store: &mut Store,
    root: &Path,
    tree_id: Id,
    prefix: &[u8],
    attributes: &AttributeRules,
) -> Result<()> {
    let entries = tree::flatten(store, tree_id)?;
    for entry in entries {
        if entry.kind == tree::KIND_CONFLICT || entry.kind == tree::KIND_SUBMODULE {
            continue;
        }
        let path = crate::object::path::join(prefix, &entry.path);
        write_entry(store, root, &FlatEntry { path, ..entry }, attributes)?;
    }
    Ok(())
}

fn materialize_value(
    store: &mut Store,
    root: &Path,
    path: &[u8],
    value: &ConflictValue,
    attributes: &AttributeRules,
) -> Result<()> {
    if value.kind == 0 {
        return remove_tracked_path(root, path);
    }
    let target = value
        .target
        .ok_or_else(|| Error::new("conflict value has no target"))?;
    if value.kind == tree::KIND_SUBTREE {
        remove_tracked_path(root, path)?;
        return write_tree_side(store, root, target, path, attributes);
    }
    write_entry(
        store,
        root,
        &FlatEntry {
            path: path.to_vec(),
            kind: value.kind,
            target,
        },
        attributes,
    )
}

fn materialize_conflict(
    store: &mut Store,
    root: &Path,
    path: &[u8],
    target: Id,
    attributes: &AttributeRules,
) -> Result<()> {
    let conflict =
        load_conflict(store, target)?.ok_or_else(|| Error::new("cannot read conflict value"))?;
    for (index, value) in conflict.removes.iter().enumerate() {
        let suffix = if index == 0 {
            ".base".to_string()
        } else {
            format!(".base{}", index + 1)
        };
        let mut full = path.to_vec();
        full.extend_from_slice(suffix.as_bytes());
        materialize_value(store, root, &full, value, attributes)?;
    }
    for (index, value) in conflict.adds.iter().enumerate() {
        let suffix = match index {
            0 => ".ours".to_string(),
            1 => ".theirs".to_string(),
            _ => format!(".theirs{}", index + 1),
        };
        let mut full = path.to_vec();
        full.extend_from_slice(suffix.as_bytes());
        materialize_value(store, root, &full, value, attributes)?;
    }
    if let Some(first) = conflict.adds.first() {
        materialize_value(store, root, path, first, attributes)?;
    } else {
        remove_tracked_path(root, path)?;
    }
    Ok(())
}

fn save_checkout_cache(root: &Path, entries: &[FlatEntry]) -> Result<()> {
    let now_ms = crate::time::now_millis();
    let mut cache = Vec::new();
    for entry in entries {
        if !matches!(
            entry.kind,
            tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK
        ) {
            continue;
        }
        let Some(info) = core::stat_path(&root.join(core::path_from_bytes(&entry.path))) else {
            continue;
        };
        cache.push(CacheEntry {
            path: entry.path.clone(),
            size: info.size,
            mtime_ns: info.mtime_ns,
            inode: info.inode,
            kind: info.kind,
            executable: info.executable,
            target: entry.target,
            trusted: true,
        });
    }
    stat_cache::save(root, &mut cache, now_ms)
}

pub fn materialize(
    root: &Path,
    store: &mut Store,
    old_root: Option<Id>,
    new_root: Id,
) -> Result<()> {
    if old_root == Some(new_root) {
        return Ok(());
    }
    let old_entries = match old_root {
        Some(id) => tree::flatten(store, id)?,
        None => Vec::new(),
    };
    let attributes = AttributeRules::load(root);
    let new_entries = tree::flatten(store, new_root)?;

    let mut directories: Vec<Vec<u8>> = Vec::new();
    let mut files: Vec<FlatEntry> = Vec::new();
    let mut conflicts: Vec<FlatEntry> = Vec::new();
    for entry in &new_entries {
        if !valid_checkout_path(&entry.path) {
            return Err(Error::new(format!(
                "checkout tree validation failed at: {}",
                String::from_utf8_lossy(&entry.path)
            )));
        }
        let mut start = 0;
        for index in 0..entry.path.len() {
            if entry.path[index] == b'/' {
                directories.push(entry.path[start..index].to_vec());
                start = index + 1;
            }
        }
        match entry.kind {
            tree::KIND_CONFLICT => conflicts.push(entry.clone()),
            tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => {
                files.push(entry.clone())
            }
            _ => {}
        }
    }

    let suffixes = sidecar_suffixes();
    for conflict in &conflicts {
        for suffix in &suffixes {
            let mut full = conflict.path.clone();
            full.extend_from_slice(suffix.as_bytes());
            if tree::find_flat(&old_entries, &full).is_some() {
                return Err(Error::new(format!(
                    "conflict sidecar would overwrite a tracked path: {}",
                    String::from_utf8_lossy(&full)
                )));
            }
        }
    }

    for entry in &old_entries {
        if entry.kind == tree::KIND_CONFLICT {
            delete_sidecars(root, &entry.path)?;
        }
    }

    delete_stale(root, &old_entries, &new_entries)?;
    for directory in &directories {
        ensure_safe_dirs(root, directory)?;
    }
    ensure_safe_dirs(root, b"")?;

    store.preload()?;
    files
        .par_iter()
        .try_for_each(|entry| write_entry(store, root, entry, &attributes))?;
    for conflict in &conflicts {
        materialize_conflict(store, root, &conflict.path, conflict.target, &attributes)?;
    }

    save_checkout_cache(root, &new_entries)?;
    println!("info: checked out {} files", files.len());
    Ok(())
}

pub fn materialize_optional(
    root: &Path,
    store: &mut Store,
    old_root: Option<Id>,
    new_root: Option<Id>,
) -> Result<()> {
    match new_root {
        Some(new_root) => materialize(root, store, old_root, new_root),
        None => {
            let old_entries = match old_root {
                Some(id) => tree::flatten(store, id)?,
                None => Vec::new(),
            };
            delete_stale(root, &old_entries, &[])?;
            clear_stat_cache(root);
            Ok(())
        }
    }
}

pub fn clear_stat_cache(root: &Path) {
    let _ = fs::remove_file(layout::working_copy_dir(root).join("stat-cache"));
}

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