use std::io::Write;
use anyhow::{bail, Context, Result};
use doiget_core::store::{FsStore, Store};
use doiget_core::Ref;
use super::resolve_store_root;
pub fn run(input: String, mode: super::output::OutputMode) -> Result<()> {
let ref_ = Ref::parse(&input).with_context(|| format!("invalid ref: {input}"))?;
let safekey = ref_.safekey();
let store_root = resolve_store_root()?;
let store = FsStore::new(store_root)?;
let metadata = store
.read(&safekey)
.with_context(|| format!("failed to read store entry for {input}"))?;
match metadata {
Some(m) => {
if mode == super::output::OutputMode::Quiet {
return Ok(());
}
let stdout = std::io::stdout();
let mut out = stdout.lock();
if mode == super::output::OutputMode::Json {
let s = serde_json::to_string_pretty(&m)
.context("failed to serialize metadata to JSON for stdout")?;
writeln!(out, "{s}").context("failed to write metadata JSON to stdout")?;
return Ok(());
}
let s = toml::to_string_pretty(&m)
.context("failed to serialize metadata to TOML for stdout")?;
write!(out, "{s}").context("failed to write metadata to stdout")?;
if !s.ends_with('\n') {
writeln!(out).context("failed to write trailing newline")?;
}
Ok(())
}
None => bail!("no entry for {input}"),
}
}