This repository has been archived on 2026-09-13. You can view files and clone it, but cannot push or open issues or pull requests.
rusty_midi_commander/src/cli.rs

151 lines
4.6 KiB
Rust

//! CLI & config processing.
//!
//! Processes all arguments given by the CLI invocation via clap
//! The usage of config will provide if used a way to have default values for all arguments
use std::{
fs::{read_to_string, File},
io::Write,
};
use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize};
use crate::{projector::VPType, RustyMidiError};
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
/// A struct representing command line arguments for a CLI.
pub struct RMCArgs {
/// The subcommand to pick from
#[command(subcommand)]
pub command: SubCommands,
}
#[derive(Debug, Subcommand)]
pub enum SubCommands {
/// Create a VP config file with the given name
Create(CreateArgs),
/// Launch the program as a cli
Launch(CLIArgs),
// /// Launch the program as a TUI
// TUI(TUIArgs),
}
/// The bulk of the cli arguments, able to be launch and reloaded from a config file.
///
/// Note that the global config file and a vp config file are different and created differently
#[derive(Debug, Parser, Serialize, Deserialize, Clone)]
pub struct CLIArgs {
/// The midi interface to select, if none is selected,
/// the program will not be using midi altogether
pub midi_interface: Option<usize>,
/// Config, holding another subset of values
#[arg(short, long)]
pub config: Option<String>,
/// Create a config file from all the given arguments
#[arg(short, long)]
pub save: Option<String>,
//
// /// Connect to a VP
// pub vp: Option<Vec<VPType>>,
}
/// All arguments for creating a VP configuration
#[derive(Debug, Parser, Serialize, Deserialize)]
pub struct CreateArgs {
/// Create a projector config file of a specific type
#[command(subcommand)]
pub create: Option<VPType>,
}
// impl From<OsStr> for VPType {
// fn from(value: OsStr) -> Self {
// todo!()
// }
// }
/// Get a parsed Args from the Cli, this function will also perform the basic (save/load) and printing needed
pub fn get_arguments_from_cli() -> Result<RMCArgs, RustyMidiError> {
log::debug!("Loading CLI arguments");
let cli = parse_cli_and_load()?;
if let SubCommands::Launch(cliargs) = &cli.command {
if let Some(save_path) = &cliargs.save {
log::info!("Saving config as {}: ", save_path);
File::create(save_path)?
.write_all(serde_json::to_string_pretty(&cliargs)?.as_bytes())?;
}
}
Ok(cli)
}
/// Parse all cli arguments and loads a config from file if needed
fn parse_cli_and_load() -> Result<RMCArgs, RustyMidiError> {
let mut args = RMCArgs::parse();
if let SubCommands::Launch(ref mut cliargs) = args.command {
if let Some(path) = &cliargs.config {
match load_from_disk(path) {
Ok(args_new) => {
log::debug!(
"Updated arguments with new values \n [OLD] {:?} \n [NEW] {:?}",
cliargs,
args_new
);
update_non_default(cliargs, args_new);
}
Err(e) => {
log::warn!("The file {} couldn't be loaded:\n {}", path, e);
}
}
}
};
Ok(args)
}
/// Load a given config from disk and return it as a Config
fn load_from_disk(path: &str) -> Result<CLIArgs, RustyMidiError> {
Ok(serde_json::from_str(&read_to_string(path)?)?)
}
/// Update a parameter
macro_rules! update {
($args_og:ident, $args_new:ident, $param:ident) => {
let og = $args_og.$param.take();
$args_og.$param = og.or_else(|| {
// log::info!("Changing save with {:?}", args_new.config.as_mut());
$args_new.$param
});
};
}
/// Update all None parameters withthe config loaded ones
fn update_non_default(args_og: &mut CLIArgs, args_new: CLIArgs) {
update!(args_og, args_new, save);
update!(args_og, args_new, config);
update!(args_og, args_new, midi_interface);
}
impl RMCArgs {
/// Save the config
pub fn save(&self) -> Result<(), RustyMidiError> {
if let RMCArgs {
command:
SubCommands::Launch(
cliargs @ CLIArgs {
midi_interface: _,
config: _,
save: Some(save_path),
},
),
} = &self
{
log::info!("Saving config as {}: ", save_path);
File::create(save_path)?
.write_all(serde_json::to_string_pretty(&cliargs)?.as_bytes())?;
}
Ok(())
}
}