Skip to content

Commit 8d6f237

Browse files
authored
refactor: extract function (#41)
Extract random file function
2 parents bfc55b8 + 0d10fb1 commit 8d6f237

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

src/wallpaper.rs

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use rand::Rng;
22
use std::{
3-
fs::{read_dir, read_to_string},
3+
fs::{read_dir, read_to_string, DirEntry},
44
path::PathBuf,
55
process::Command,
66
};
@@ -41,6 +41,11 @@ pub fn get_current_wallpaper() -> Result<File> {
4141
File::try_from(wallpaper).map_err(|msg| anyhow!("failed to get current wallpaper: {msg}"))
4242
}
4343

44+
fn get_random_file(files: Vec<&DirEntry>) -> PathBuf {
45+
let random_number = rand::rng().random_range(0..files.len());
46+
files.get(random_number).unwrap().path()
47+
}
48+
4449
/// Gets a random wallpaper from the wallpaper directory.
4550
/// It can also return a folder, which will be handled by the caller.
4651
/// Hidden files will be ignored.
@@ -68,28 +73,22 @@ pub fn get_random_wallpaper(settings: &Settings) -> Result<File> {
6873
return Err(anyhow!("no wallpapers in the wallpaper directory"));
6974
}
7075

71-
let get_path_str = |path: &PathBuf| -> Result<String> {
72-
path.to_str()
73-
.ok_or(anyhow!("failed to convert path to str"))
74-
.map(|path_str| path_str.to_owned())
75-
};
76-
7776
let path = if let Ok(current_wallpaper) = get_current_wallpaper() {
7877
let current_wallpaper_str = current_wallpaper.to_string();
7978
let files = files
8079
.iter()
8180
.filter(|entry| {
82-
let entry_path = entry.path();
83-
let entry_path_str = get_path_str(&entry_path).unwrap();
81+
let entry_path_str = entry
82+
.path()
83+
.to_str()
84+
.expect("failed to convert path to str")
85+
.to_string();
8486
entry_path_str != current_wallpaper_str
8587
})
8688
.collect::<Vec<_>>();
87-
88-
let random_number = rand::rng().random_range(0..files.len());
89-
files.get(random_number).unwrap().path()
89+
get_random_file(files)
9090
} else {
91-
let random_number = rand::rng().random_range(0..files.len());
92-
files.get(random_number).unwrap().path()
91+
get_random_file(files.iter().collect())
9392
};
9493

9594
File::new(path).ok_or(anyhow!("failed to get random wallpaper"))

0 commit comments

Comments
 (0)