void-cli 0.0.4

CLI for void — anonymous encrypted source control
//! Rebuild the repository index from HEAD and working tree.
//!
//! Recovers a corrupted or missing index by scanning the HEAD commit
//! and working tree to reconstruct file entries.

use std::path::Path;

use serde::Serialize;
use void_core::index::rebuild_index;

use crate::context::{open_repo, void_err_to_cli};
use crate::output::{run_command, CliError, CliOptions};

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RebuildIndexOutput {
    pub entries_rebuilt: usize,
    pub from_head: usize,
    pub from_working_tree: usize,
}

pub fn run(cwd: &Path, opts: &CliOptions) -> Result<(), CliError> {
    run_command("debug rebuild-index", opts, |ctx| {
        let repo = open_repo(cwd)?;
        let void_dir = repo.void_dir();
        let workspace = void_dir
            .parent()
            .ok_or_else(|| CliError::internal("void_dir has no parent"))?;

        ctx.progress("Rebuilding index...");

        let result = rebuild_index(void_dir.as_std_path(), workspace.as_std_path(), repo.vault()).map_err(void_err_to_cli)?;

        if !ctx.use_json() {
            ctx.info(format!("Rebuilt {} index entries", result.entries_rebuilt));
            ctx.info(format!(
                "  from HEAD: {}, from working tree: {}",
                result.from_head, result.from_working_tree
            ));
        }

        Ok(RebuildIndexOutput {
            entries_rebuilt: result.entries_rebuilt,
            from_head: result.from_head,
            from_working_tree: result.from_working_tree,
        })
    })
}