Skip to main content

mkit_cli/commands/
tree.rs

1//! `mkit tree` — snapshot the working directory as a tree object,
2//! printing the resulting tree hash.
3
4use std::io::Write;
5
6use clap::Parser;
7use mkit_core::store::ObjectStore;
8use mkit_core::worktree;
9
10use crate::clap_shim;
11use crate::exit;
12use crate::format;
13
14#[derive(Debug, Parser)]
15#[command(
16    name = "mkit tree",
17    about = "Snapshot the working directory as a tree object."
18)]
19struct TreeOpts {}
20
21#[must_use]
22pub fn run(args: &[String]) -> u8 {
23    if let Err(code) = clap_shim::parse::<TreeOpts>("mkit tree", args) {
24        return code;
25    }
26    let cwd = match std::env::current_dir() {
27        Ok(p) => p,
28        Err(e) => return emit_err(&format!("cwd: {e}"), exit::NOINPUT),
29    };
30    let store = match ObjectStore::open(&cwd) {
31        Ok(s) => s,
32        Err(e) => return emit_err(&format!("not a mkit repo: {e}"), exit::GENERAL_ERROR),
33    };
34    match worktree::build_tree(&store, &cwd) {
35        Ok(h) => {
36            let mut stdout = std::io::stdout().lock();
37            let _ = writeln!(stdout, "{}", format::hex_hash(&h));
38            exit::OK
39        }
40        Err(e) => emit_err(&format!("build tree: {e}"), exit::GENERAL_ERROR),
41    }
42}
43
44fn emit_err(msg: &str, code: u8) -> u8 {
45    let mut stderr = std::io::stderr().lock();
46    let _ = writeln!(stderr, "error: {msg}");
47    code
48}