use std::path::Path;
use dbmd_core::render::{self, Outline};
use dbmd_core::Store;
use crate::cli::OutlineArgs;
use crate::context::Context;
use crate::error::CliResult;
pub fn run(ctx: &Context, args: &OutlineArgs) -> CliResult {
let store = Store::open(Path::new(".")).map_err(dbmd_core::Error::from)?;
let outline = render::outline(&store, Path::new(&args.file)).map_err(dbmd_core::Error::from)?;
if ctx.json {
emit_json(&outline);
} else {
emit_text(&outline);
}
Ok(())
}
fn emit_text(outline: &Outline) {
for section in &outline.sections {
let indent = " ".repeat(section.level.saturating_sub(2) as usize);
println!("{indent}{}", section.heading);
}
}
fn emit_json(outline: &Outline) {
let sections: Vec<serde_json::Value> = outline
.sections
.iter()
.map(|s| {
serde_json::json!({
"heading": s.heading,
"level": s.level,
"line": s.line,
})
})
.collect();
let out = serde_json::json!({
"file": path_str(&outline.file),
"sections": sections,
});
println!(
"{}",
serde_json::to_string(&out).expect("serialize outline")
);
}
fn path_str(p: &Path) -> String {
p.to_string_lossy().replace('\\', "/")
}