navid/veins / 83508482911f348af86cb892949a35bdce0d6b2f949b4a0faab7cba9a499fb82 / veinsrs/src/store/graph.rs

graph.rs

← veinsrs/src/store · 12225 bytes · raw · download

use std::collections::HashSet;

use crate::error::{Error, Result};
use crate::object::blob::{self, BlobForm};
use crate::object::commit::{self, Commit};
use crate::object::id::{Id, is_hex_prefix, prefix_matches};
use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_MISSING, KIND_SUBTREE};
use crate::object::view::View;
use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT};
use crate::store::ops;
use crate::store::reader::Store;

pub fn load_commit(store: &mut Store, id: Id) -> Result<Option<Commit>> {
    let Some(body) = store.body(id, TYPE_COMMIT)? else {
        return Ok(None);
    };
    Ok(Some(commit::decode(&body)?))
}

pub fn has_changes(store: &mut Store, commit: &Commit) -> Result<bool> {
    if let Some(parent) = commit.parents.first() {
        let Some(parent) = load_commit(store, *parent)? else {
            return Ok(true);
        };
        return Ok(parent.root_tree != commit.root_tree);
    }
    Ok(!tree::flatten(store, commit.root_tree)?.is_empty())
}

pub fn collect_commits(store: &mut Store, start: &[Id]) -> Result<Vec<Id>> {
    let mut output = Vec::new();
    let mut stack = Vec::new();
    let mut seen = HashSet::new();
    for id in start {
        if seen.insert(*id) {
            stack.push(*id);
        }
    }
    while let Some(id) = stack.pop() {
        output.push(id);
        if let Some(commit) = load_commit(store, id)? {
            for parent in commit.parents {
                if seen.insert(parent) {
                    stack.push(parent);
                }
            }
        }
    }
    Ok(output)
}

pub struct LogNode {
    pub id: Id,
    pub seconds: i64,
    pub parents: Vec<Id>,
}

pub fn order_log_nodes(nodes: &[LogNode]) -> Vec<usize> {
    use std::cmp::Reverse;
    use std::collections::{BinaryHeap, HashMap};
    let mut index = HashMap::new();
    for (position, node) in nodes.iter().enumerate() {
        index.insert(node.id, position);
    }
    let mut unemitted = vec![0usize; nodes.len()];
    for node in nodes {
        for parent in &node.parents {
            if let Some(found) = index.get(parent) {
                unemitted[*found] += 1;
            }
        }
    }
    let mut ready = BinaryHeap::new();
    for (position, node) in nodes.iter().enumerate() {
        if unemitted[position] == 0 {
            ready.push((node.seconds, Reverse(position)));
        }
    }
    let mut emitted = vec![false; nodes.len()];
    let mut order = Vec::with_capacity(nodes.len());
    while let Some((_, Reverse(position))) = ready.pop() {
        if emitted[position] {
            continue;
        }
        emitted[position] = true;
        order.push(position);
        for parent in &nodes[position].parents {
            let Some(found) = index.get(parent).copied() else {
                continue;
            };
            if unemitted[found] > 0 {
                unemitted[found] -= 1;
            }
            if unemitted[found] == 0 {
                ready.push((nodes[found].seconds, Reverse(found)));
            }
        }
    }
    for position in 0..nodes.len() {
        if !emitted[position] {
            order.push(position);
        }
    }
    order
}

pub fn view_roots(view: &View) -> Vec<Id> {
    let mut roots = Vec::new();
    let mut add = |id: Id| {
        if !roots.contains(&id) {
            roots.push(id);
        }
    };
    for head in &view.heads {
        add(*head);
    }
    for bookmark in &view.bookmarks {
        for id in bookmark.targets.adds.iter().flatten() {
            add(*id);
        }
    }
    for tag in &view.tags {
        add(tag.target);
    }
    for workspace in &view.working_copies {
        add(workspace.target);
    }
    roots
}

pub fn all_commits(store: &mut Store, view: &View) -> Result<Vec<Id>> {
    collect_commits(store, &view_roots(view))
}

pub fn bookmark_target(view: &View, name: &[u8]) -> Option<Id> {
    view.bookmarks.iter().find_map(|bookmark| {
        if bookmark.name == name
            && bookmark.targets.adds.len() == 1
            && bookmark.targets.adds[0].is_some()
        {
            bookmark.targets.adds[0]
        } else {
            None
        }
    })
}

fn is_change_id_prefix(text: &str) -> bool {
    if text.is_empty() || text.len() > 26 {
        return false;
    }
    text.bytes().all(|byte| {
        let lower = byte.to_ascii_lowercase();
        lower.is_ascii_lowercase() || (b'2'..=b'7').contains(&lower)
    })
}

pub fn resolve_revision(store: &mut Store, view: &View, revision: &str) -> Result<Option<Id>> {
    if revision.is_empty() || revision == "@" {
        return Ok(ops::working_copy_id(view));
    }
    if let Some(id) = bookmark_target(view, revision.as_bytes()) {
        return Ok(Some(id));
    }
    if let Some(id) = view
        .tags
        .iter()
        .find(|tag| tag.name == revision.as_bytes())
        .map(|tag| tag.target)
    {
        return Ok(Some(id));
    }
    if let Some(id) = view.remote_refs.iter().find_map(|reference| {
        let mut joined = reference.remote.clone();
        joined.push(b'/');
        joined.extend_from_slice(&reference.name);
        (joined == revision.as_bytes()).then_some(reference.target)
    }) {
        return Ok(Some(id));
    }

    if revision.len() == 64 {
        if let Ok(id) = Id::from_hex(revision)
            && load_commit(store, id)?.is_some()
        {
            return Ok(Some(id));
        }
        return Ok(None);
    }

    let hex_prefix = is_hex_prefix(revision);
    let change_prefix = is_change_id_prefix(revision);
    if !hex_prefix && !change_prefix {
        return Ok(None);
    }

    let ids = all_commits(store, view)?;
    let mut matches = Vec::new();
    if hex_prefix {
        for id in &ids {
            if prefix_matches(&id.to_hex(), revision) {
                matches.push(*id);
            }
        }
    }
    if matches.is_empty() && change_prefix {
        for id in &ids {
            if let Some(commit) = load_commit(store, *id)? {
                let encoded = base32_encode(commit.change_id);
                if prefix_matches(&encoded, revision) {
                    matches.push(*id);
                }
            }
        }
    }
    if matches.len() == 1 {
        Ok(Some(matches[0]))
    } else {
        Ok(None)
    }
}

pub fn base32_encode(value: [u8; 16]) -> String {
    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
    let mut output = String::with_capacity(26);
    let mut buffer = 0u64;
    let mut bits = 0usize;
    for byte in value {
        buffer = (buffer << 8) | u64::from(byte);
        bits += 8;
        while bits >= 5 {
            let shift = bits - 5;
            let index = ((buffer >> shift) & 31) as usize;
            output.push(ALPHABET[index] as char);
            bits = shift;
        }
        if bits == 0 {
            buffer = 0;
        } else {
            buffer &= (1u64 << bits) - 1;
        }
    }
    if bits > 0 {
        output.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);
    }
    output
}

pub fn short_change_id(ids: &[String], index: usize) -> String {
    let target = &ids[index];
    let mut length = 4.min(target.len());
    while length < target.len() {
        let prefix = &target[..length];
        let unique = ids.iter().enumerate().all(|(other_index, other)| {
            other_index == index || other == target || !other.starts_with(prefix)
        });
        if unique {
            break;
        }
        length += 1;
    }
    target[..length].to_string()
}

fn append_blob(store: &Store, id: Id, output: &mut Vec<u8>, depth: usize) -> Result<bool> {
    if depth > 64 {
        return Err(Error::new("blob nesting too deep"));
    }
    let Some(body) = store.body_loaded(id, TYPE_BLOB)? else {
        return Ok(false);
    };
    let blob = blob::decode(&body)?;
    match blob.form {
        BlobForm::Inline => {
            output.extend_from_slice(&blob.data);
        }
        BlobForm::Leaf => {
            for entry in blob.entries {
                let Some(chunk) = store.body_loaded(entry.id, TYPE_CHUNK)? else {
                    return Ok(false);
                };
                output.extend_from_slice(&chunk);
            }
        }
        BlobForm::Interior => {
            for entry in blob.entries {
                if !append_blob(store, entry.id, output, depth + 1)? {
                    return Ok(false);
                }
            }
        }
    }
    Ok(true)
}

pub fn read_blob_loaded(store: &Store, id: Id) -> Result<Option<Vec<u8>>> {
    let mut output = Vec::new();
    if append_blob(store, id, &mut output, 0)? {
        Ok(Some(output))
    } else {
        Ok(None)
    }
}

pub fn read_blob(store: &mut Store, id: Id) -> Result<Option<Vec<u8>>> {
    store.preload()?;
    read_blob_loaded(store, id)
}

#[derive(Clone)]
pub struct TreeChange {
    pub path: Vec<u8>,
    pub old_kind: u8,
    pub new_kind: u8,
    pub old_id: Option<Id>,
    pub new_id: Option<Id>,
}

pub fn compare_trees(
    store: &mut Store,
    old_tree: Option<Id>,
    new_tree: Option<Id>,
) -> Result<Vec<TreeChange>> {
    let old_entries = match old_tree {
        Some(id) => tree::flatten(store, id)?,
        None => Vec::new(),
    };
    let new_entries = match new_tree {
        Some(id) => tree::flatten(store, id)?,
        None => Vec::new(),
    };
    let mut changes = Vec::new();
    let mut old_index = 0;
    let mut new_index = 0;
    while old_index < old_entries.len() || new_index < new_entries.len() {
        let ordering = if old_index >= old_entries.len() {
            std::cmp::Ordering::Greater
        } else if new_index >= new_entries.len() {
            std::cmp::Ordering::Less
        } else {
            old_entries[old_index]
                .path
                .cmp(&new_entries[new_index].path)
        };
        match ordering {
            std::cmp::Ordering::Less => {
                let entry = &old_entries[old_index];
                changes.push(TreeChange {
                    path: entry.path.clone(),
                    old_kind: entry.kind,
                    new_kind: KIND_MISSING,
                    old_id: Some(entry.target),
                    new_id: None,
                });
                old_index += 1;
            }
            std::cmp::Ordering::Greater => {
                let entry = &new_entries[new_index];
                changes.push(TreeChange {
                    path: entry.path.clone(),
                    old_kind: KIND_MISSING,
                    new_kind: entry.kind,
                    old_id: None,
                    new_id: Some(entry.target),
                });
                new_index += 1;
            }
            std::cmp::Ordering::Equal => {
                let old = &old_entries[old_index];
                let new = &new_entries[new_index];
                if old.kind != new.kind || old.target != new.target {
                    changes.push(TreeChange {
                        path: old.path.clone(),
                        old_kind: old.kind,
                        new_kind: new.kind,
                        old_id: Some(old.target),
                        new_id: Some(new.target),
                    });
                }
                old_index += 1;
                new_index += 1;
            }
        }
    }
    Ok(changes)
}

pub fn flatten(store: &mut Store, tree_id: Id) -> Result<Vec<FlatEntry>> {
    tree::flatten(store, tree_id)
}

fn conflicted_into(store: &mut Store, tree_id: Id, depth: usize) -> Result<bool> {
    if depth > crate::object::MAX_TREE_DEPTH {
        return Ok(true);
    }
    let Some(body) = store.body(tree_id, crate::object::TYPE_TREE)? else {
        return Ok(true);
    };
    let Ok(tree) = tree::decode(&body) else {
        return Ok(true);
    };
    for entry in tree.entries {
        if entry.kind == KIND_CONFLICT {
            return Ok(true);
        }
        if entry.kind == KIND_SUBTREE && conflicted_into(store, entry.target, depth + 1)? {
            return Ok(true);
        }
    }
    Ok(false)
}

pub fn tree_conflicted(store: &mut Store, tree_id: Id) -> Result<bool> {
    conflicted_into(store, tree_id, 0)
}