1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include "shell_command.h"
17
18#include <getopt.h>
19#include <utility>
20
21#include "event_log_wrapper.h"
22
23namespace OHOS {
24namespace EventFwk {
25ShellCommand::ShellCommand(int argc, char *argv[], std::string name)
26{
27    opterr = 0;
28    argc_ = argc;
29    argv_ = argv;
30    name_ = name;
31
32    if (argc < MIN_ARGUMENT_NUMBER) {
33        cmd_ = "help";
34        return;
35    }
36    cmd_ = argv[1];
37    for (int i = 2; i < argc; i++) {
38        argList_.emplace_back(argv[i]);
39    }
40}
41
42ShellCommand::~ShellCommand() = default;
43
44ErrCode ShellCommand::OnCommand()
45{
46    int result = OHOS::ERR_OK;
47    auto respond = commandMap_[cmd_];
48    if (respond == nullptr) {
49        resultReceiver_.append(GetCommandErrorMsg());
50        respond = commandMap_["help"];
51    }
52    respond();
53    return result;
54}
55
56std::string ShellCommand::ExecCommand()
57{
58    int result = CreateCommandMap();
59    if (result != OHOS::ERR_OK) {
60        EVENT_LOGE("failed to create command map.\n");
61    }
62    result = OnCommand();
63    if (result != OHOS::ERR_OK) {
64        EVENT_LOGE("failed to execute your command.\n");
65        resultReceiver_ = "error: failed to execute your command.\n";
66    }
67    return resultReceiver_;
68}
69
70std::string ShellCommand::GetCommandErrorMsg() const
71{
72    return name_ + ": '" + cmd_ + "' is not a valid " + name_ + " command. See '" + name_ + " help'.\n";
73}
74}  // namespace EventFwk
75}  // namespace OHOS