From: Thomas Otto Date: Wed, 30 Oct 2019 15:38:28 +0000 (+0100) Subject: Add and test change_extension() X-Git-Tag: v4.0~703^2~2 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=1481c848d024f77e4a8d3ea7f9b7a5ed6d2a94ec;p=thirdparty%2Fccache.git Add and test change_extension() New function, not ported from legacy_util. Added because remove_extension() followed by format("%s.new_ext", name) is used quite frequently. --- diff --git a/src/Util.cpp b/src/Util.cpp index 8ad1ebd89..1d932fb0e 100644 --- a/src/Util.cpp +++ b/src/Util.cpp @@ -167,6 +167,13 @@ remove_extension(nonstd::string_view path) return path.substr(0, path.length() - get_extension(path).length()); } +std::string +change_extension(nonstd::string_view path, nonstd::string_view new_ext) +{ + string_view without_ext = Util::remove_extension(path); + return std::string(without_ext).append(new_ext.data(), new_ext.length()); +} + nonstd::string_view get_truncated_base_name(nonstd::string_view path, size_t max_length) { diff --git a/src/Util.hpp b/src/Util.hpp index 7c8729551..8a46306b5 100644 --- a/src/Util.hpp +++ b/src/Util.hpp @@ -49,6 +49,11 @@ nonstd::string_view get_extension(nonstd::string_view path); // filename extension as determined by `get_extension()`. nonstd::string_view remove_extension(nonstd::string_view path); +// Remove the extension via `remove_extension()`, then add `new_ext`. +// `new_ext` should start with a dot, no extra dot is inserted. +std::string change_extension(nonstd::string_view path, + nonstd::string_view new_ext); + // Return a shortened view into the base name of `path``. This view starts at // the beginning of the base name and ends at either the position the first dot, // or `max_length`, or the length of the base name, whichever is the shortest. diff --git a/unittest/test_Util.cpp b/unittest/test_Util.cpp index ef1d2655d..c73872608 100644 --- a/unittest/test_Util.cpp +++ b/unittest/test_Util.cpp @@ -62,6 +62,20 @@ TEST_CASE("Util::remove_extension") CHECK(Util::remove_extension("/foo/bar/f.abc.txt") == "/foo/bar/f.abc"); } +TEST_CASE("Util::change_extension") +{ + CHECK(Util::change_extension("", "") == ""); + CHECK(Util::change_extension("x", "") == "x"); + CHECK(Util::change_extension("", "x") == "x"); + CHECK(Util::change_extension("", ".") == "."); + CHECK(Util::change_extension(".", "") == ""); + CHECK(Util::change_extension("...", "x") == "..x"); + CHECK(Util::change_extension("abc", "def") == "abcdef"); + CHECK(Util::change_extension("foo.ext", "e2") == "fooe2"); + CHECK(Util::change_extension("bar.txt", ".o") == "bar.o"); + CHECK(Util::change_extension("foo.bar.txt", ".o") == "foo.bar.o"); +} + TEST_CASE("Util:get_truncated_base_name") { CHECK(Util::get_truncated_base_name("", 5) == "");