#include "cmd/cmd.h" #include "utils.h" #include #include #include #include const std::map> nargs({ {"cp", {2}}, {"mv", {2}}, {"attacks", {1}}, {"attack", {3}}, {"damage", {2, 3}}, {"heal", {2}}, {"spellcasting", {2, 3, 4}}, }); void checkArgs(std::string cmd, std::vector args) { if(nargs.contains(cmd)) { auto& allowed = nargs.at(cmd); if(std::find(allowed.begin(), allowed.end(), args.size()) == allowed.end()) { throw std::runtime_error("Subcommand '" + cmd + "' expected " + utils::join(allowed, ", ") + " arguments but got " + std::to_string(args.size())); } } } // Removes flags from args (in-place) and returns map of options std::map extractFlags(std::vector& args, const std::vector& knownOptions = {}) { std::map ret; auto it = args.begin(); while(it != args.end()) { if((*it)[0] == '-') { while((*it)[0] == '-') { (*it).erase((*it).begin()); } if(it < args.end()-1) { ret.emplace(*it, *(it+1)); if(std::find(knownOptions.begin(), knownOptions.end(), *it) != knownOptions.end()) { args.erase(it); } } else { ret.emplace(*it, std::string()); } args.erase(it); } else { it++; } } return ret; } int main(int argc, char *argv[]) { // Full thing is surrounded in try/catch to plesantly print out any errors try { std::string exename = argv[0]; std::vector args(&argv[1], &argv[argc]); auto argsWithFlags = args; auto flags = extractFlags(args); cmd::mkdir({cmd::getTruePath("")}); if(args.empty()) { std::cout << cmd::list(args); return 0; } std::string cmd = args[0]; std::vector argsOrig(args); args.erase(args.begin()); checkArgs(cmd, args); if(cmd == "ls") std::cout << cmd::list(args); else if(cmd == "cp") std::cout << cmd::cp(args); else if(cmd == "mkdir") std::cout << cmd::mkdir(args); else if(cmd == "mv") std::cout << cmd::mv(args); else if(cmd == "rm") std::cout << cmd::rm(args); else if(cmd == "attacks") std::cout << cmd::attacks(args); else if(cmd == "roll") std::cout << cmd::roll(args); else if(cmd == "attack") std::cout << cmd::attack(args, flags); else if(cmd == "damage") std::cout << cmd::damage(args, flags); else if(cmd == "heal") std::cout << cmd::heal(args); else if(cmd == "save") { args = argsWithFlags; extractFlags(args, {"damage", "type"}); args.erase(args.begin()); std::cout << cmd::save(args, flags); } else if(cmd == "reset") std::cout << cmd::reset(args); else if(cmd == "set") std::cout << cmd::set(args); else if(cmd == "add") std::cout << cmd::add(args); else if(cmd == "del") std::cout << cmd::del(args); else if(cmd == "edit") std::cout << cmd::edit(args); else if(cmd == "spellcasting") std::cout << cmd::spellcasting(args); else if(cmd == "git") std::cout << cmd::git(argsWithFlags); else if(cmd == "help") std::cout << cmd::usage(exename); else std::cout << cmd::list(argsOrig); } catch(std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; }