1 /*
2 * Copyright (c) 2022-2023 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 "tools_op.h"
17
18 #include <regex>
19 #include <sstream>
20
21 namespace OHOS::FileManagement::Backup {
22 using namespace std;
23
GetName() const24 const std::string ToolsOp::GetName() const
25 {
26 std::stringstream ss;
27
28 auto &&allSubOps = desc_.opName;
29 for (size_t j = 0; j < allSubOps.size(); ++j) {
30 ss << allSubOps[j];
31 if (j != allSubOps.size() - 1) {
32 ss << ' ';
33 }
34 }
35
36 return ss.str();
37 }
38
Register(ToolsOp && op)39 bool ToolsOp::Register(ToolsOp &&op)
40 {
41 auto &&opName = op.GetDescriptor().opName;
42 auto isIncorrect = [&opName](const std::string_view &subOp) {
43 std::vector<std::string> patterns {
44 "\\W", // 匹配任意不是字母、数字、下划线的字符
45 "^$", // 匹配空串
46 };
47
48 for (auto subOp : opName) {
49 for (auto pattern : patterns) {
50 std::regex re(pattern);
51 if (std::regex_search(string(subOp), re)) {
52 fprintf(stderr, "Sub-op '%s' failed to pass regex '%s'\n", subOp.data(), pattern.c_str());
53 return true;
54 }
55 }
56 }
57
58 return false;
59 };
60 if (std::any_of(opName.begin(), opName.end(), isIncorrect)) {
61 fprintf(stderr, "Failed to register an illegal operation '%s'\n", op.GetName().c_str());
62 return false;
63 }
64
65 ToolsOp::opsAvailable_.emplace_back(std::move(op));
66
67 // sort with ascending order
68 std::sort(opsAvailable_.begin(), opsAvailable_.end(), [](const ToolsOp &lop, const ToolsOp &rop) {
69 return lop.desc_.opName < rop.desc_.opName;
70 });
71 return true;
72 }
73
TryMatch(CRefVStrView op) const74 bool ToolsOp::TryMatch(CRefVStrView op) const
75 {
76 return op == desc_.opName;
77 }
78
Execute(map<string,vector<string>> args) const79 int ToolsOp::Execute(map<string, vector<string>> args) const
80 {
81 if (!desc_.funcExec) {
82 fprintf(stderr, "Incomplete operation: executor is missing\n");
83 return -EPERM;
84 }
85 return desc_.funcExec(args);
86 }
87 } // namespace OHOS::FileManagement::Backup
88