Skip to content

Commit

Permalink
create intuiconfig trait in intuitils
Browse files Browse the repository at this point in the history
  • Loading branch information
micielski committed Oct 26, 2024
1 parent 42c0f5e commit e5c0ddb
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 159 deletions.
9 changes: 7 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ license = "GPL-3.0-or-later"
rm-config = { version = "0.5", path = "rm-config" }
rm-shared = { version = "0.5", path = "rm-shared" }

intuitils = "0.0.2"
intuitils = "0.0.3"

magnetease = "0.3"
anyhow = "1"
Expand Down
72 changes: 29 additions & 43 deletions rm-config/src/categories.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use std::{collections::HashMap, io::ErrorKind, path::PathBuf, sync::OnceLock};
use std::collections::HashMap;

use anyhow::{Context, Result};
use intuitils::config::IntuiConfig;
use ratatui::style::Color;
use serde::Deserialize;

use crate::utils::{self, ConfigFetchingError};

#[derive(Deserialize)]
pub struct CategoriesConfig {
#[serde(default)]
Expand All @@ -18,6 +16,33 @@ pub struct CategoriesConfig {
pub max_icon_len: u8,
}

impl IntuiConfig for CategoriesConfig {
fn app_name() -> &'static str {
"rustmission"
}

fn filename() -> &'static str {
"categories.toml"
}

fn default_config() -> &'static str {
include_str!("../defaults/categories.toml")
}

fn should_exit_if_not_found() -> bool {
false
}

fn message_if_not_found() -> Option<String> {
None
}

fn post_init(&mut self) {
self.populate_hashmap();
self.set_lengths();
}
}

#[derive(Deserialize, Clone)]
pub struct Category {
pub name: String,
Expand All @@ -26,50 +51,11 @@ pub struct Category {
pub default_dir: String,
}

impl CategoriesConfig {
pub(crate) const FILENAME: &'static str = "categories.toml";
pub const DEFAULT_CONFIG: &'static str = include_str!("../defaults/categories.toml");

pub(crate) fn init() -> Result<Self> {
match utils::fetch_config::<Self>(Self::FILENAME) {
Ok(mut config) => {
config.after_init();
Ok(config)
}
Err(e) => match e {
ConfigFetchingError::Io(e) if e.kind() == ErrorKind::NotFound => {
let mut config =
utils::put_config::<Self>(Self::DEFAULT_CONFIG, Self::FILENAME)?;
config.after_init();
Ok(config)
}
ConfigFetchingError::Toml(e) => Err(e).with_context(|| {
format!(
"Failed to parse config located at {:?}",
utils::get_config_path(Self::FILENAME)
)
}),
_ => anyhow::bail!(e),
},
}
}

pub(crate) fn path() -> &'static PathBuf {
static PATH: OnceLock<PathBuf> = OnceLock::new();
PATH.get_or_init(|| utils::get_config_path(Self::FILENAME))
}
}

impl CategoriesConfig {
pub fn is_empty(&self) -> bool {
self.categories.is_empty()
}

fn after_init(&mut self) {
self.populate_hashmap();
self.set_lengths();
}

fn populate_hashmap(&mut self) {
for category in &self.categories {
self.map.insert(category.name.clone(), category.clone());
Expand Down
48 changes: 18 additions & 30 deletions rm-config/src/keymap/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
pub mod actions;

use std::{io::ErrorKind, path::PathBuf, sync::OnceLock};

use anyhow::{Context, Result};
use intuitils::config::keybindings::KeybindsHolder;
use intuitils::config::{keybindings::KeybindsHolder, IntuiConfig};
use serde::Deserialize;

use crate::utils::{self, ConfigFetchingError};
use rm_shared::action::Action;

pub use self::actions::{
Expand All @@ -20,32 +16,24 @@ pub struct KeymapConfig {
pub search_tab: KeybindsHolder<SearchAction, Action>,
}

impl KeymapConfig {
pub const FILENAME: &'static str = "keymap.toml";
pub const DEFAULT_CONFIG: &'static str = include_str!("../../defaults/keymap.toml");

pub fn init() -> Result<Self> {
match utils::fetch_config::<Self>(Self::FILENAME) {
Ok(keymap_config) => Ok(keymap_config),
Err(e) => match e {
ConfigFetchingError::Io(e) if e.kind() == ErrorKind::NotFound => {
let keymap_config =
utils::put_config::<Self>(Self::DEFAULT_CONFIG, Self::FILENAME)?;
Ok(keymap_config)
}
ConfigFetchingError::Toml(e) => Err(e).with_context(|| {
format!(
"Failed to parse config located at {:?}",
utils::get_config_path(Self::FILENAME)
)
}),
_ => anyhow::bail!(e),
},
}
impl IntuiConfig for KeymapConfig {
fn app_name() -> &'static str {
"rustmission"
}

fn filename() -> &'static str {
"keymap.toml"
}

fn default_config() -> &'static str {
include_str!("../../defaults/keymap.toml")
}

fn should_exit_if_not_found() -> bool {
false
}

pub fn path() -> &'static PathBuf {
static PATH: OnceLock<PathBuf> = OnceLock::new();
PATH.get_or_init(|| utils::get_config_path(Self::FILENAME))
fn message_if_not_found() -> Option<String> {
None
}
}
2 changes: 1 addition & 1 deletion rm-config/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
pub mod categories;
pub mod keymap;
pub mod main_config;
mod utils;

use std::{path::PathBuf, sync::LazyLock};

use anyhow::Result;
use categories::CategoriesConfig;
use intuitils::config::IntuiConfig;
use keymap::KeymapConfig;
use main_config::MainConfig;

Expand Down
51 changes: 21 additions & 30 deletions rm-config/src/main_config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@ mod torrents_tab;
pub use connection::Connection;
pub use general::General;
pub use icons::Icons;
use intuitils::config::IntuiConfig;
pub use search_tab::SearchTab;
pub use torrents_tab::TorrentsTab;

use std::{io::ErrorKind, path::PathBuf, sync::OnceLock};

use anyhow::{Context, Result};
use serde::Deserialize;

use crate::utils::{self, ConfigFetchingError};

#[derive(Deserialize)]
pub struct MainConfig {
#[serde(default)]
Expand All @@ -30,32 +26,27 @@ pub struct MainConfig {
pub icons: Icons,
}

impl MainConfig {
pub(crate) const FILENAME: &'static str = "config.toml";
pub const DEFAULT_CONFIG: &'static str = include_str!("../../defaults/config.toml");

pub(crate) fn init() -> Result<Self> {
match utils::fetch_config::<Self>(Self::FILENAME) {
Ok(config) => Ok(config),
Err(e) => match e {
ConfigFetchingError::Io(e) if e.kind() == ErrorKind::NotFound => {
utils::put_config::<Self>(Self::DEFAULT_CONFIG, Self::FILENAME)?;
println!("Update {:?} (especially connection url) and start rustmission again", Self::path());
std::process::exit(0);
}
ConfigFetchingError::Toml(e) => Err(e).with_context(|| {
format!(
"Failed to parse config located at {:?}",
utils::get_config_path(Self::FILENAME)
)
}),
_ => anyhow::bail!(e),
},
}
impl IntuiConfig for MainConfig {
fn app_name() -> &'static str {
"rustmission"
}

fn filename() -> &'static str {
"config.toml"
}

fn default_config() -> &'static str {
include_str!("../../defaults/config.toml")
}

fn should_exit_if_not_found() -> bool {
true
}

pub(crate) fn path() -> &'static PathBuf {
static PATH: OnceLock<PathBuf> = OnceLock::new();
PATH.get_or_init(|| utils::get_config_path(Self::FILENAME))
fn message_if_not_found() -> Option<String> {
Some(format!(
"Update {:?} (especially connection url) and start rustmission again",
Self::path()
))
}
}
50 changes: 0 additions & 50 deletions rm-config/src/utils.rs

This file was deleted.

1 change: 1 addition & 0 deletions rm-main/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ regex.workspace = true
throbber-widgets-tui.workspace = true
chrono.workspace = true
open.workspace = true
intuitils.workspace = true
12 changes: 10 additions & 2 deletions rm-main/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use clap::{Parser, Subcommand};

use add_torrent::add_torrent;
use fetch_rss::fetch_rss;
use intuitils::config::IntuiConfig;

#[derive(Parser)]
#[command(version, about)]
Expand All @@ -20,17 +21,24 @@ pub enum Commands {
FetchRss { url: String, filter: Option<String> },
PrintDefaultConfig {},
PrintDefaultKeymap {},
PrintDefaultCategories {},
}

pub async fn handle_command(command: Commands) -> Result<()> {
match command {
Commands::AddTorrent { torrent } => add_torrent(torrent).await?,
Commands::FetchRss { url, filter } => fetch_rss(&url, filter.as_deref()).await?,
Commands::PrintDefaultConfig {} => {
println!("{}", rm_config::main_config::MainConfig::DEFAULT_CONFIG)
println!("{}", rm_config::main_config::MainConfig::default_config())
}
Commands::PrintDefaultKeymap {} => {
println!("{}", rm_config::keymap::KeymapConfig::DEFAULT_CONFIG)
println!("{}", rm_config::keymap::KeymapConfig::default_config())
}
Commands::PrintDefaultCategories {} => {
println!(
"{}",
rm_config::categories::CategoriesConfig::default_config()
)
}
}
Ok(())
Expand Down

0 comments on commit e5c0ddb

Please sign in to comment.