Skip to content

Commit

Permalink
More verbose error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
trumank committed Jul 21, 2023
1 parent 32b8807 commit 56e04be
Show file tree
Hide file tree
Showing 8 changed files with 124 additions and 16 deletions.
61 changes: 59 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ edition = "2021"
repository = "https://github.com/trumank/drg-mod-integration"

[dependencies]
anyhow = "1.0.71"
anyhow = { version = "1.0.71", features = ["backtrace"] }
async-trait = "0.1.68"
clap = { version = "4.3.0", features = ["derive"] }
dialoguer = "0.10.4"
Expand Down
25 changes: 20 additions & 5 deletions src/gui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,22 @@ use crate::{

use request_counter::{RequestCounter, RequestID};

pub fn gui() -> Result<()> {
pub fn gui(args: Option<Vec<String>>) -> Result<()> {
let options = eframe::NativeOptions {
initial_window_size: Some(egui::vec2(320.0, 240.0)),
..Default::default()
};
eframe::run_native(
"DRG Mod Integration",
options,
Box::new(|_cc| Box::new(App::new().unwrap())),
Box::new(|_cc| Box::new(App::new(args).unwrap())),
)
.map_err(|e| anyhow!("{e}"))?;
Ok(())
}

struct App {
args: Option<Vec<String>>,
tx: Sender<message::Message>,
rx: Receiver<message::Message>,
state: State,
Expand All @@ -65,11 +66,12 @@ struct App {
}

impl App {
fn new() -> Result<Self> {
fn new(args: Option<Vec<String>>) -> Result<Self> {
let (tx, rx) = mpsc::channel(10);
let state = State::new()?;

Ok(Self {
args,
tx,
rx,
request_counter: Default::default(),
Expand Down Expand Up @@ -575,7 +577,7 @@ impl eframe::App for App {
);
}
Err(e) => {
self.log.println(format!("{:#?}", e));
self.log.println(format!("{:#?}\n{}", e, e.backtrace()));
}
},
}
Expand All @@ -602,7 +604,7 @@ impl eframe::App for App {
);
}
Err(e) => {
self.log.println(format!("{:#?}", e));
self.log.println(format!("{:#?}\n{}", e, e.backtrace()));
}
},
}
Expand Down Expand Up @@ -645,6 +647,19 @@ impl eframe::App for App {
&& self.update_rid.is_none()
&& self.state.config.drg_pak_path.is_some(),
|ui| {
if let Some(args) = &self.args {
if ui.button("launch game").on_hover_ui(|ui| for arg in args {
ui.label(arg);
}).clicked() {
let args = args.clone();
tokio::task::spawn_blocking(move || {
let mut iter = args.iter();
std::process::Command::new(
iter.next().unwrap(),
).args(iter).spawn().unwrap();
});
}
}
ui.add_enabled_ui(self.state.config.drg_pak_path.is_some(), |ui| {
let mut button = ui.button("install mods");
if self.state.config.drg_pak_path.is_none() {
Expand Down
7 changes: 4 additions & 3 deletions src/integrate.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::collections::{HashMap, HashSet};
use std::fs::{File, OpenOptions};
use std::fs::OpenOptions;
use std::io::{self, BufReader, BufWriter, Cursor, Read, Seek};
use std::path::{Path, PathBuf};

Expand All @@ -8,6 +8,7 @@ use unreal_asset::properties::object_property::TopLevelAssetPath;
use unreal_asset::types::vector::Vector;
use unreal_asset::unversioned::ancestry::Ancestry;

use crate::open_file;
use crate::providers::{ModInfo, ReadSeek};

use unreal_asset::{
Expand Down Expand Up @@ -38,7 +39,7 @@ pub fn integrate<P: AsRef<Path>>(path_pak: P, mods: Vec<(ModInfo, PathBuf)>) ->
let path_pak = Path::join(path_paks, "FSD-WindowsNoEditor.pak");
let path_mod_pak = Path::join(path_paks, "mods_P.pak");

let mut fsd_pak_reader = BufReader::new(File::open(path_pak)?);
let mut fsd_pak_reader = BufReader::new(open_file(path_pak)?);
let fsd_pak = repak::PakReader::new_any(&mut fsd_pak_reader, None)?;

let pcb_path = (
Expand Down Expand Up @@ -83,7 +84,7 @@ pub fn integrate<P: AsRef<Path>>(path_pak: P, mods: Vec<(ModInfo, PathBuf)>) ->
let mods = mods
.into_iter()
.map(|(m, path)| {
let mut buf = get_pak_from_data(Box::new(BufReader::new(File::open(path)?)))?;
let mut buf = get_pak_from_data(Box::new(BufReader::new(open_file(path)?)))?;
let pak = repak::PakReader::new_any(&mut buf, None)?;

let mount = Path::new(pak.mount_point());
Expand Down
21 changes: 19 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
path::{Path, PathBuf},
};

use anyhow::Result;
use anyhow::{Context, Result};

use error::IntegrationError;
use providers::{ModSpecification, ProviderFactory};
Expand All @@ -23,8 +23,25 @@ pub fn find_drg_pak() -> Option<PathBuf> {
})
}

/// File::open with the file path included in any error messages
pub fn open_file<P: AsRef<Path>>(path: P) -> Result<std::fs::File> {
std::fs::File::open(&path)
.with_context(|| format!("Could not open file {}", path.as_ref().display()))
}

/// fs::read with the file path included in any error messages
pub fn read_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
std::fs::read(&path).with_context(|| format!("Could not read file {}", path.as_ref().display()))
}

/// fs::write with the file path included in any error messages
pub fn write_file<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, data: C) -> Result<()> {
std::fs::write(&path, data)
.with_context(|| format!("Could not write to file {}", path.as_ref().display()))
}

pub fn is_drg_pak<P: AsRef<Path>>(path: P) -> Result<()> {
let mut reader = std::io::BufReader::new(std::fs::File::open(path)?);
let mut reader = std::io::BufReader::new(open_file(path)?);
let pak = repak::PakReader::new_any(&mut reader, None)?;
pak.get("FSD/FSD.uproject", &mut reader)?;
Ok(())
Expand Down
17 changes: 16 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,17 @@ struct ActionIntegrateProfile {
profile: String,
}

/// Launch via steam
#[derive(Parser, Debug)]
struct ActionLaunch {
args: Vec<String>,
}

#[derive(Subcommand, Debug)]
enum Action {
Integrate(ActionIntegrate),
Profile(ActionIntegrateProfile),
Launch(ActionLaunch),
}

#[derive(Parser, Debug)]
Expand All @@ -66,6 +73,7 @@ struct Args {
}

fn main() -> Result<()> {
std::env::set_var("RUST_BACKTRACE", "1");
let rt = tokio::runtime::Runtime::new().expect("Unable to create Runtime");
let _enter = rt.enter();

Expand All @@ -80,11 +88,18 @@ fn main() -> Result<()> {
action_integrate_profile(action).await?;
Ok(())
}),
Some(Action::Launch(action)) => {
std::thread::spawn(move || {
rt.block_on(std::future::pending::<()>());
});
gui(Some(action.args))?;
Ok(())
}
None => {
std::thread::spawn(move || {
rt.block_on(std::future::pending::<()>());
});
gui()?;
gui(None)?;
Ok(())
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/providers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod modio;

use crate::error::IntegrationError;
use crate::state::config::ConfigWrapper;
use crate::write_file;

use anyhow::{Context, Result};

Expand Down Expand Up @@ -380,7 +381,7 @@ impl BlobCache {
let hash = hex::encode(hasher.finalize());

let tmp = self.path.join(format!(".{hash}"));
std::fs::write(&tmp, blob)?;
write_file(&tmp, blob)?;
std::fs::rename(tmp, self.path.join(&hash))?;

Ok(BlobRef(hash))
Expand Down
4 changes: 3 additions & 1 deletion src/state/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use anyhow::Result;

use serde::{de::DeserializeOwned, Serialize};

use crate::write_file;

/// Wrapper around an object that is read from a file on init and written on drop
pub struct ConfigWrapper<C: Default + Serialize + DeserializeOwned> {
path: PathBuf,
Expand All @@ -20,7 +22,7 @@ impl<C: Default + Serialize + DeserializeOwned> ConfigWrapper<C> {
}
}
pub fn save(&self) -> Result<()> {
std::fs::write(&self.path, serde_json::to_vec_pretty(&self.config)?)?;
write_file(&self.path, serde_json::to_vec_pretty(&self.config)?)?;
Ok(())
}
}
Expand Down

0 comments on commit 56e04be

Please sign in to comment.