use crate::{status_err, Application, RUSTIC_APP};
use abscissa_core::{Command, Runnable, Shutdown};
use anyhow::Result;
use rustic_core::repofile::{BlobType, FileType};
#[derive(clap::Parser, Command, Debug)]
pub(crate) struct CatCmd {
#[clap(subcommand)]
cmd: CatSubCmd,
}
#[derive(clap::Subcommand, Debug)]
enum CatSubCmd {
TreeBlob(IdOpt),
DataBlob(IdOpt),
Config,
Index(IdOpt),
Snapshot(IdOpt),
Tree(TreeOpts),
}
#[derive(Default, clap::Parser, Debug)]
struct IdOpt {
id: String,
}
#[derive(clap::Parser, Debug)]
struct TreeOpts {
#[clap(value_name = "SNAPSHOT[:PATH]")]
snap: String,
}
impl Runnable for CatCmd {
fn run(&self) {
if let Err(err) = self.inner_run() {
status_err!("{}", err);
RUSTIC_APP.shutdown(Shutdown::Crash);
};
}
}
impl CatCmd {
fn inner_run(&self) -> Result<()> {
let config = RUSTIC_APP.config();
let data = match &self.cmd {
CatSubCmd::Config => config
.repository
.run_open(|repo| Ok(repo.cat_file(FileType::Config, "")?))?,
CatSubCmd::Index(opt) => config
.repository
.run_open(|repo| Ok(repo.cat_file(FileType::Index, &opt.id)?))?,
CatSubCmd::Snapshot(opt) => config
.repository
.run_open(|repo| Ok(repo.cat_file(FileType::Snapshot, &opt.id)?))?,
CatSubCmd::TreeBlob(opt) => config
.repository
.run_indexed(|repo| Ok(repo.cat_blob(BlobType::Tree, &opt.id)?))?,
CatSubCmd::DataBlob(opt) => config
.repository
.run_indexed(|repo| Ok(repo.cat_blob(BlobType::Data, &opt.id)?))?,
CatSubCmd::Tree(opt) => config.repository.run_indexed(|repo| {
Ok(repo.cat_tree(&opt.snap, |sn| config.snapshot_filter.matches(sn))?)
})?,
};
println!("{}", String::from_utf8(data.to_vec())?);
Ok(())
}
}