Skip to content

Commit 08e2947

Browse files
committed
Reduce amount of blocking in blocks
Replaced `exists` with `try_exists`
1 parent 4dd8ae4 commit 08e2947

File tree

9 files changed

+69
-31
lines changed

9 files changed

+69
-31
lines changed

src/blocks/amd_gpu.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ pub async fn run(config: &Config, api: &CommonApi) -> Result<()> {
6363
};
6464

6565
let device = match &config.device {
66-
Some(name) => Device::new(name)?,
66+
Some(name) => Device::new(name).await?,
6767
None => Device::default_card()
6868
.await
6969
.error("failed to get default GPU")?
@@ -121,10 +121,13 @@ struct GpuInfo {
121121
}
122122

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

127-
if !path.exists() {
127+
if !tokio::fs::try_exists(&path)
128+
.await
129+
.error("Unable to stat file")?
130+
{
128131
Err(Error::new(format!("Device {name} not found")))
129132
} else {
130133
Ok(Self { path })
@@ -185,9 +188,9 @@ impl Device {
185188
mod tests {
186189
use super::*;
187190

188-
#[test]
189-
fn test_non_existing_gpu_device() {
190-
let device = Device::new("/nope");
191+
#[tokio::test]
192+
async fn test_non_existing_gpu_device() {
193+
let device = Device::new("/nope").await;
191194
assert!(device.is_err());
192195
}
193196
}

src/blocks/calendar.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ pub async fn run(config: &Config, api: &CommonApi) -> Result<()> {
295295
let warning_threshold = Duration::try_seconds(config.warning_threshold.into())
296296
.error("Invalid warning threshold configuration")?;
297297

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

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

@@ -424,7 +424,8 @@ impl Source {
424424
credentials_path,
425425
}) => {
426426
let credentials = if let Some(path) = credentials_path {
427-
util::deserialize_toml_file(path.expand()?.to_string())
427+
util::async_deserialize_toml_file(path.expand()?.to_string())
428+
.await
428429
.error("Failed to read basic credentials file")?
429430
} else {
430431
credentials.clone()
@@ -440,7 +441,8 @@ impl Source {
440441
}
441442
AuthConfig::OAuth2(oauth2) => {
442443
let credentials = if let Some(path) = &oauth2.credentials_path {
443-
util::deserialize_toml_file(path.expand()?.to_string())
444+
util::async_deserialize_toml_file(path.expand()?.to_string())
445+
.await
444446
.error("Failed to read oauth2 credentials file")?
445447
} else {
446448
oauth2.credentials.clone()

src/blocks/packages/apt.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,10 @@ impl Apt {
5050
async fn setup(&mut self) -> Result<()> {
5151
let mut cache_dir = env::temp_dir();
5252
cache_dir.push("i3rs-apt");
53-
if !cache_dir.exists() {
53+
if !tokio::fs::try_exists(&cache_dir)
54+
.await
55+
.error("Unable to stat file")?
56+
{
5457
create_dir_all(&cache_dir)
5558
.await
5659
.error("Failed to create temp dir")?;

src/blocks/packages/pacman.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,10 @@ impl Backend for Pacman {
7272

7373
// Create symlink to local cache in `checkup-db` if required
7474
let local_cache = PACMAN_UPDATES_DB.join("local");
75-
if !local_cache.exists() {
75+
if !tokio::fs::try_exists(&local_cache)
76+
.await
77+
.error("Unable to stat file")?
78+
{
7679
symlink(PACMAN_DB.join("local"), local_cache)
7780
.await
7881
.error("Failed to created required symlink")?;

src/icons.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ impl Icons {
121121
if file == "none" {
122122
Ok(Icons::default())
123123
} else {
124-
let file = util::find_file(file, Some("icons"), Some("toml"))
124+
let file = util::find_file(file, Some("icons"), Some("toml"))?
125125
.or_error(|| format!("Icon set '{file}' not found"))?;
126126
Ok(Icons(util::deserialize_toml_file(file)?))
127127
}

src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ fn main() {
3131
.build()
3232
.unwrap()
3333
.block_on(async move {
34-
let config_path = util::find_file(&args.config, None, Some("toml"))
34+
let config_path = util::find_file(&args.config, None, Some("toml"))?
3535
.or_error(|| format!("Configuration file '{}' not found", args.config))?;
3636
let mut config: Config = util::deserialize_toml_file(&config_path)?;
3737
let blocks = std::mem::take(&mut config.blocks);

src/netlink.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ impl NetDevice {
7777
let path = Path::new("/sys/class/net").join(&iface.name);
7878
let tun = iface.name.starts_with("tun")
7979
|| iface.name.starts_with("tap")
80-
|| path.join("tun_flags").exists();
80+
|| tokio::fs::try_exists(path.join("tun_flags"))
81+
.await
82+
.error("Unable to stat file")?;
8183
let (wg, ppp) = util::read_file(path.join("uevent"))
8284
.await
8385
.map_or((false, false), |c| {

src/themes.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ impl TryFrom<ThemeUserConfig> for Theme {
140140

141141
fn try_from(user_config: ThemeUserConfig) -> Result<Self, Self::Error> {
142142
let name = user_config.theme.as_deref().unwrap_or("plain");
143-
let file = util::find_file(name, Some("themes"), Some("toml"))
143+
let file = util::find_file(name, Some("themes"), Some("toml"))?
144144
.or_error(|| format!("Theme '{name}' not found"))?;
145145
let theme: ThemeInner = util::deserialize_toml_file(file)?;
146146
let mut theme = Theme(theme);

src/util.rs

Lines changed: 41 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,15 @@ use crate::errors::*;
1414
/// - Then try `/usr/share/`
1515
///
1616
/// Automatically append an extension if not presented.
17-
pub fn find_file(file: &str, subdir: Option<&str>, extension: Option<&str>) -> Option<PathBuf> {
17+
pub fn find_file(
18+
file: &str,
19+
subdir: Option<&str>,
20+
extension: Option<&str>,
21+
) -> Result<Option<PathBuf>> {
1822
let file = Path::new(file);
1923

20-
if file.is_absolute() && file.exists() {
21-
return Some(file.to_path_buf());
24+
if file.is_absolute() && file.try_exists().error("Unable to stat file")? {
25+
return Ok(Some(file.to_path_buf()));
2226
}
2327

2428
// Try XDG_CONFIG_HOME (e.g. `~/.config`)
@@ -28,8 +32,8 @@ pub fn find_file(file: &str, subdir: Option<&str>, extension: Option<&str>) -> O
2832
xdg_config.push(subdir);
2933
}
3034
xdg_config.push(file);
31-
if let Some(file) = exists_with_opt_extension(&xdg_config, extension) {
32-
return Some(file);
35+
if let Some(file) = exists_with_opt_extension(&xdg_config, extension)? {
36+
return Ok(Some(file));
3337
}
3438
}
3539

@@ -40,8 +44,8 @@ pub fn find_file(file: &str, subdir: Option<&str>, extension: Option<&str>) -> O
4044
xdg_data.push(subdir);
4145
}
4246
xdg_data.push(file);
43-
if let Some(file) = exists_with_opt_extension(&xdg_data, extension) {
44-
return Some(file);
47+
if let Some(file) = exists_with_opt_extension(&xdg_data, extension)? {
48+
return Ok(Some(file));
4549
}
4650
}
4751

@@ -51,26 +55,26 @@ pub fn find_file(file: &str, subdir: Option<&str>, extension: Option<&str>) -> O
5155
usr_share_path.push(subdir);
5256
}
5357
usr_share_path.push(file);
54-
if let Some(file) = exists_with_opt_extension(&usr_share_path, extension) {
55-
return Some(file);
58+
if let Some(file) = exists_with_opt_extension(&usr_share_path, extension)? {
59+
return Ok(Some(file));
5660
}
5761

58-
None
62+
Ok(None)
5963
}
6064

61-
fn exists_with_opt_extension(file: &Path, extension: Option<&str>) -> Option<PathBuf> {
62-
if file.exists() {
63-
return Some(file.into());
65+
fn exists_with_opt_extension(file: &Path, extension: Option<&str>) -> Result<Option<PathBuf>> {
66+
if file.try_exists().error("Unable to stat file")? {
67+
return Ok(Some(file.into()));
6468
}
6569
// If file has no extension, test with given extension
6670
if let (None, Some(extension)) = (file.extension(), extension) {
6771
let file = file.with_extension(extension);
6872
// Check again with extension added
69-
if file.exists() {
70-
return Some(file);
73+
if file.try_exists().error("Unable to stat file")? {
74+
return Ok(Some(file));
7175
}
7276
}
73-
None
77+
Ok(None)
7478
}
7579

7680
pub async fn new_dbus_connection() -> Result<zbus::Connection> {
@@ -95,6 +99,27 @@ where
9599
let contents = std::fs::read_to_string(path)
96100
.or_error(|| format!("Failed to read file: {}", path.display()))?;
97101

102+
deserialize_toml_file_string(contents, path)
103+
}
104+
105+
pub async fn async_deserialize_toml_file<T, P>(path: P) -> Result<T>
106+
where
107+
T: DeserializeOwned,
108+
P: AsRef<Path>,
109+
{
110+
let path = path.as_ref();
111+
112+
let contents = read_file(path)
113+
.await
114+
.or_error(|| format!("Failed to read file: {}", path.display()))?;
115+
116+
deserialize_toml_file_string(contents, path)
117+
}
118+
119+
fn deserialize_toml_file_string<T>(contents: String, path: &Path) -> Result<T>
120+
where
121+
T: DeserializeOwned,
122+
{
98123
toml::from_str(&contents).map_err(|err| {
99124
let location_msg = err
100125
.span()

0 commit comments

Comments
 (0)