Skip to content

Commit

Permalink
refactoring ⚡
Browse files Browse the repository at this point in the history
  • Loading branch information
doums committed Aug 18, 2024
1 parent a4e177e commit a92dcfc
Show file tree
Hide file tree
Showing 22 changed files with 793 additions and 172 deletions.
413 changes: 409 additions & 4 deletions Cargo.lock

Large diffs are not rendered by default.

15 changes: 12 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
[package]
name = "baru"
version = "0.3.2"
version = "0.4.0"
authors = ["pierre <dommerc.pierre@gmail.com>"]
edition = "2021"
links = "netlink,audio"
build = "build.rs"

[dependencies]
chrono = "0.4"
regex = "1"
anyhow = "1.0.86"
thiserror = "1.0"
clap = { version = "4.5", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.9"
tracing = "0.1"
tracing-subscriber = { version = "0.3.1", features = [
"tracing-log",
"env-filter",
] }
tracing-appender = "0.2"
chrono = "0.4"
regex = "1"

[build-dependencies]
cmake = "0.1"
Expand Down
17 changes: 8 additions & 9 deletions baru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -479,22 +479,21 @@ temperature:
# core_inputs: u32 | List of u32 | String, default: 1
#
# The average temperature is calculated from one or several input files.
# Input files are files named `tempx_input` where x is a number.
# Input files are located in the directory /sys/devices/platform/coretemp.0/hwmon/*
# and are named `tempn_input` where n is a number.
# e.g. temp1_input temp2_input
# You can list them using `ls -l /sys/devices/platform/coretemp.0/hwmon/* `
# Input files can contain the temperature of a cpu core.
# Based on the cpu and its number of cores you want to provide
# the corresponding input file number(s).
# Tips: see the label files, e.g. `temp1_label`, to identify
# which input files reports cpu core temperature.
#
# Can be a number to select one input file, eg. 1 for temp1_input.
# Can be a list of number to select multiple input files, eg.
# core_inputs: [ 2, 6 ]
# to select temp2_input and temp6_input
# Can be a inclusive range to select multiple input files, eg.
# core_inputs: 2..3
# to select temp1_input temp2_input and temp3_input
# This option can be set either to:
# A number to select one input file, eg. 1 for temp1_input.
# A list of number to select multiple input files, eg.
# core_inputs: [ 2, 6 ] to select temp2_input and temp6_input
# A inclusive range to select multiple input files, eg.
# core_inputs: 2..3 to select temp1_input temp2_input and temp3_input
#
core_inputs: 1

Expand Down
17 changes: 17 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use clap::{Parser, ValueEnum};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone, ValueEnum)]
pub enum Logs {
Off,
Stdout,
File,
}

#[derive(Parser, Serialize, Deserialize, Debug, Clone)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
/// Enable app logs
#[arg(short, long)]
pub logs: Option<Logs>,
}
57 changes: 20 additions & 37 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,33 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

mod battery;
mod brightness;
mod cpu;
mod cpu_freq;
mod date_time;
pub mod cli;
mod error;
mod memory;
mod mic;
mod module;
mod modules;
mod netlink;
pub mod pulse;
mod sound;
mod temperature;
mod wired;
mod wireless;
use battery::Config as BatteryConfig;
use brightness::Config as BrightnessConfig;
use cpu::Config as CpuConfig;
use cpu_freq::Config as CpuFreqConfig;
use date_time::Config as DateTimeConfig;
pub mod trace;
pub mod util;

use error::Error;
use memory::Config as MemoryConfig;
use mic::Config as MicConfig;
use module::{Bar, ModuleData};
use modules::battery::Config as BatteryConfig;
use modules::brightness::Config as BrightnessConfig;
use modules::cpu::Config as CpuConfig;
use modules::cpu_freq::Config as CpuFreqConfig;
use modules::date_time::Config as DateTimeConfig;
use modules::memory::Config as MemoryConfig;
use modules::mic::Config as MicConfig;
use modules::sound::Config as SoundConfig;
use modules::temperature::Config as TemperatureConfig;
use modules::wired::Config as WiredConfig;
use modules::wireless::Config as WirelessConfig;
use pulse::Pulse;
use serde::{Deserialize, Serialize};
use sound::Config as SoundConfig;
use std::fs;
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use temperature::Config as TemperatureConfig;
use wired::Config as WiredConfig;
use wireless::Config as WirelessConfig;

#[derive(Debug)]
pub struct ModuleMsg(char, Option<String>, Option<String>);
Expand Down Expand Up @@ -129,6 +122,10 @@ impl<'a> Baru<'a> {
println!("{}", output);
Ok(())
}

pub fn modules(&self) -> Vec<&str> {
self.modules.iter().map(|m| m.module.name()).collect()
}
}

fn parse_format(format: &str) -> Vec<MarkupMatch> {
Expand All @@ -144,20 +141,6 @@ fn parse_format(format: &str) -> Vec<MarkupMatch> {
matches
}

fn read_and_trim(file: &str) -> Result<String, Error> {
let content = fs::read_to_string(file)
.map_err(|err| format!("error while reading the file \"{}\": {}", file, err))?;
Ok(content.trim().to_string())
}

fn read_and_parse(file: &str) -> Result<i32, Error> {
let content = read_and_trim(file)?;
let data = content
.parse::<i32>()
.map_err(|err| format!("error while parsing the file \"{}\": {}", file, err))?;
Ok(data)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
89 changes: 45 additions & 44 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,68 +2,69 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use anyhow::{Context, Result};
use baru::cli::Cli;
use baru::pulse::Pulse;
use baru::{Baru, Config};
use baru::{trace, util, Baru, Config};
use clap::Parser;
use std::env;
use std::fs;
use std::io::Error;
use std::process;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tracing::{debug, error, info};

const XDG_CONFIG_HOME: &str = "XDG_CONFIG_HOME";
const APP_DIR: &str = "baru";
const CONFIG_FILE: &str = "baru.yaml";
const TICK_RATE: Duration = Duration::from_millis(50);

fn print_out_err(message: &str) {
println!("{}", message);
eprintln!("{}", message);
}
fn main() -> Result<()> {
let cli = Cli::parse();
trace::init(cli.logs).context("failed to init tracing")?;

let home = env::var("HOME")?;
let mut config_dir = env::var(XDG_CONFIG_HOME)
.map(PathBuf::from)
.unwrap_or_else(|_| Path::new(&home).join(".config"));
config_dir.push(APP_DIR);
util::check_dir(&config_dir)?;

let config_file = config_dir.join(CONFIG_FILE);
info!("config file: {:?}", config_file);
let content = fs::read_to_string(config_file)
.inspect_err(|e| error!("failed to read config file: {}", e))?;
let config: Config = serde_yaml::from_str(&content)
.inspect_err(|e| error!("failed to parse config file: {}", e))?;
debug!("{:#?}", config);

fn main() -> Result<(), Error> {
let home = env::var("HOME").unwrap_or_else(|err| {
print_out_err(&format!("baru: environment variable HOME, {}", err));
process::exit(1);
});
let config_path = env::var("XDG_CONFIG_HOME").unwrap_or_else(|_| format!("{}/.config", home));
let content =
fs::read_to_string(format!("{}/baru/baru.yaml", config_path)).unwrap_or_else(|err| {
print_out_err(&format!(
"baru: error while reading the config file, {}",
err
));
process::exit(1);
});
let config: Config = serde_yaml::from_str(&content).unwrap_or_else(|err| {
print_out_err(&format!(
"baru: error while deserializing the config file, {}",
err
));
process::exit(1);
});
let tick = match config.tick {
Some(ms) => Duration::from_millis(ms as u64),
None => TICK_RATE,
};
let pulse = Arc::new(Mutex::new(Pulse::new(&config).unwrap_or_else(|err| {
print_out_err(&format!("baru: error while creating pulse module, {}", err));
process::exit(1);
})));
let mut baru = Baru::with_config(&config, &pulse).unwrap_or_else(|err| {
print_out_err(&format!("baru: {}", err));
process::exit(1);
});
baru.start().unwrap_or_else(|err| {
print_out_err(&format!("baru: {}", err));
process::exit(1);
});
let pulse = Arc::new(Mutex::new(Pulse::new(&config).inspect_err(|e| {
error!("baru: error while creating pulse module, {}", e);
})?));
let mut baru = Baru::with_config(&config, &pulse)
.inspect_err(|e| error!("failed to create baru instance {}", e))?;
info!("baru instance initialized");

let modules = baru.modules();
info!("modules registered: {}", modules.len());
debug!("modules: {:?}", modules);

baru.start()
.inspect_err(|e| error!("failed to start {}", e))?;
info!("started");
let mut iteration_start: Instant;
let mut iteration_end: Duration;

info!("launching main loop");
loop {
iteration_start = Instant::now();
baru.update().unwrap_or_else(|err| {
print_out_err(&format!("baru: {}", err));
process::exit(1);
});
baru.update()
.inspect_err(|e| error!("failed to update: {}", e))?;
iteration_end = iteration_start.elapsed();
if iteration_end < tick {
thread::sleep(tick - iteration_end);
Expand Down
22 changes: 11 additions & 11 deletions src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use crate::battery::Battery;
use crate::brightness::Brightness;
use crate::cpu::Cpu;
use crate::cpu_freq::CpuFreq;
use crate::date_time::DateTime;
use crate::error::Error;
use crate::memory::Memory;
use crate::mic::Mic;
use crate::sound::Sound;
use crate::temperature::Temperature;
use crate::wired::Wired;
use crate::wireless::Wireless;
use crate::modules::battery::Battery;
use crate::modules::brightness::Brightness;
use crate::modules::cpu::Cpu;
use crate::modules::cpu_freq::CpuFreq;
use crate::modules::date_time::DateTime;
use crate::modules::memory::Memory;
use crate::modules::mic::Mic;
use crate::modules::sound::Sound;
use crate::modules::temperature::Temperature;
use crate::modules::wired::Wired;
use crate::modules::wireless::Wireless;
use crate::Config;
use crate::ModuleMsg;
use crate::Pulse;
Expand Down
3 changes: 3 additions & 0 deletions src/battery.rs → src/modules/battery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tracing::{debug, instrument};

const PLACEHOLDER: &str = "-";
const SYS_PATH: &str = "/sys/class/power_supply/";
Expand Down Expand Up @@ -173,13 +174,15 @@ impl<'a> Bar for Battery<'a> {
}
}

#[instrument(skip_all)]
pub fn run(
key: char,
main_config: MainConfig,
_: Arc<Mutex<Pulse>>,
tx: Sender<ModuleMsg>,
) -> Result<(), Error> {
let config = InternalConfig::try_from(&main_config)?;
debug!("{:#?}", config);
let mut iteration_start: Instant;
let mut iteration_end: Duration;
loop {
Expand Down
6 changes: 5 additions & 1 deletion src/brightness.rs → src/modules/brightness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@

use crate::error::Error;
use crate::module::{Bar, RunPtr};
use crate::util::read_and_parse;
use crate::Pulse;
use crate::{read_and_parse, Config as MainConfig, ModuleMsg};
use crate::{Config as MainConfig, ModuleMsg};
use serde::{Deserialize, Serialize};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tracing::{debug, instrument};

const PLACEHOLDER: &str = "-";
const SYS_PATH: &str = "/sys/devices/pci0000:00/0000:00:02.0/drm/card0/card0-eDP-1/intel_backlight";
Expand Down Expand Up @@ -101,13 +103,15 @@ impl<'a> Bar for Brightness<'a> {
}
}

#[instrument(skip_all)]
pub fn run(
key: char,
main_config: MainConfig,
_: Arc<Mutex<Pulse>>,
tx: Sender<ModuleMsg>,
) -> Result<(), Error> {
let config = InternalConfig::from(&main_config);
debug!("{:#?}", config);
let mut iteration_start: Instant;
let mut iteration_end: Duration;
loop {
Expand Down
3 changes: 3 additions & 0 deletions src/cpu.rs → src/modules/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tracing::{debug, instrument};

const PLACEHOLDER: &str = "-";
const PROC_STAT: &str = "/proc/stat";
Expand Down Expand Up @@ -115,13 +116,15 @@ impl<'a> Bar for Cpu<'a> {
}
}

#[instrument(skip_all)]
pub fn run(
key: char,
main_config: MainConfig,
_: Arc<Mutex<Pulse>>,
tx: Sender<ModuleMsg>,
) -> Result<(), Error> {
let config = InternalConfig::from(&main_config);
debug!("{:#?}", config);
let mut prev_idle = 0;
let mut prev_total = 0;
let mut iteration_start: Instant;
Expand Down
Loading

0 comments on commit a92dcfc

Please sign in to comment.