aboutsummaryrefslogtreecommitdiff
path: root/src/dmtool.cc
blob: e9d8ed6ea68476d896b4caabe83b681938f594d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "cmd.h"
#include "utils.h"
#include <iostream>
#include <exception>
#include <algorithm>
#include <map>

const std::map<std::string, std::vector<int>> nargs({
        {"cp", {2}},
        {"mv", {2}},
        {"attacks", {1}},
        {"damage", {2, 3}},
        {"heal", {2}},
        });

void checkArgs(std::string cmd, std::vector<std::string> 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 vector of flags
std::vector<std::string> extractFlags(std::vector<std::string>& args) {
    std::vector<std::string> ret;
    auto it = args.begin();
    while(it != args.end()) {
        if((*it)[0] == '-') {
            while((*it)[0] == '-') {
                (*it).erase((*it).begin());
            }
            ret.push_back(*it);
            args.erase(it);
        } else {
            it++;
        }
    }
    return ret;
}

int main(int argc, char *argv[]) {
    std::string exename = argv[0];
    std::vector<std::string> args(&argv[1], &argv[argc]);
    std::vector<std::string> flags = extractFlags(args);
    cmd::mkdir({cmd::getTruePath("")});
    if(args.empty()) {
        std::cout << cmd::list(args);
        return 0;
    }
    std::string cmd = args[0];
    std::vector<std::string> argsOrig(args);
    args.erase(args.begin());
    try {
        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 == "damage") std::cout << cmd::damage(args, flags);
        else if(cmd == "heal") std::cout << cmd::heal(args);
        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 == "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;
}