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

status.rs

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

use std::collections::HashSet;

use crate::error::{Error, Result};
use crate::object::tree::KIND_CONFLICT;
use crate::store::graph;
use crate::store::ops;
use crate::store::reader::Store;
use crate::worktree::pathspec;
use crate::worktree::snapshot;

use super::output;

pub fn run() -> Result<u8> {
    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;
    let cwd = pathspec::cwd_relative(&root).unwrap_or_default();
    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"))?;
    let Some(working_copy) = ops::working_copy_id(&view) else {
        output::info_prefix();
        println!("working copy clean");
        return Ok(0);
    };
    let commit = graph::load_commit(&mut store, working_copy)?
        .ok_or_else(|| Error::new("no operation state"))?;
    let old_tree = match commit.parents.first() {
        Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree),
        None => None,
    };
    let changes = if old_tree == Some(commit.root_tree) {
        Vec::new()
    } else {
        graph::compare_trees(&mut store, old_tree, Some(commit.root_tree))?
    };
    let mut conflicts = 0usize;
    for change in &changes {
        let path = output::status_path(&change.path, &cwd);
        if change.old_kind == crate::object::tree::KIND_MISSING {
            println!("A {path}");
        } else if change.new_kind == crate::object::tree::KIND_MISSING {
            println!("D {path}");
        } else if change.new_kind == KIND_CONFLICT {
            println!("C {path}");
            conflicts += 1;
        } else {
            println!("M {path}");
        }
    }
    if changes.is_empty() {
        output::info_prefix();
        println!("working copy clean");
    }
    if conflicts > 0 {
        println!("{conflicts} conflict(s)");
    }
    let mut stack = vec![working_copy];
    let mut seen = HashSet::new();
    let mut conflicted_commits = 0usize;
    while let Some(id) = stack.pop() {
        if !seen.insert(id) {
            continue;
        }
        let Some(commit) = graph::load_commit(&mut store, id)? else {
            continue;
        };
        if graph::tree_conflicted(&mut store, commit.root_tree)? {
            conflicted_commits += 1;
        }
        stack.extend(commit.parents);
    }
    if conflicted_commits > 0 {
        println!("{conflicted_commits} conflicted commit(s) in ancestry");
    }
    Ok(0)
}