Skip to content

Commit

Permalink
Remove unwraps (#316)
Browse files Browse the repository at this point in the history
Remove all unwraps and clippy warnings
  • Loading branch information
PhilipK authored Jan 7, 2023
1 parent 59b67a1 commit f6188b1
Show file tree
Hide file tree
Showing 30 changed files with 691 additions and 538 deletions.
8 changes: 4 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ mod tests {
// Parameters for set environment 'XDG_CONFIG_HOME'
std::env::set_var(
"XDG_CONFIG_HOME",
std::env::var("HOME").unwrap() + "/.config/boilr",
std::env::var("HOME").unwrap_or_default() + "/.config/boilr",
);

let xdg_config_home = std::env::var("XDG_CONFIG_HOME").unwrap();
let xdg_config_home = std::env::var("XDG_CONFIG_HOME").unwrap_or_default();
let config_path = get_config_folder();
let test_path = PathBuf::from(xdg_config_home);

Expand All @@ -79,11 +79,11 @@ mod tests {
fn check_return_config_path() {
std::env::set_var(
"XDG_CONFIG_HOME",
std::env::var("HOME").unwrap() + "/.config/boilr",
std::env::var("HOME").unwrap_or_default() + "/.config/boilr",
);

let config_path = get_config_folder();
let current_path = std::env::var("HOME").unwrap() + "/.config/boilr";
let current_path = std::env::var("HOME").unwrap_or_default() + "/.config/boilr";

assert_eq!(config_path, PathBuf::from(current_path));
}
Expand Down
8 changes: 6 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#![deny(clippy::unwrap_in_result)]
#![deny(clippy::get_unwrap)]
#![deny(clippy::unwrap_used)]

mod config;
mod migration;
mod platforms;
Expand All @@ -16,9 +20,9 @@ fn main() -> Result<()> {

let args: Vec<String> = std::env::args().collect();
if args.contains(&"--no-ui".to_string()) {
ui::run_sync();
ui::run_sync()?;
} else {
ui::run_ui(args);
ui::run_ui(args)?;
}
Ok(())
}
Expand Down
4 changes: 3 additions & 1 deletion src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ pub fn migrate_config() {
if let Ok(mut settings) = crate::settings::Settings::new() {
settings.config_version = Some(1);
let platforms = get_platforms();
save_settings(&settings, &platforms);
if let Err(err) = save_settings(&settings, &platforms){
eprintln!("Failed to load settings {:?}", err);
}
}
}
}
3 changes: 3 additions & 0 deletions src/platforms/egs/manifest_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,9 @@ impl ManifestItem {
#[cfg(test)]
mod tests {

//Okay to unwrap in tests
#![allow(clippy::unwrap_in_result)]
#![allow(clippy::unwrap_used)]
use super::*;

#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/platforms/gog/gog_game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl From<GogShortcut> for ShortcutOwned {
let icon_file = format!("goggame-{}.ico", gogs.game_id);
let icon_path = Path::new(&gogs.game_folder).join(icon_file);
let icon = if icon_path.exists() {
icon_path.to_str().unwrap().to_string()
icon_path.to_string_lossy().to_string()
} else {
"".to_string()
};
Expand Down
3 changes: 3 additions & 0 deletions src/platforms/itch/butler_db_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ fn parse_path(i: &[u8]) -> nom::IResult<&[u8], DbPaths> {

#[cfg(test)]
mod tests {
//Okay to unwrap in tests
#![allow(clippy::unwrap_in_result)]
#![allow(clippy::unwrap_used)]

use super::*;

Expand Down
2 changes: 1 addition & 1 deletion src/platforms/itch/itch_game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub struct ItchGame {
impl From<ItchGame> for ShortcutOwned {
fn from(game: ItchGame) -> Self {
let exe = Path::new(&game.install_path).join(&game.executable);
let exe = exe.to_str().unwrap().to_string();
let exe = exe.to_string_lossy().to_string();
let shortcut = Shortcut::new(
"0",
game.title.as_str(),
Expand Down
26 changes: 14 additions & 12 deletions src/platforms/itch/itch_platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl ItchPlatform {
));
}

let shortcut_bytes = std::fs::read(&itch_db_location).unwrap();
let shortcut_bytes = std::fs::read(&itch_db_location)?;

let paths = match parse_butler_db(&shortcut_bytes) {
Ok((_, shortcuts)) => Ok(shortcuts),
Expand Down Expand Up @@ -59,17 +59,19 @@ fn dbpath_to_game(paths: &DbPaths) -> Option<ItchGame> {
.iter()
.filter(|p| Path::new(&paths.base_path).join(p).is_executable())
.find_map(|executable| {
let gz_bytes = std::fs::read(&recipt).unwrap();
let mut d = GzDecoder::new(gz_bytes.as_slice());
let mut s = String::new();
d.read_to_string(&mut s).unwrap();

let receipt_op: Option<Receipt> = serde_json::from_str(&s).ok();
receipt_op.map(|re| ItchGame {
install_path: paths.base_path.to_owned(),
executable: executable.to_owned(),
title: re.game.title,
})
if let Ok(gz_bytes) = std::fs::read(&recipt) {
let mut d = GzDecoder::new(gz_bytes.as_slice());
let mut s = String::new();
if d.read_to_string(&mut s).is_ok() {
let receipt_op: Option<Receipt> = serde_json::from_str(&s).ok();
return receipt_op.map(|re| ItchGame {
install_path: paths.base_path.to_owned(),
executable: executable.to_owned(),
title: re.game.title,
});
}
}
None
})
}

Expand Down
6 changes: 1 addition & 5 deletions src/platforms/origin/origin_platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,7 @@ impl NeedsPorton<OriginPlatform> for OriginGame {

impl OriginPlatform {
fn get_shortcuts(&self) -> eyre::Result<Vec<OriginGame>> {
let origin_folders = get_default_locations();
if origin_folders.is_none() {
return Err(eyre::format_err!("Default path not found"));
}
let origin_folders = origin_folders.unwrap();
let origin_folders = get_default_locations().ok_or(eyre::format_err!("Default path not found"))?;
let origin_folder = origin_folders.local_content_path;
let origin_exe = origin_folders.exe_path;
let game_folders = origin_folder.join("LocalContent").read_dir()?;
Expand Down
7 changes: 4 additions & 3 deletions src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ pub fn load_setting_sections() -> eyre::Result<HashMap<String, String>> {
Ok(result)
}

pub fn save_settings(settings: &Settings, platforms: &Platforms) {
let mut toml = toml::to_string(&settings).unwrap();
pub fn save_settings(settings: &Settings, platforms: &Platforms) -> eyre::Result<()>{
let mut toml = toml::to_string(&settings)?;

for platform in platforms {
let section_name = format!("[{}]", platform.code_name());
Expand All @@ -82,7 +82,8 @@ pub fn save_settings(settings: &Settings, platforms: &Platforms) {
}

let config_path = crate::config::get_config_file();
std::fs::write(config_path, toml).unwrap();
std::fs::write(config_path, toml)?;
Ok(())
}

fn add_sections(
Expand Down
33 changes: 17 additions & 16 deletions src/steam/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ pub fn write_collections<S: AsRef<str>>(
&vdf_collections,
);
if let Some(new_string) = new_string {
std::fs::write(path, new_string).unwrap();
std::fs::write(path, new_string)?;
}
}
}
Expand Down Expand Up @@ -242,22 +242,19 @@ fn get_categories<S: AsRef<str>>(
Ok(res)
}

fn open_db() -> Result<DB, Box<dyn Error>> {
let location = get_level_db_location();
fn open_db() -> eyre::Result<DB> {
use eyre::eyre;
let location = get_level_db_location().ok_or(eyre!("Collections db not found"))?;
let options = Options::default();
let open_res = DB::open(location.unwrap(), options);
if let Err(e) = &open_res {
match &e.code {
rusty_leveldb::StatusCode::LockError => {
println!("Could not lock the steam level database, make sure steam is turned off when running synchronizations");
}
rusty_leveldb::StatusCode::NotFound => {
println!("Could not find the steam level database, try to open and close steam once and synchronize again");
}
_ => {}
};
}
Ok(open_res?)
let open_res = DB::open(location, options);
open_res.map_err(|e|{
use rusty_leveldb::StatusCode::*;
match e.code{
LockError => eyre!("Could not lock the steam level database, make sure steam is turned off when running synchronizations"),
NotFound => eyre!("Could not find the steam level database, try to open and close steam once and synchronize again"),
_ => eyre!("Failed opening collections file: {}",e.err),
}
})
}

fn get_namespace_keys<S: AsRef<str>>(steamid: S, db: &mut DB) -> HashSet<String> {
Expand Down Expand Up @@ -394,6 +391,10 @@ pub struct VdfCollection {

#[cfg(test)]
mod tests {
//Allow unwraps in test
#![allow(clippy::unwrap_in_result)]
#![allow(clippy::get_unwrap)]
#![allow(clippy::unwrap_used)]
use super::*;

#[test]
Expand Down
20 changes: 13 additions & 7 deletions src/steam/installed_games.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,25 @@ fn parse_manifest_string<S: AsRef<str>>(string: S) -> Option<SteamGameInfo> {
let app_id_line = lines.find(|l| l.contains("\"appid\""));
let name_line = lines.find(|l| l.contains("\"name\""));
match (app_id_line, name_line) {
(Some(app_id_line), Some(name_line)) => Some(SteamGameInfo {
name: name_line[10..name_line.len() - 1].to_string(),
appid: app_id_line[11..app_id_line.len() - 1]
.to_string()
.parse()
.unwrap(),
}),
(Some(app_id_line), Some(name_line)) => {
let appid = app_id_line[11..app_id_line.len() - 1].to_string().parse();
match appid {
Ok(appid) => Some(SteamGameInfo {
name: name_line[10..name_line.len() - 1].to_string(),
appid,
}),
Err(_) => None,
}
}
_ => None,
}
}

#[cfg(test)]
mod tests {
//Okay to unwrap in tests
#![allow(clippy::unwrap_in_result)]
#![allow(clippy::unwrap_used)]

use super::*;

Expand Down
8 changes: 6 additions & 2 deletions src/steam/proton_vdf_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ use std::path::Path;

use nom::FindSubstring;

pub fn setup_proton_games<B: AsRef<str>>(games: &[B]) {
pub fn setup_proton_games<B: AsRef<str>>(games: &[B]) -> eyre::Result<()>{
if let Ok(home) = std::env::var("HOME") {
let config_file = Path::new(&home).join(".local/share/Steam/config/config.vdf");
if config_file.exists() {
if let Ok(config_content) = std::fs::read_to_string(&config_file) {
let new_string = enable_proton_games(config_content, games);
std::fs::write(config_file, new_string).unwrap();
std::fs::write(config_file, new_string)?;
}
}
}
Ok(())
}

fn enable_proton_games<S: AsRef<str>, B: AsRef<str>>(vdf_content: S, games: &[B]) -> String {
Expand Down Expand Up @@ -96,6 +97,9 @@ fn find_indexes<S: AsRef<str>>(vdf_content: S) -> Option<SectionInfo> {
#[cfg(target_family = "unix")]
mod tests {

//Okay to unwrap in tests
#![allow(clippy::unwrap_in_result)]
#![allow(clippy::unwrap_used)]
use super::*;

#[test]
Expand Down
40 changes: 20 additions & 20 deletions src/steam/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ use steam_shortcuts_util::{parse_shortcuts, shortcut::ShortcutOwned};

use super::SteamSettings;

pub fn get_shortcuts_for_user(user: &SteamUsersInfo) -> ShortcutInfo {
pub fn get_shortcuts_for_user(user: &SteamUsersInfo) -> eyre::Result<ShortcutInfo> {
let mut shortcuts = vec![];

let new_path = match &user.shortcut_path {
Some(shortcut_path) => {
let content = std::fs::read(shortcut_path).unwrap();
let content = std::fs::read(shortcut_path)?;
shortcuts = parse_shortcuts(content.as_slice())
.unwrap()
.map_err(|e| eyre::format_err!("Could not parse shortcuts: {:?}", e))?
.iter()
.map(|s| s.to_owned())
.collect();
Expand All @@ -27,15 +27,15 @@ pub fn get_shortcuts_for_user(user: &SteamUsersInfo) -> ShortcutInfo {
user.steam_user_data_folder
);
let path = Path::new(&user.steam_user_data_folder).join("config");
std::fs::create_dir_all(path.clone()).unwrap();
std::fs::create_dir_all(path.clone())?;
path.join("shortcuts.vdf")
}
};

ShortcutInfo {
Ok(ShortcutInfo {
shortcuts,
path: new_path,
}
})
}

pub struct ShortcutInfo {
Expand All @@ -51,22 +51,22 @@ pub struct SteamUsersInfo {
}

/// Get the paths to the steam users shortcuts (one for each user)
pub fn get_shortcuts_paths(
settings: &SteamSettings,
) -> Result<Vec<SteamUsersInfo>, Box<dyn Error + Sync + Send>> {
pub fn get_shortcuts_paths(settings: &SteamSettings) -> eyre::Result<Vec<SteamUsersInfo>> {
let steam_path_str = get_steam_path(settings)?;
let steam_path = Path::new(&steam_path_str);
if !steam_path.exists() {
return Result::Err(Box::new(SteamFolderNotFound {
location_tried: format!("{:?}", steam_path),
}));
return Err(eyre::format_err!(
"Steam folder not found at: {:?}",
steam_path
));
}

let user_data_path = steam_path.join("userdata");
if !user_data_path.exists() {
return Result::Err(Box::new(SteamFolderNotFound {
location_tried: format!("{:?}", user_data_path),
}));
return Err(eyre::format_err!(
"Steam user data folder not found at: {:?}",
user_data_path
));
}

if !user_data_path.exists() {}
Expand All @@ -89,7 +89,7 @@ pub fn get_shortcuts_paths(
if shortcuts_path.exists() {
return SteamUsersInfo {
steam_user_data_folder: folder_string,
shortcut_path: Some(shortcuts_path.to_str().unwrap().to_string()),
shortcut_path: Some(shortcuts_path.to_string_lossy().to_string()),
user_id,
};
} else {
Expand All @@ -104,7 +104,7 @@ pub fn get_shortcuts_paths(
Ok(users_info)
}

pub fn get_steam_path(settings: &SteamSettings) -> Result<String, Box<dyn Error + Sync + Send>> {
pub fn get_steam_path(settings: &SteamSettings) -> eyre::Result<String> {
let user_location = settings.location.clone();
let steam_path_str = match user_location {
Some(location) => location,
Expand All @@ -113,7 +113,7 @@ pub fn get_steam_path(settings: &SteamSettings) -> Result<String, Box<dyn Error
Ok(steam_path_str)
}

pub fn get_default_location() -> Result<String, Box<dyn Error + Sync + Send>> {
pub fn get_default_location() -> eyre::Result<String> {
#[cfg(target_os = "windows")]
let path_string = {
let key = "PROGRAMFILES(X86)";
Expand Down Expand Up @@ -198,8 +198,8 @@ impl Error for SteamUsersDataEmpty {
self.location_tried.as_str()
}
}
pub fn get_users_images(user: &SteamUsersInfo) -> Result<Vec<String>, Box<dyn Error>> {
let grid_folder = Path::new(user.steam_user_data_folder.as_str()).join("config/grid");
pub fn get_users_images(data_folder: &str) -> Result<Vec<String>, Box<dyn Error>> {
let grid_folder = Path::new(data_folder).join("config/grid");
if !grid_folder.exists() {
std::fs::create_dir_all(&grid_folder)?;
}
Expand Down
Loading

0 comments on commit f6188b1

Please sign in to comment.