1 /* 2 * Copyright (c) 2021-2025 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 #ifndef OHOS_ABILITY_RUNTIME_SHELL_COMMAND_H 17 #define OHOS_ABILITY_RUNTIME_SHELL_COMMAND_H 18 19 #include <map> 20 #include <sstream> 21 #include <string> 22 #include <functional> 23 #include <vector> 24 25 #include "errors.h" 26 27 namespace OHOS { 28 namespace AAFwk { 29 namespace { 30 const std::string HELP_MSG_NO_OPTION = "error: you must specify an option at least."; 31 32 const int OFFSET_REQUIRED_ARGUMENT = 2; 33 } // namespace 34 35 struct AaToolErrorInfo; 36 37 class ShellCommand { 38 public: 39 ShellCommand(int argc, char* argv[], std::string name); 40 virtual ~ShellCommand(); 41 42 ErrCode OnCommand(); 43 std::string ExecCommand(); 44 std::string GetCommandErrorMsg() const; 45 std::string GetUnknownOptionMsg(std::string& unknownOption) const; 46 std::string GetMessageFromCode(const int32_t code) const; 47 48 virtual ErrCode CreateCommandMap() = 0; 49 virtual ErrCode CreateMessageMap() = 0; 50 virtual ErrCode init() = 0; 51 52 protected: 53 static constexpr int MIN_ARGUMENT_NUMBER = 2; 54 static constexpr int MAX_ARGUMENT_NUMBER = 4096; 55 56 char** argv_ = nullptr; 57 int argc_ = 0; 58 int64_t startTime_ = 0; 59 std::string resultReceiver_ = ""; 60 61 std::string cmd_; 62 std::vector<std::string> argList_; 63 64 std::string name_; 65 std::map<std::string, std::function<int()>> commandMap_; 66 std::map<int32_t, std::string> messageMap_; 67 }; 68 69 struct AaToolErrorInfo { 70 std::string code; 71 std::string message; 72 std::string cause; 73 std::vector<std::string> solutions; 74 ToStringAaToolErrorInfo75 std::string ToString() 76 { 77 std::ostringstream oss; 78 79 oss << "Error Code:" << code << " Error Message:" << message << "\n"; 80 oss << "Error cause: " << cause << "\n"; 81 oss << " Try the following:\n"; 82 for (const auto& solution : solutions) { 83 oss << " > " << solution << "\n"; 84 } 85 return oss.str(); 86 } 87 }; 88 } // namespace AAFwk 89 } // namespace OHOS 90 91 #endif // OHOS_ABILITY_RUNTIME_SHELL_COMMAND_H 92