• 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 "bundle_active_log.h"
17 #include "shell_command.h"
18 
19 namespace OHOS {
20 namespace DeviceUsageStats {
ShellCommand(int32_t argc,char * argv[],std::string name)21 ShellCommand::ShellCommand(int32_t argc, char *argv[], std::string name)
22 {
23     argc_ = argc;
24     argv_ = argv;
25     name_ = name;
26 
27     if (argc < MIN_ARGUMENT_NUMBER) {
28         cmd_ = "help";
29         return;
30     }
31     cmd_ = argv[1];
32     for (int32_t i = 2; i < argc; i++) {
33         argList_.push_back(argv[i]);
34     }
35     for (const auto& arg : argList_) {
36         BUNDLE_ACTIVE_LOGI("arg is %{public}s", arg.c_str());
37     }
38 }
39 
OnCommand()40 int32_t ShellCommand::OnCommand()
41 {
42     int32_t result = 0;
43 
44     auto respond = commandMap_[cmd_];
45     if (respond == nullptr) {
46         resultReceiver_.append(GetCommandErrorMsg());
47         respond = commandMap_["help"];
48     }
49 
50     if (init() == 0) {
51         respond();
52     } else {
53         result = -1;
54     }
55 
56     return result;
57 }
58 
ExecCommand()59 std::string ShellCommand::ExecCommand()
60 {
61     int32_t result = CreateCommandMap();
62     if (result != 0) {
63         BUNDLE_ACTIVE_LOGE("failed to create command map.");
64     }
65 
66     result = CreateMessageMap();
67     if (result != 0) {
68         BUNDLE_ACTIVE_LOGE("failed to create message map.");
69     }
70 
71     result = OnCommand();
72     if (result != 0) {
73         BUNDLE_ACTIVE_LOGE("failed to execute your command.");
74         resultReceiver_ = "error: failed to execute your command.\n";
75     }
76 
77     return resultReceiver_;
78 }
79 
GetCommandErrorMsg() const80 std::string ShellCommand::GetCommandErrorMsg() const
81 {
82     std::string commandErrorMsg =
83         name_ + ": '" + cmd_ + "' is not a valid " + name_ + " command. See '" + name_ + " help'.\n";
84     return commandErrorMsg;
85 }
86 }  // namespace DeviceUsageStats
87 }  // namespace OHOS
88 
89