From f5d76fbbcdb5a3b1c304d78a7c25286d0016e2ab Mon Sep 17 00:00:00 2001 From: Sven Stucki Date: Fri, 2 Sep 2016 01:43:30 +0200 Subject: [PATCH] Catch all command line parsing errors, properly exit on --help --- rwgame/RWGame.cpp | 26 +++++++++++++++++--------- rwgame/main.cpp | 5 +++++ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/rwgame/RWGame.cpp b/rwgame/RWGame.cpp index fc768efa..c3db01fd 100644 --- a/rwgame/RWGame.cpp +++ b/rwgame/RWGame.cpp @@ -50,6 +50,7 @@ RWGame::RWGame(int argc, char* argv[]) bool fullscreen = false; bool newgame = false; bool test = false; + bool help = false; std::string startSave; std::string benchFile; @@ -64,18 +65,25 @@ RWGame::RWGame(int argc, char* argv[]) ("newgame,n", "Directly start a new game") ("test,t", "Starts a new game in a test location") ("load,l", po::value(), "Load save file") - ("benchmark,b", po::value(), "Run benchmark and store results in file") + ("benchmark,b", po::value(), "Run benchmark from file") ; po::variables_map vm; - po::store(po::parse_command_line(argc, argv, desc), vm); - po::notify(vm); - - if( vm.count("help") ) + try { - // TODO: This is a hack - std::cout << desc << std::endl; - throw std::runtime_error("Terminate"); + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + } + catch (po::error& ex) + { + help = true; + std::cout << "Error parsing arguments: " << ex.what() << std::endl; + } + + if( help || vm.count("help") ) + { + std::cout << desc; + throw std::invalid_argument(""); } if( vm.count("width") ) { @@ -178,7 +186,7 @@ RWGame::RWGame(int argc, char* argv[]) { loading->setNextState(new MenuState(this)); } - + StateManager::get().enter(loading); log.info("Game", "Started"); diff --git a/rwgame/main.cpp b/rwgame/main.cpp index 1edcefa0..88cdce1a 100644 --- a/rwgame/main.cpp +++ b/rwgame/main.cpp @@ -8,6 +8,11 @@ int main(int argc, char* argv[]) RWGame game(argc, argv); return game.run(); + } catch (std::invalid_argument& ex) { + // This exception is thrown when either an invalid command line option + // or a --help is found. The RWGame constructor prints a usage message + // in this case and then throws this exception. + return -2; } catch (std::runtime_error& ex) { // Catch runtime_error as these are fatal issues the user may want to // know about like corrupted files or GL initialisation failure.