| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #include "stringutils.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <cstddef> |
| 8 | #include <regex> |
| 9 | #include <sstream> |
| 10 | |
| 11 | namespace Utils::String { |
| 12 | |
| 13 | std::string cleanPrefix(std::string const &str, std::string const &prefix) |
| 14 | { |
| 15 | auto it = std::search(str.cbegin(), str.cend(), prefix.cbegin(), prefix.cend()); |
| 16 | if (it != str.cend()) { |
| 17 | size_t const pos = prefix.size(); |
| 18 | return str.substr(pos, str.size() - pos); |
| 19 | } |
| 20 | |
| 21 | return str; |
| 22 | } |
| 23 | |
| 24 | std::tuple<int, int, int> parseVersion(std::string const &version) |
| 25 | { |
| 26 | try { |
| 27 | if (std::count(version.cbegin(), version.cend(), '.') == 2) { |
| 28 | auto firstDot = version.find("."); |
| 29 | auto secondDot = version.find(".", firstDot + 1); |
| 30 | if (firstDot > 0 && // mayor version exists |
| 31 | firstDot + 1 < secondDot && // minor version exists |
| 32 | secondDot < version.length() - 1) // patch version exists |
| 33 | return {std::stoi(version.substr(0, firstDot)), |
| 34 | std::stoi(version.substr(firstDot + 1, secondDot)), |
| 35 | std::stoi(version.substr(secondDot + 1, std::string::npos))}; |
| 36 | } |
| 37 | SPDLOG_DEBUG("'{}' is not a valid version string", version); |
| 38 | } |
| 39 | catch (std::exception const &e) { |
| 40 | SPDLOG_DEBUG("Cannot parse version string '{}'. Error: {}", version, |
| 41 | e.what()); |
| 42 | } |
| 43 | |
| 44 | return {0, 0, 0}; |
| 45 | } |
| 46 | |
| 47 | std::vector<std::string> split(std::string const &src, char delim) |
| 48 | { |
| 49 | std::vector<std::string> result; |
| 50 | |
| 51 | std::istringstream istream(src); |
| 52 | for (std::string part; std::getline(istream, part, delim);) |
| 53 | if (!part.empty()) // skip empty parts |
| 54 | result.push_back(part); |
| 55 | |
| 56 | return result; |
| 57 | } |
| 58 | |
| 59 | std::optional<std::string> parseKernelProcVersion(std::string const &data) |
| 60 | { |
| 61 | std::regex const regex(R"(^Linux\s*version\s*(\d+\.\d+(?:\.\d+){0,1}).*)"); |
| 62 | |
| 63 | std::smatch result; |
| 64 | if (!std::regex_search(data, result, regex)) { |
| 65 | SPDLOG_DEBUG("Cannot parse kernel version"); |
| 66 | return {}; |
| 67 | } |
| 68 | |
| 69 | // Append .0 when the patch version number is missing, see #254 |
| 70 | std::string version = result[1]; |
| 71 | if (std::count(version.cbegin(), version.cend(), '.') == 1) |
| 72 | version.append(".0"); |
| 73 | |
| 74 | return version; |
| 75 | } |
| 76 | |
| 77 | } // namespace Utils::String |