]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Add and test change_extension()
authorThomas Otto <thomas.otto@pdv-fs.de>
Wed, 30 Oct 2019 15:38:28 +0000 (16:38 +0100)
committerThomas Otto <thomas.otto@pdv-fs.de>
Tue, 26 Nov 2019 13:45:21 +0000 (14:45 +0100)
New function, not ported from legacy_util. Added because remove_extension()
followed by format("%s.new_ext", name) is used quite frequently.

src/Util.cpp
src/Util.hpp
unittest/test_Util.cpp

index 8ad1ebd89566a33da6e5047e13ee50ab921537f6..1d932fb0e25a292d62f375e5d1b515dfce304f4a 100644 (file)
@@ -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)
 {
index 7c87295512568bcb68da9c838c0d6303bb62aa93..8a46306b57496dde92be2a40a90c2d5f821be6d9 100644 (file)
@@ -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.
index ef1d2655dc72f271a74a582a3dd60f2d77b11fa6..c73872608f92f500b52567ff40914964e01a44f3 100644 (file)
@@ -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) == "");