Skip to content

Commit

Permalink
style: report errors during CLI handling
Browse files Browse the repository at this point in the history
  • Loading branch information
carrascomj committed Jan 20, 2025
1 parent 421261b commit 3741e29
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
23 changes: 16 additions & 7 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,23 @@
use bevy::prelude::{App, Entity, FileDragAndDrop};
use bevy::window::PrimaryWindow;
use std::env;
use std::io;
use std::path::PathBuf;
use thiserror::Error;

pub struct CliArgs {
pub map_path: Option<PathBuf>,
pub data_path: Option<PathBuf>,
}

#[derive(Error, Debug)]
pub enum InitCliError {
#[error("supplied path is invalid.")]
InvalidPathError(#[from] io::Error),
#[error("window not initialized.")]
UninitWindow,
}

pub fn parse_args() -> CliArgs {
let args: Vec<String> = env::args().collect();
// the last args take priority
Expand All @@ -29,28 +39,27 @@ pub fn parse_args() -> CliArgs {

/// Generate `FileDragAndDrop` such that the map and/or data
/// if supplied as CLI args are later loaded.
pub fn handle_cli_args(app: &mut App, cli_args: CliArgs) {
let Some((win, _)) = app
pub fn handle_cli_args(app: &mut App, cli_args: CliArgs) -> Result<(), InitCliError> {
let (win, _) = app
.world_mut()
.query::<(Entity, &PrimaryWindow)>()
.iter(app.world())
.next()
else {
return;
};
.ok_or(InitCliError::UninitWindow)?;
// paths are canonicalized so that they are not interpreted
// to be in the assets directory by bevy's `AssetLoader`.
if let Some(map_path) = cli_args.map_path {
app.world_mut().send_event(FileDragAndDrop::DroppedFile {
window: win,
path_buf: map_path.canonicalize().unwrap(),
path_buf: map_path.canonicalize()?,
});
}

if let Some(data_path) = cli_args.data_path {
app.world_mut().send_event(FileDragAndDrop::DroppedFile {
window: win,
path_buf: data_path.canonicalize().unwrap(),
path_buf: data_path.canonicalize()?,
});
}
Ok(())
}
8 changes: 7 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,13 @@ fn main() {
.add_plugins(legend::LegendPlugin);

let cli_args = cli::parse_args();
cli::handle_cli_args(app, cli_args);
if let Err(e) = cli::handle_cli_args(app, cli_args) {
use cli::InitCliError::*;
match e {
InvalidPathError(error) => error!("Supplied path as arg is invalid: {error}"),
UninitWindow => error!("Window was not initialized!"),
}
}

app.run();
}
Expand Down

0 comments on commit 3741e29

Please sign in to comment.