summaryrefslogtreecommitdiff
path: root/src/command.cpp
blob: 4066c23e6ffbf8742293ce58e83508e692ff2947 (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
#include "command.h"
#include <cassert>

namespace katja
{
    void list::execute() const
    {
        for (const auto& package : katja::read_package_database())
        {
            std::cout << package.second.name()
                << " " << package.second.version()
                << " (" << package.second.tag() << ")"
                << std::endl;
        }
    }

    void help::execute() const
    {
        std::cout << "Usage:\n"
            "\tkatja {info|help} [OPTIONS]\n\n";
    }

    command_exception::command_exception(const command_exception_t exception_type,
        std::vector<std::string> failed_arguments) noexcept
        : m_exception_type(exception_type), m_failed_arguments(failed_arguments)
    {
    }

    const char *command_exception::what() const noexcept
    {
        switch (m_exception_type)
        {
            case command_exception_t::no_command:
                return "No command specified.";
            case command_exception_t::too_many_arguments:
                return "Too many arguments given.";
            case command_exception_t::unknown_command:
                return "Unknown command.";
        }
        assert(false);
    }

    const std::vector<std::string>& command_exception::failed_arguments() const noexcept
    {
        return m_failed_arguments;
    }

    std::unique_ptr<command> parse_command_line(int argc, char **argv)
    {
        if (argc > 2)
        {
            std::vector<std::string> failed_arguments;

            for (std::size_t i = 2; i < argc; ++i)
            {
                failed_arguments.push_back(argv[i]);
            }
            throw command_exception(command_exception_t::unknown_command);
        }
        else if (argc < 2)
        {
            throw command_exception(command_exception_t::no_command);
        }
        if (strcmp(argv[1], "list") == 0)
        {
            return std::make_unique<list>();
        }
        else if (strcmp(argv[1], "help") == 0)
        {
            return std::make_unique<help>();
        }
        throw command_exception(command_exception_t::unknown_command, { argv[1] });
    }
}