Skip to content

Commit

Permalink
Reduce amount of blocking in blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
bim9262 committed Oct 20, 2024
1 parent 005233a commit 0fa560f
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 13 deletions.
12 changes: 6 additions & 6 deletions src/blocks/amd_gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub async fn run(config: &Config, api: &CommonApi) -> Result<()> {
};

let device = match &config.device {
Some(name) => Device::new(name)?,
Some(name) => Device::new(name).await?,
None => Device::default_card()
.await
.error("failed to get default GPU")?
Expand Down Expand Up @@ -121,10 +121,10 @@ struct GpuInfo {
}

impl Device {
fn new(name: &str) -> Result<Self, Error> {
async fn new(name: &str) -> Result<Self, Error> {
let path = PathBuf::from(format!("/sys/class/drm/{name}/device"));

if !path.exists() {
if !file_exists(&path).await {
Err(Error::new(format!("Device {name} not found")))
} else {
Ok(Self { path })
Expand Down Expand Up @@ -185,9 +185,9 @@ impl Device {
mod tests {
use super::*;

#[test]
fn test_non_existing_gpu_device() {
let device = Device::new("/nope");
#[tokio::test]
async fn test_non_existing_gpu_device() {
let device = Device::new("/nope").await;
assert!(device.is_err());
}
}
8 changes: 5 additions & 3 deletions src/blocks/calendar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ pub async fn run(config: &Config, api: &CommonApi) -> Result<()> {
let warning_threshold = Duration::try_seconds(config.warning_threshold.into())
.error("Invalid warning threshold configuration")?;

let mut source = Source::new(source_config.clone()).await?;
let mut source = Source::new(source_config.to_owned()).await?;

let mut timer = config.fetch_interval.timer();

Expand Down Expand Up @@ -424,7 +424,8 @@ impl Source {
credentials_path,
}) => {
let credentials = if let Some(path) = credentials_path {
util::deserialize_toml_file(path.expand()?.to_string())
util::async_deserialize_toml_file(path.expand()?.to_string())
.await
.error("Failed to read basic credentials file")?
} else {
credentials.clone()
Expand All @@ -440,7 +441,8 @@ impl Source {
}
AuthConfig::OAuth2(oauth2) => {
let credentials = if let Some(path) = &oauth2.credentials_path {
util::deserialize_toml_file(path.expand()?.to_string())
util::async_deserialize_toml_file(path.expand()?.to_string())
.await
.error("Failed to read oauth2 credentials file")?
} else {
oauth2.credentials.clone()
Expand Down
2 changes: 1 addition & 1 deletion src/blocks/packages/apt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Apt {
async fn setup(&mut self) -> Result<()> {
let mut cache_dir = env::temp_dir();
cache_dir.push("i3rs-apt");
if !cache_dir.exists() {
if !file_exists(&cache_dir).await {
create_dir_all(&cache_dir)
.await
.error("Failed to create temp dir")?;
Expand Down
2 changes: 1 addition & 1 deletion src/blocks/packages/pacman.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl Backend for Pacman {

// Create symlink to local cache in `checkup-db` if required
let local_cache = PACMAN_UPDATES_DB.join("local");
if !local_cache.exists() {
if !file_exists(&local_cache).await {
symlink(PACMAN_DB.join("local"), local_cache)
.await
.error("Failed to created required symlink")?;
Expand Down
2 changes: 1 addition & 1 deletion src/blocks/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ pub use super::{BlockAction, CommonApi};
pub use crate::click::MouseButton;
pub use crate::errors::*;
pub use crate::formatting::{config::Config as FormatConfig, value::Value, Values};
pub use crate::util::{default, new_dbus_connection, new_system_dbus_connection};
pub use crate::util::{default, file_exists, new_dbus_connection, new_system_dbus_connection};
pub use crate::widget::{State, Widget};
pub use crate::wrappers::{Seconds, ShellString};
pub(crate) use crate::REQWEST_CLIENT;
Expand Down
2 changes: 1 addition & 1 deletion src/netlink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl NetDevice {
let path = Path::new("/sys/class/net").join(&iface.name);
let tun = iface.name.starts_with("tun")
|| iface.name.starts_with("tap")
|| path.join("tun_flags").exists();
|| util::file_exists(path.join("tun_flags")).await;
let (wg, ppp) = util::read_file(path.join("uevent"))
.await
.map_or((false, false), |c| {
Expand Down
25 changes: 25 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ use tokio::process::Command;

use crate::errors::*;

pub async fn file_exists(path: impl AsRef<Path>) -> bool {
tokio::fs::metadata(path).await.is_ok()
}

/// Tries to find a file in standard locations:
/// - Fist try to find a file by full path (only if path is absolute)
/// - Then try XDG_CONFIG_HOME (e.g. `~/.config`)
Expand Down Expand Up @@ -95,6 +99,27 @@ where
let contents = std::fs::read_to_string(path)
.or_error(|| format!("Failed to read file: {}", path.display()))?;

deserialize_toml_file_string(contents, path)
}

pub async fn async_deserialize_toml_file<T, P>(path: P) -> Result<T>
where
T: DeserializeOwned,
P: AsRef<Path>,
{
let path = path.as_ref();

let contents = read_file(path)
.await
.or_error(|| format!("Failed to read file: {}", path.display()))?;

deserialize_toml_file_string(contents, path)
}

fn deserialize_toml_file_string<T>(contents: String, path: &Path) -> Result<T>
where
T: DeserializeOwned,
{
toml::from_str(&contents).map_err(|err| {
let location_msg = err
.span()
Expand Down

0 comments on commit 0fa560f

Please sign in to comment.