• 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 "flashd_utils.h"
17 
18 #include <unistd.h>
19 
20 #include "securec.h"
21 
22 namespace Flashd {
23 constexpr const char *PREFIX_PARTITION_NODE = "/dev/block/by-name/";
24 
GetRealPath(const std::string & path)25 std::string GetRealPath(const std::string &path)
26 {
27     char realPath[PATH_MAX + 1] = {0};
28     auto ret = realpath(path.c_str(), realPath);
29     return (ret == nullptr) ? "" : ret;
30 }
31 
GetPartitionRealPath(const std::string & name)32 std::string GetPartitionRealPath(const std::string &name)
33 {
34     return GetRealPath(PREFIX_PARTITION_NODE + name);
35 }
36 
GetPathRoot(const std::string & path)37 std::string GetPathRoot(const std::string &path)
38 {
39     auto pos = path.find_first_of('/', 1);
40     return path.substr(0, pos);
41 }
42 
GetFileName(const std::string & path)43 std::string GetFileName(const std::string &path)
44 {
45     auto pos = path.find_last_of('/');
46     if (pos == std::string::npos) {
47         pos = path.find_last_of('\\');
48         if (pos == std::string::npos) {
49             return "";
50         }
51     }
52     return path.substr(pos + 1);
53 }
54 
Split(const std::string & src,const std::vector<std::string> & filter)55 std::vector<std::string> Split(const std::string &src, const std::vector<std::string> &filter)
56 {
57     std::vector<std::string> result;
58     if (src.empty()) {
59         return result;
60     }
61 
62     const auto len = src.size() + 1;
63     auto buffer = std::vector<char>(len, 0);
64     buffer.assign(src.begin(), src.end());
65 
66     const char delimit[] = " ";
67     char *nextToken = nullptr;
68     auto token = strtok_s(buffer.data(), delimit, &nextToken);
69     while (token != nullptr) {
70         if (find(filter.cbegin(), filter.cend(), token) == filter.cend()) {
71             result.push_back(token);
72         }
73         token = strtok_s(nullptr, delimit, &nextToken);
74     }
75     return result;
76 }
77 
SafeCloseFile(int & fd)78 void SafeCloseFile(int &fd)
79 {
80     if (fd >= 0) {
81         close(fd);
82         fd = -1;
83     }
84 }
85 } // namespace Flashd