From d094b291576b71fc39bfc142e12537edc91a7005 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 8 Dec 2024 14:50:36 +0100 Subject: [PATCH] Adds some cli & Error handling --- .gitignore | 3 ++ Cargo.toml | 3 +- README.md | 3 +- badges/coverage.svg | 1 + badges/test.svg | 1 + badges/version.svg | 1 + src/cli.rs | 83 +++++++++++++++++++++++++++++++++++++++++++++ src/error.rs | 22 ++++++++++-- src/lib.rs | 1 + src/main.rs | 38 ++++++++++----------- 10 files changed, 133 insertions(+), 23 deletions(-) create mode 100644 badges/coverage.svg create mode 100644 badges/test.svg create mode 100644 badges/version.svg create mode 100644 src/cli.rs diff --git a/.gitignore b/.gitignore index 193d30e..bd11ae0 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ Cargo.lock # Added by cargo /target + +# Tarpaulin +tarpaulin-report.html diff --git a/Cargo.toml b/Cargo.toml index 552a5ba..152570e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,11 @@ reqwest = { version = "0.11.16", features = ["blocking"] } base64 = "0.21.0" lazy_static = "1.4.0" ratatui = "0.29.0" -serde = "1.0.215" +serde = { version = "1.0.215", features = ["derive", "alloc"] } thiserror = "2.0.4" tracing = "0.1.41" tokio = "1.42.0" +ron = "0.8.1" [[bin]] name = "rusty_midicommander" diff --git a/README.md b/README.md index 59b03a9..4831eca 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # RustyMIDICommander +![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) Rusty MIDI Commander is a lightweight and flexible Rust program for sending asynchronous commands in response to MIDI input. @@ -10,4 +11,4 @@ Rusty MIDI Commander makes it easy to build powerful and responsive MIDI control # Installation Depends on: - - `librust-alsa-dev` + - `librust-alsa-sys-dev` diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..e6a15fe --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 0%test-coverage0% diff --git a/badges/test.svg b/badges/test.svg new file mode 100644 index 0000000..a7859aa --- /dev/null +++ b/badges/test.svg @@ -0,0 +1 @@ +test: passingtestpassing diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..c28c459 --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.1.0version0.1.0 diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..255b2cb --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,83 @@ +//! 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; +use serde::{Deserialize, Serialize}; +use tracing::{debug, info, warn}; + +use crate::RustyMidiError; + +#[derive(Parser, Debug, Serialize, Deserialize, Default)] +#[command(author, version, about, long_about = None)] +/// A struct representing command line arguments for a CLI. +pub struct Args { + /// The midi interface to select + pub midi_interface: Option, + + /// Natural timeout delay + pub delay: Option, + + /// Config, holding another subset of values + pub config: Option, + + /// Create a config file from all the given arguments + pub save: Option, +} + +/// 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 { + debug!("Loading CLI arguments"); + let cli = parse_cli_and_load()?; + if let Some(save_path) = &cli.save { + info!("Saving config as {}", save_path); + File::create(save_path)?.write_all( + ron::ser::to_string_pretty(&cli, ron::ser::PrettyConfig::default())?.as_bytes(), + )?; + } + Ok(cli) +} + +/// Parse all cli arguments and loads a config from file if needed +fn parse_cli_and_load() -> Result { + let args_og = Args::parse(); + if let Some(path) = &args_og.config { + match load_from_disk(path) { + Ok(args_new) => Ok(update_non_default(args_og, args_new)), + Err(e) => { + warn!("The file {} coudln't be loaded: {}", path, e); + Ok(args_og) + } + } + } else { + Ok(args_og) + } +} + +/// Load a given config from disk and return it as a Config +fn load_from_disk(path: &str) -> Result { + Ok(ron::from_str(&read_to_string(path)?)?) +} + +/// Update a parameter +macro_rules! update { + ($args_og:ident, $new_args:ident, $param:ident) => { + $args_og.$param.or($new_args.$param) + }; +} + +/// Update all None parameters withthe config loaded ones +fn update_non_default(args_og: Args, args_new: Args) -> Args { + Args { + midi_interface: update!(args_og, args_new, midi_interface), + delay: update!(args_og, args_new, delay), + config: update!(args_og, args_new, config), + save: update!(args_og, args_new, save), + } +} diff --git a/src/error.rs b/src/error.rs index 0e79da7..63ec23c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,12 +1,30 @@ -//! Generic rusty midi commander error +//! Generic Rusty MIDI Commander error //! use thiserror::Error; -/// A generic error +/// A generic error for the Rusty Midi Commander. /// +/// # Example Usage +/// ``` +/// use rmc_lib::RustyMidiError; +/// +/// match Some(reqwest::Error::new(reqwest::StatusCode::NotFound)) { +/// None => println!("No error"), +/// Some(err) => return Err(RustyMidiError::NetworkRequest(err)), +/// } +/// ``` #[derive(Error, Debug)] pub enum RustyMidiError { #[error("network request failed {0}")] NetworkRequest(#[from] reqwest::Error), + + #[error("an error occured while accessing a file {0}")] + IO(#[from] std::io::Error), + + #[error("an error occured while trying to deserialize the config file {0}")] + RonSerialization(#[from] ron::de::SpannedError), + + #[error("an error occured while trying to serialize the config file {0}")] + RonDeSerialization(#[from] ron::Error), } diff --git a/src/lib.rs b/src/lib.rs index b1e8c4e..3acb5f7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ #![warn(clippy::missing_docs_in_private_items)] // use midir::MidiOutput; +pub mod cli; pub mod error; pub mod midi; pub mod projector; diff --git a/src/main.rs b/src/main.rs index 2ae34e8..3d788e8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,37 +1,37 @@ -//! In this organization, src/main.rs is the entry point for the program. -//! This file should set up the MIDI input and output devices, and then -//! start a loop to receive and process MIDI messages. -//! It should also use the commands module to send commands asynchronously. -//! use crate::midi::print_midi_interfaces; +//! This file initializes MIDI input and output devices, then continually listens to and processes MIDI messages. +//! It employs the `commands` module to send commands asynchronously. For all input MIDI devices present on the system, +//! it registers a command with the input interface which will be executed when a MIDI message with the specified velocity +//! is received from that device. #![warn(clippy::missing_docs_in_private_items)] -use std::sync::{Arc, Mutex}; +use std::{ + process::exit, + sync::{Arc, Mutex}, +}; use clap::Parser; use rmc_lib::{ + cli, midi::{self, cleanup, connect_loop_with_callback, create_output_interface}, projector, }; -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -/// Description of the cli -struct Args { - /// The midi interface to select - midi_interface: Option, -} - fn main() { // Parse Arguments - let args = Args::parse(); - if let Args { - midi_interface: None, - } = args - { + let args = cli::get_arguments_from_cli().unwrap_or_else(|e| { + println!("Coudln't read the command line {}", e); + // TODO: Test this + cli::Args::parse_from(vec!["-h"]); + exit(1); + }); + + // TODO: Cleanup all the following + if args.midi_interface.is_none() { midi::print_midi_interfaces(); return; } + println!("{:?}", args); let proj = Arc::new(Mutex::new(projector::panasonic::Projector::new( "127.0.0.1:8080",