Skip to content

Commit

Permalink
refactor: make config static (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
micielski authored Aug 13, 2024
1 parent c0218a4 commit cb3bb56
Show file tree
Hide file tree
Showing 23 changed files with 123 additions and 172 deletions.
11 changes: 9 additions & 2 deletions rm-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,19 @@ pub mod keymap;
pub mod main_config;
mod utils;

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

use anyhow::Result;
use keymap::KeymapConfig;
use main_config::MainConfig;

pub static CONFIG: LazyLock<Config> = LazyLock::new(|| {
Config::init().unwrap_or_else(|e| {
eprintln!("{:?}", e);
std::process::exit(1);
})
});

pub struct Config {
pub general: main_config::General,
pub connection: main_config::Connection,
Expand All @@ -23,7 +30,7 @@ pub struct Directories {
}

impl Config {
pub fn init() -> Result<Self> {
fn init() -> Result<Self> {
let main_config = MainConfig::init()?;
let keybindings = KeymapConfig::init()?;

Expand Down
28 changes: 9 additions & 19 deletions rm-main/src/app.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crossterm::event::Event;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use rm_config::Config;
use rm_config::CONFIG;
use rm_shared::action::Action;
use rm_shared::action::UpdateAction;
use std::sync::Arc;
Expand All @@ -19,7 +19,6 @@ use transmission_rpc::{types::SessionGet, TransClient};

#[derive(Clone)]
pub struct Ctx {
pub config: Arc<Config>,
pub session_info: Arc<SessionGet>,
action_tx: UnboundedSender<Action>,
update_tx: UnboundedSender<UpdateAction>,
Expand All @@ -29,7 +28,6 @@ pub struct Ctx {
impl Ctx {
async fn new(
client: &mut TransClient,
config: Config,
action_tx: UnboundedSender<Action>,
update_tx: UnboundedSender<UpdateAction>,
trans_tx: UnboundedSender<TorrentAction>,
Expand All @@ -39,15 +37,14 @@ impl Ctx {
Ok(res) => {
let session_info = Arc::new(res.arguments);
Ok(Self {
config: Arc::new(config),
action_tx,
trans_tx,
update_tx,
session_info,
})
}
Err(e) => {
let config_path = config.directories.main_path;
let config_path = CONFIG.directories.main_path;
Err(Error::msg(format!(
"{e}\nIs the connection info in {:?} correct?",
config_path
Expand Down Expand Up @@ -79,21 +76,14 @@ pub struct App {
}

impl App {
pub async fn new(config: Config) -> Result<Self> {
pub async fn new() -> Result<Self> {
let (action_tx, action_rx) = mpsc::unbounded_channel();
let (update_tx, update_rx) = mpsc::unbounded_channel();

let mut client = transmission::utils::client_from_config(&config);
let mut client = transmission::utils::new_client();

let (trans_tx, trans_rx) = mpsc::unbounded_channel();
let ctx = Ctx::new(
&mut client,
config,
action_tx.clone(),
update_tx.clone(),
trans_tx,
)
.await?;
let ctx = Ctx::new(&mut client, action_tx.clone(), update_tx.clone(), trans_tx).await?;

tokio::spawn(transmission::action_handler(client, trans_rx, update_tx));

Expand Down Expand Up @@ -217,12 +207,12 @@ pub fn event_to_action(ctx: &Ctx, mode: Mode, current_tab: CurrentTab, event: Ev
Event::Key(key) => {
let keymaps = match current_tab {
CurrentTab::Torrents => [
&ctx.config.keybindings.general_keymap,
&ctx.config.keybindings.torrent_keymap,
&CONFIG.keybindings.general_keymap,
&CONFIG.keybindings.torrent_keymap,
],
CurrentTab::Search => [
&ctx.config.keybindings.general_keymap,
&ctx.config.keybindings.search_keymap,
&CONFIG.keybindings.general_keymap,
&CONFIG.keybindings.search_keymap,
],
};

Expand Down
15 changes: 7 additions & 8 deletions rm-main/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use anyhow::{bail, Result};
use base64::Engine;
use clap::{Parser, Subcommand};
use regex::Regex;
use rm_config::Config;
use transmission_rpc::types::TorrentAddArgs;

use crate::transmission;
Expand All @@ -22,16 +21,16 @@ pub enum Commands {
FetchRss { url: String, filter: Option<String> },
}

pub async fn handle_command(config: &Config, command: Commands) -> Result<()> {
pub async fn handle_command(command: Commands) -> Result<()> {
match command {
Commands::AddTorrent { torrent } => add_torrent(config, torrent).await?,
Commands::FetchRss { url, filter } => fetch_rss(config, &url, filter.as_deref()).await?,
Commands::AddTorrent { torrent } => add_torrent(torrent).await?,
Commands::FetchRss { url, filter } => fetch_rss(&url, filter.as_deref()).await?,
}
Ok(())
}

async fn add_torrent(config: &Config, torrent: String) -> Result<()> {
let mut transclient = transmission::utils::client_from_config(config);
async fn add_torrent(torrent: String) -> Result<()> {
let mut transclient = transmission::utils::new_client();
let args = {
if torrent.starts_with("magnet:")
|| torrent.starts_with("http:")
Expand Down Expand Up @@ -69,8 +68,8 @@ async fn add_torrent(config: &Config, torrent: String) -> Result<()> {
Ok(())
}

async fn fetch_rss(config: &Config, url: &str, filter: Option<&str>) -> Result<()> {
let mut transclient = transmission::utils::client_from_config(config);
async fn fetch_rss(url: &str, filter: Option<&str>) -> Result<()> {
let mut transclient = transmission::utils::new_client();
let content = reqwest::get(url).await?.bytes().await?;
let channel = rss::Channel::read_from(&content[..])?;
let re: Option<Regex> = {
Expand Down
11 changes: 4 additions & 7 deletions rm-main/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ pub mod tui;
mod ui;

use app::App;
use rm_config::Config;

use anyhow::Result;
use clap::Parser;
Expand All @@ -14,19 +13,17 @@ use clap::Parser;
async fn main() -> Result<()> {
let args = cli::Args::parse();

let config = Config::init()?;

if let Some(command) = args.command {
cli::handle_command(&config, command).await?;
cli::handle_command(command).await?;
} else {
run_tui(config).await?;
run_tui().await?;
}

Ok(())
}

async fn run_tui(config: Config) -> Result<()> {
let mut app = App::new(config).await?;
async fn run_tui() -> Result<()> {
let mut app = App::new().await?;
app.run().await?;
Ok(())
}
10 changes: 4 additions & 6 deletions rm-main/src/transmission/fetchers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{sync::Arc, time::Duration};

use rm_config::CONFIG;
use tokio::sync::oneshot;
use transmission_rpc::types::TorrentGetField;

Expand All @@ -22,7 +23,7 @@ pub async fn stats(ctx: app::Ctx) {
}
};

tokio::time::sleep(Duration::from_secs(ctx.config.connection.stats_refresh)).await;
tokio::time::sleep(Duration::from_secs(CONFIG.connection.stats_refresh)).await;
}
}

Expand Down Expand Up @@ -57,10 +58,7 @@ pub async fn free_space(ctx: app::Ctx) {
}
}

tokio::time::sleep(Duration::from_secs(
ctx.config.connection.free_space_refresh,
))
.await;
tokio::time::sleep(Duration::from_secs(CONFIG.connection.free_space_refresh)).await;
}
}

Expand Down Expand Up @@ -98,6 +96,6 @@ pub async fn torrents(ctx: app::Ctx) {
}
};

tokio::time::sleep(Duration::from_secs(ctx.config.connection.torrents_refresh)).await;
tokio::time::sleep(Duration::from_secs(CONFIG.connection.torrents_refresh)).await;
}
}
10 changes: 5 additions & 5 deletions rm-main/src/transmission/utils.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use rm_config::Config;
use rm_config::CONFIG;
use transmission_rpc::{types::BasicAuth, TransClient};

pub fn client_from_config(config: &Config) -> TransClient {
let user = config
pub fn new_client() -> TransClient {
let user = CONFIG
.connection
.username
.as_ref()
.unwrap_or(&"".to_string())
.clone();
let password = config
let password = CONFIG
.connection
.password
.as_ref()
Expand All @@ -17,5 +17,5 @@ pub fn client_from_config(config: &Config) -> TransClient {

let auth = BasicAuth { user, password };

TransClient::with_auth(config.connection.url.clone(), auth)
TransClient::with_auth(CONFIG.connection.url.clone(), auth)
}
5 changes: 3 additions & 2 deletions rm-main/src/ui/components/tabs.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::app;
use rm_config::CONFIG;
use rm_shared::action::Action;

use super::{Component, ComponentAction};
Expand All @@ -19,7 +20,7 @@ pub struct TabComponent {
impl TabComponent {
pub fn new(ctx: app::Ctx) -> Self {
let tabs_list = {
if ctx.config.general.beginner_mode {
if CONFIG.general.beginner_mode {
["1. Torrents", "2. Search"]
} else {
["Torrents", "Search"]
Expand Down Expand Up @@ -52,7 +53,7 @@ impl Component for TabComponent {
.flex(Flex::Center)
.split(rect)[0];

let tabs_highlight_style = Style::default().fg(self.ctx.config.general.accent_color);
let tabs_highlight_style = Style::default().fg(CONFIG.general.accent_color);
let tabs = Tabs::new(self.tabs_list)
.style(Style::default().white())
.highlight_style(tabs_highlight_style)
Expand Down
31 changes: 12 additions & 19 deletions rm-main/src/ui/global_popups/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ use crate::{
components::{Component, ComponentAction},
},
};
use rm_config::keymap::{actions::UserAction, Keybinding};
use rm_config::{
keymap::{actions::UserAction, Keybinding},
CONFIG,
};
use rm_shared::action::Action;

macro_rules! add_line {
Expand Down Expand Up @@ -165,17 +168,13 @@ impl Component for HelpPopup {
let popup_rect = centered_rect.inner(Margin::new(1, 1));
let text_rect = popup_rect.inner(Margin::new(3, 2));

let title_style = Style::new().fg(self.ctx.config.general.accent_color);
let title_style = Style::new().fg(CONFIG.general.accent_color);
let block = Block::bordered()
.border_set(symbols::border::ROUNDED)
.title(
Title::from(
" [ CLOSE ] "
.fg(self.ctx.config.general.accent_color)
.bold(),
)
.alignment(Alignment::Right)
.position(Position::Bottom),
Title::from(" [ CLOSE ] ".fg(CONFIG.general.accent_color).bold())
.alignment(Alignment::Right)
.position(Position::Bottom),
)
.title(" Help ")
.title_style(title_style);
Expand All @@ -186,7 +185,7 @@ impl Component for HelpPopup {
)])
.centered()];

Self::write_keybindings(&self.ctx.config.keybindings.general.keybindings, &mut lines);
Self::write_keybindings(&CONFIG.keybindings.general.keybindings, &mut lines);

lines.push(
Line::from(vec![Span::styled(
Expand All @@ -196,10 +195,7 @@ impl Component for HelpPopup {
.centered(),
);

Self::write_keybindings(
&self.ctx.config.keybindings.torrents_tab.keybindings,
&mut lines,
);
Self::write_keybindings(&CONFIG.keybindings.torrents_tab.keybindings, &mut lines);

lines.push(
Line::from(vec![Span::styled(
Expand All @@ -209,10 +205,7 @@ impl Component for HelpPopup {
.centered(),
);

Self::write_keybindings(
&self.ctx.config.keybindings.search_tab.keybindings,
&mut lines,
);
Self::write_keybindings(&CONFIG.keybindings.search_tab.keybindings, &mut lines);

let help_text = Text::from(lines);

Expand Down Expand Up @@ -254,7 +247,7 @@ impl Component for HelpPopup {

if let Some(scroll) = &mut self.scroll {
let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
.thumb_style(Style::default().fg(self.ctx.config.general.accent_color));
.thumb_style(Style::default().fg(CONFIG.general.accent_color));

f.render_stateful_widget(
scrollbar,
Expand Down
7 changes: 3 additions & 4 deletions rm-main/src/ui/tabs/search/bottom_bar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use ratatui::{
widgets::Paragraph,
Frame,
};
use rm_config::CONFIG;
use rm_shared::action::{Action, UpdateAction};
use throbber_widgets_tui::ThrobberState;

Expand Down Expand Up @@ -102,17 +103,15 @@ impl Component for SearchState {

fn render(&mut self, f: &mut Frame, rect: Rect) {
let append_key_info = |line: &mut Line| {
let providers_key = self
.ctx
.config
let providers_key = CONFIG
.keybindings
.get_keys_for_action(Action::ShowProvidersInfo);
if let Some(key) = providers_key {
line.push_span(Span::raw("Press "));
line.push_span(Span::styled(
key,
Style::default()
.fg(self.ctx.config.general.accent_color)
.fg(CONFIG.general.accent_color)
.underlined(),
));
line.push_span(Span::raw(" for details."))
Expand Down
Loading

0 comments on commit cb3bb56

Please sign in to comment.