journal/journal_cli/src/commands/psychonaut/import/custom_unit.rs
2024-11-25 23:40:36 +00:00

76 lines
1.8 KiB
Rust

use journal::{journal::JournalType, types::CustomUnit};
use super::{load_journal_and_export_data, PsychonautImportGlobalArgs};
pub fn create_or_update_custom_unit(journal: &mut JournalType, unit: CustomUnit) {
match journal.get_custom_unit(unit.id) {
Some(custom_unit) => {
println!(
"Updating Custom Unit ID: {} Name: {}",
unit.id, custom_unit.name
);
journal.update_custom_unit(unit.id, unit, false);
}
None => {
println!("Creating Custom Unit ID: {} Name: {}", unit.id, unit.name);
journal.update_custom_unit(unit.id, unit, true);
}
}
}
#[derive(Debug, Clone, clap::Args)]
#[group(args = vec!["id", "name"], required = true, multiple = false)]
pub struct PsychonautImportCustomUnitArgs {
#[command(flatten)]
pub import_global_args: PsychonautImportGlobalArgs,
#[arg(long)]
pub id: Option<i32>,
#[arg(long)]
pub name: Option<String>,
}
pub fn psychonaut_import_custom_unit(
args: &PsychonautImportCustomUnitArgs,
) -> Result<(), Box<dyn std::error::Error>> {
let (mut journal, export_data) = load_journal_and_export_data(&args.import_global_args)?;
match (&args.id, &args.name) {
(Some(id), _) => {
let unit = export_data
.custom_units
.into_iter()
.find(|unit| unit.id == *id);
match unit {
Some(unit) => {
create_or_update_custom_unit(&mut journal, CustomUnit::from(unit));
}
None => {
panic!("Could not find custom unit with ID: {id}")
}
}
}
(_, Some(name)) => {
let unit = export_data
.custom_units
.into_iter()
.find(|unit| unit.name == *name);
match unit {
Some(unit) => {
create_or_update_custom_unit(&mut journal, CustomUnit::from(unit));
}
None => {
panic!("Could not find custom unit with name: {name}")
}
}
}
_ => unreachable!(),
}
journal.save()?;
Ok(())
}