navid/veins / impl-rust / veins-rust/src/worktree/checkout.rs

checkout.rs

← veins-rust/src/worktree · 6788 bytes · raw · download

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

use rayon::prelude::*;

use crate::error::{Error, Result};
use crate::object::id::Id;
use crate::object::path::valid_checkout_path;
use crate::object::tree::{self, FlatEntry};
use crate::store::graph;
use crate::store::layout;
use crate::store::ops;
use crate::store::reader::Store;
use crate::store::Txn;
use crate::worktree::snapshot;

pub fn run(root: &Path, revision: &str) -> Result<()> {
    snapshot::run(root)?;

    let mut store = Store::open(root)?;
    let view = ops::current_view(root, &mut store)?
        .ok_or_else(|| Error::new("no operation state"))?;
    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 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 mut txn = Txn::begin(root, &mut store)?;
        if let Some(old_id) = working_copy {
            ops::remove_head(txn.view_mut(), old_id);
        }
        ops::set_workspace(txn.view_mut(), target);
        ops::rebuild_heads(txn.view_mut());
        txn.finish("checkout")?;
    }
    Ok(())
}

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

    let mut directories: Vec<Vec<u8>> = Vec::new();
    let mut files = Vec::new();
    for entry in &new_entries {
        if !valid_checkout_path(&entry.path) {
            return Err(Error::new(format!(
                "invalid path in checkout tree: {}",
                String::from_utf8_lossy(&entry.path)
            )));
        }
        let mut cursor = 0;
        while let Some(position) = entry.path[cursor..].iter().position(|byte| *byte == b'/') {
            let end = cursor + position;
            directories.push(entry.path[..end].to_vec());
            cursor = end + 1;
        }
        files.push(entry.clone());
    }

    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))?;

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

fn write_entry(store: &Store, root: &Path, entry: &FlatEntry) -> Result<()> {
    let data = graph::read_blob_loaded(store, entry.target)?
        .ok_or_else(|| Error::new("missing blob"))?;
    write_content(root, &entry.path, &data, entry.kind == tree::KIND_EXECUTABLE)
}

fn write_content(root: &Path, relative: &[u8], data: &[u8], executable: bool) -> Result<()> {
    if !valid_checkout_path(relative) {
        return Err(Error::new("invalid checkout path"));
    }
    ensure_safe_dirs(root, relative)?;
    let final_path = root.join(path_buf(relative));
    if let Ok(metadata) = fs::symlink_metadata(&final_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(&final_path)?;
        }
    }
    fs::write(&final_path, data)?;
    let mode = if executable { 0o755 } else { 0o644 };
    fs::set_permissions(&final_path, fs::Permissions::from_mode(mode))?;
    Ok(())
}

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;
        }
        if at_end {
            break;
        }
        let component = &relative[start..index];
        if component.is_empty() {
            return Err(Error::new("empty path component"));
        }
        current = current.join(path_buf(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 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;
        }
        let path = root.join(path_buf(&entry.path));
        if fs::symlink_metadata(&path).is_ok() {
            remove_any(&path)?;
            prune_empty_parents(root, &entry.path)?;
        }
    }
    Ok(())
}

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 parent = &relative[..position];
        let path = root.join(path_buf(parent));
        if fs::remove_dir(&path).is_err() {
            break;
        }
        end = position;
    }
    Ok(())
}

fn clear_stat_cache(root: &Path) -> Result<()> {
    let path = layout::working_copy_dir(root).join("stat-cache");
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
    }
}

fn path_buf(bytes: &[u8]) -> PathBuf {
    PathBuf::from(layout::os_string(bytes))
}