• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
23 namespace OHOS {
24 namespace EventFwk {
ShellCommand(int argc,char * argv[],std::string name)25 ShellCommand::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 
42 ShellCommand::~ShellCommand() = default;
43 
OnCommand()44 ErrCode 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     if (Init() == OHOS::ERR_OK) {
53         respond();
54     } else {
55         result = OHOS::ERR_INVALID_VALUE;
56     }
57     return result;
58 }
59 
ExecCommand()60 std::string ShellCommand::ExecCommand()
61 {
62     int result = CreateCommandMap();
63     if (result != OHOS::ERR_OK) {
64         EVENT_LOGE("failed to create command map.\n");
65     }
66     result = OnCommand();
67     if (result != OHOS::ERR_OK) {
68         EVENT_LOGE("failed to execute your command.\n");
69         resultReceiver_ = "error: failed to execute your command.\n";
70     }
71     return resultReceiver_;
72 }
73 
GetCommandErrorMsg() const74 std::string ShellCommand::GetCommandErrorMsg() const
75 {
76     return name_ + ": '" + cmd_ + "' is not a valid " + name_ + " command. See '" + name_ + " help'.\n";
77 }
78 }  // namespace EventFwk
79 }  // namespace OHOS