845f1efc8d49eeea77f84aeb4d1efde747ab4c59
[platform/core/security/cynara.git] / src / cyad / CommandlineParser / CyadCommandlineParser.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /**
17  * @file        src/cyad/CommandlineParser/CyadCommandlineParser.cpp
18  * @author      Aleksander Zdyb <a.zdyb@samsung.com>
19  * @version     1.0
20  * @brief       Commandline parser for Cyad
21  */
22
23 #include <cstring>
24 #include <getopt.h>
25 #include <map>
26 #include <sstream>
27
28 #include "CyadCommandlineParser.h"
29
30 namespace Cynara {
31
32 namespace CyadCmdlineArgs {
33     const char HELP = 'h';
34     const char * const HELP_LONG = "help";
35 }
36
37 namespace CyadCmdlineErrors {
38     const char * const UNKNOWN_ERROR = "Unknown error";
39     const char * const NO_OPTION = "No option specified";
40     const char * const UNKNOWN_OPTION = "Unknown option";
41 }
42
43 CyadCommandlineParser::CyadCommandlineParser(int argc, char * const *argv)
44     : m_argc(argc), m_argv(argv) {}
45
46 CyadCommandlineParser::~CyadCommandlineParser() {}
47
48 std::shared_ptr<CyadCommand> CyadCommandlineParser::parseMain(void) {
49     namespace Args = CyadCmdlineArgs;
50
51     const struct option long_options[] = {
52         { Args::HELP_LONG, no_argument, nullptr, Args::HELP },
53         { nullptr, 0, nullptr, 0 }
54     };
55
56     optind = 0; // On entry to `getopt', zero means this is the first call; initialize.
57     int opt;
58     std::stringstream optstr;
59     optstr << ":" << Args::HELP;
60
61     while ((opt = getopt_long(m_argc, m_argv, optstr.str().c_str(), long_options, nullptr)) != -1) {
62         switch (opt) {
63         case Args::HELP:
64             return std::make_shared<HelpCyadCommand>();
65
66         case '?': // Unknown option
67             return std::make_shared<ErrorCyadCommand>(CyadCmdlineErrors::UNKNOWN_OPTION);
68
69         case ':': // Missing argument
70             // Shall never happen, but let's just make compiler happy.
71             return std::make_shared<ErrorCyadCommand>(CyadCmdlineErrors::UNKNOWN_ERROR);
72
73         default:
74             return std::make_shared<ErrorCyadCommand>(CyadCmdlineErrors::UNKNOWN_OPTION);
75         }
76     }
77
78     return std::make_shared<ErrorCyadCommand>(CyadCmdlineErrors::NO_OPTION);
79 }
80
81 } /* namespace Cynara */