Skip to content

Commit

Permalink
Logging to files is now possible
Browse files Browse the repository at this point in the history
  • Loading branch information
Xithrius committed Jul 22, 2022
1 parent 8d9f748 commit 64f09ec
Show file tree
Hide file tree
Showing 11 changed files with 290 additions and 259 deletions.
453 changes: 215 additions & 238 deletions Cargo.lock

Large diffs are not rendered by default.

18 changes: 10 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,27 @@ keywords = ["tui", "twitch"]
categories = ["command-line-utilities"]

[dependencies]
crossterm = "0.23.2"
crossterm = "0.24.0"
tui = { version = "0.18.0", default-features = false, features = [ "crossterm" ] }
tokio = { version = "1.19.2", features = [ "full" ] }
clap = { version = "3.1.1", features = [ "derive", "cargo" ] }
serde = { version = "1.0.137", features = [ "derive" ] }
serde_json = "1.0.81"
tokio = { version = "1.20.0", features = [ "full" ] }
clap = { version = "3.2.13", features = [ "derive", "cargo" ] }
serde = { version = "1.0.140", features = [ "derive" ] }
serde_json = "1.0.82"
unicode-width = "0.1.9"
unicode-segmentation = "1.9.0"
chrono = "0.4"
irc = "0.15.0"
futures = "0.3.21"
toml = "0.5.9"
textwrap = "0.15.0"
rustyline = "9.1.2"
rustyline = "10.0.0"
lazy_static = "1.4.0"
enum-iterator = "0.8.1"
fuzzy-matcher = "0.3.7"
regex = "1.5.6"
color-eyre = "0.6.1"
regex = "1.6.0"
color-eyre = "0.6.2"
log = "0.4.17"
fern = "0.6.1"

[[bin]]
bench = false
Expand Down
2 changes: 2 additions & 0 deletions default-config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ token = ""
tick_delay = 30
# The maximum amount of messages to be stored.
maximum_messages = 150
# The file path to log to.
log_file = ""

[storage]
# If previous channels switched to should be tracked.
Expand Down
9 changes: 3 additions & 6 deletions src/handlers/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ use enum_iterator::IntoEnumIterator;
use rustyline::line_buffer::LineBuffer;
use tui::layout::Constraint;

use crate::{
handlers::{config::CompleteConfig, data::Data, filters::Filters, storage::Storage},
utils::pathing::config_path,
};
use crate::handlers::{config::CompleteConfig, data::Data, filters::Filters, storage::Storage};

pub enum State {
Normal,
Expand Down Expand Up @@ -61,8 +58,8 @@ impl App {

Self {
messages: VecDeque::with_capacity(config.terminal.maximum_messages),
storage: Storage::new(config_path("storage.json"), config.storage),
filters: Filters::new(config_path("filters.txt"), config.filters),
storage: Storage::new("storage.json", config.storage),
filters: Filters::new("filters.txt", config.filters),
state: State::Normal,
selected_buffer: BufferName::Chat,
buffer_suggestion: "".to_string(),
Expand Down
10 changes: 8 additions & 2 deletions src/handlers/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ pub struct Cli {
/// The streamer's name
#[clap(short, long)]
pub channel: Option<String>,
/// File to log to
#[clap(short, long)]
pub log_file: Option<String>,
/// The delay in milliseconds between terminal updates
#[clap(short, long)]
pub tick_delay: Option<u64>,
Expand All @@ -34,8 +37,11 @@ pub struct Cli {
}

pub fn merge_args_into_config(config: &mut CompleteConfig, args: Cli) {
if let Some(ch) = args.channel {
config.twitch.channel = ch;
if let Some(channel) = args.channel {
config.twitch.channel = channel;
}
if let Some(log_file) = args.log_file {
config.terminal.log_file = Some(log_file);
}
if let Some(tick_delay) = args.tick_delay {
config.terminal.tick_delay = tick_delay;
Expand Down
3 changes: 3 additions & 0 deletions src/handlers/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub struct TerminalConfig {
pub tick_delay: u64,
/// The maximum amount of messages before truncation.
pub maximum_messages: usize,
/// The file path to log to.
pub log_file: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
Expand Down Expand Up @@ -105,6 +107,7 @@ impl Default for TerminalConfig {
Self {
tick_delay: 30,
maximum_messages: 150,
log_file: None,
}
}
}
Expand Down
8 changes: 5 additions & 3 deletions src/handlers/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::fs::read_to_string;

use regex::Regex;

use crate::handlers::config::FiltersConfig;
use crate::{handlers::config::FiltersConfig, utils::pathing::config_path};

#[derive(Debug, Clone)]
pub struct Filters {
Expand All @@ -12,9 +12,11 @@ pub struct Filters {
}

impl Filters {
pub fn new(filter_path: String, config: FiltersConfig) -> Self {
pub fn new(file: &str, config: FiltersConfig) -> Self {
let file_path = config_path(file);

Self {
captures: if let Ok(f) = read_to_string(filter_path) {
captures: if let Ok(f) = read_to_string(file_path) {
f.split('\n')
.filter(|s| !s.is_empty())
.flat_map(Regex::new)
Expand Down
6 changes: 4 additions & 2 deletions src/handlers/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::{
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};

use crate::handlers::config::StorageConfig;
use crate::{handlers::config::StorageConfig, utils::pathing::config_path};

lazy_static! {
pub static ref ITEM_KEYS: Vec<&'static str> = vec!["channels", "mentions"];
Expand All @@ -29,7 +29,9 @@ pub struct StorageItem {
}

impl Storage {
pub fn new(file_path: String, config: StorageConfig) -> Self {
pub fn new(file: &str, config: StorageConfig) -> Self {
let file_path = config_path(file);

if !Path::new(&file_path).exists() {
let mut items = StorageMap::new();

Expand Down
32 changes: 32 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,36 @@ mod utils;

use clap::Parser;
use color_eyre::eyre::{Result, WrapErr};
use log::debug;
use tokio::sync::mpsc;

use crate::handlers::{app::App, args::Cli, config::CompleteConfig};

fn initialize_logging(config: &CompleteConfig) {
let logger = fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message
))
})
.level(log::LevelFilter::Debug);

if let Some(log_file_path) = config.terminal.log_file.to_owned() {
if !log_file_path.is_empty() {
logger
.chain(fern::log_file(log_file_path).unwrap())
.apply()
.unwrap();
}
} else {
logger.apply().unwrap();
}
}

#[tokio::main]
async fn main() -> Result<()> {
color_eyre::install().unwrap();
Expand All @@ -18,11 +44,17 @@ async fn main() -> Result<()> {
.wrap_err("Configuration error.")
.unwrap();

initialize_logging(&config);

debug!("Logging system initialised");

let app = App::new(config.clone());

let (twitch_tx, terminal_rx) = mpsc::channel(100);
let (terminal_tx, twitch_rx) = mpsc::channel(100);

debug!("Started tokio communication channels.");

let cloned_config = config.clone();

tokio::task::spawn(async move {
Expand Down
5 changes: 5 additions & 0 deletions src/terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crossterm::{
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use log::debug;
use rustyline::{At, Word};
use tokio::sync::mpsc::{Receiver, Sender};
use tui::{backend::CrosstermBackend, layout::Constraint, Terminal};
Expand Down Expand Up @@ -48,9 +49,13 @@ pub async fn ui_driver(
tx: Sender<Action>,
mut rx: Receiver<Data>,
) {
debug!("Started UI driver.");

let original_hook = std::panic::take_hook();

std::panic::set_hook(Box::new(move |panic| {
debug!("Panic hook hit.");

reset_terminal();
original_hook(panic);
}));
Expand Down
3 changes: 3 additions & 0 deletions src/twitch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use irc::{
error::Error::PingTimeout,
proto::Command,
};
use log::debug;
use tokio::{
sync::mpsc::{Receiver, Sender},
time::sleep,
Expand Down Expand Up @@ -53,6 +54,8 @@ async fn create_client_stream(config: CompleteConfig) -> (Client, ClientStream)
}

pub async fn twitch_irc(mut config: CompleteConfig, tx: Sender<Data>, mut rx: Receiver<Action>) {
debug!("Spawned Twitch IRC thread.");

let data_builder = DataBuilder::new(&config.frontend.date_format);
let mut room_state_startup = false;

Expand Down

0 comments on commit 64f09ec

Please sign in to comment.