From 96f62d2d34a7ee294a9830fa047cff22c1c808ff Mon Sep 17 00:00:00 2001 From: Michael Friedrich Date: Wed, 14 Aug 2019 11:22:55 +0200 Subject: [PATCH] Add Utility::ParseVersion() and unit tests This now uses a regex to extract the short version similar to how Icinga Web 2 does it. Additional unit tests prove the rule. --- lib/base/utility.cpp | 21 +++++++++++++++++++++ lib/base/utility.hpp | 1 + test/CMakeLists.txt | 1 + test/base-utility.cpp | 10 ++++++++++ 4 files changed, 33 insertions(+) diff --git a/lib/base/utility.cpp b/lib/base/utility.cpp index c946a0d44..1add7616c 100644 --- a/lib/base/utility.cpp +++ b/lib/base/utility.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -1172,6 +1173,26 @@ unsigned long Utility::SDBM(const String& str, size_t len) return hash; } +String Utility::ParseVersion(const String& v) +{ + /* + * 2.11.0-0.rc1.1 + * v2.10.5 + * r2.10.3 + * v2.11.0-rc1-58-g7c1f716da + */ + boost::regex pattern("^[vr]?(2\\.\\d+\\.\\d+).*$"); + boost::smatch result; + + if (boost::regex_search(v.GetData(), result, pattern)) { + String res(result[1].first, result[1].second); + return res; + } + + // Couldn't not extract anything, return unparsed version + return v; +} + int Utility::CompareVersion(const String& v1, const String& v2) { std::vector tokensv1 = v1.Split("."); diff --git a/lib/base/utility.hpp b/lib/base/utility.hpp index 2c1b0cdc3..4505dc918 100644 --- a/lib/base/utility.hpp +++ b/lib/base/utility.hpp @@ -100,6 +100,7 @@ public: static unsigned long SDBM(const String& str, size_t len = String::NPos); + static String ParseVersion(const String& v); static int CompareVersion(const String& v1, const String& v2); static int Random(); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3d5ed9b7c..6c84fd1f2 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -108,6 +108,7 @@ add_boost_test(base base_type/assign base_type/byname base_type/instantiate + base_utility/parse_version base_utility/comparepasswords_works base_utility/comparepasswords_issafe base_utility/validateutf8 diff --git a/test/base-utility.cpp b/test/base-utility.cpp index a73c32008..bf9b8429e 100644 --- a/test/base-utility.cpp +++ b/test/base-utility.cpp @@ -8,6 +8,16 @@ using namespace icinga; BOOST_AUTO_TEST_SUITE(base_utility) +BOOST_AUTO_TEST_CASE(parse_version) +{ + BOOST_CHECK(Utility::ParseVersion("2.11.0-0.rc1.1") == "2.11.0"); + BOOST_CHECK(Utility::ParseVersion("v2.10.5") == "2.10.5"); + BOOST_CHECK(Utility::ParseVersion("r2.11.1") == "2.11.1"); + BOOST_CHECK(Utility::ParseVersion("v2.11.0-rc1-58-g7c1f716da") == "2.11.0"); + + BOOST_CHECK(Utility::ParseVersion("v2.11butactually3.0") == "v2.11butactually3.0"); +} + BOOST_AUTO_TEST_CASE(comparepasswords_works) { BOOST_CHECK(Utility::ComparePasswords("", ""));