From: Thomas Otto Date: Thu, 19 Mar 2020 21:41:55 +0000 (+0100) Subject: Util: Don’t include path in error description from read_file/write_file X-Git-Tag: v4.0~547^2~11 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c5dff353530ca02439f00c37dd0ece4a6666a0af;p=thirdparty%2Fccache.git Util: Don’t include path in error description from read_file/write_file By only returning the error description the caller is more flexible when composing their own error message. --- diff --git a/src/Util.cpp b/src/Util.cpp index dff944d84..5a2adb655 100644 --- a/src/Util.cpp +++ b/src/Util.cpp @@ -461,7 +461,7 @@ read_file(const std::string& path) { std::ifstream file(path); if (!file) { - throw Error(fmt::format("{}: {}", path, strerror(errno))); + throw Error(strerror(errno)); } return std::string(std::istreambuf_iterator(file), std::istreambuf_iterator()); @@ -568,7 +568,7 @@ write_file(const std::string& path, const std::string& data, bool binary) std::ofstream file(path, binary ? std::ios::out | std::ios::binary : std::ios::out); if (!file) { - throw Error(fmt::format("{}: {}", path, strerror(errno))); + throw Error(strerror(errno)); } file << data; } diff --git a/src/Util.hpp b/src/Util.hpp index 26d3af556..62f290baf 100644 --- a/src/Util.hpp +++ b/src/Util.hpp @@ -220,7 +220,8 @@ int parse_int(const std::string& value); // Read file data as a string. // -// Throws Error on error. +// Throws `Error` on error. The description contains the error message without +// the path. std::string read_file(const std::string& path); #ifndef _WIN32 @@ -250,7 +251,8 @@ strip_whitespace(const std::string& string); // Write file data from a string. // -// Throws Error on error. +// Throws `Error` on error. The description contains the error message without +// the path. void write_file(const std::string& path, const std::string& data, bool binary = false); diff --git a/unittest/test_AtomicFile.cpp b/unittest/test_AtomicFile.cpp index 3e07e1955..71b19234f 100644 --- a/unittest/test_AtomicFile.cpp +++ b/unittest/test_AtomicFile.cpp @@ -42,5 +42,5 @@ TEST_CASE("Not committing") atomic_file.write("hello"); } CHECK_THROWS_WITH(Util::read_file("test"), - Equals("test: No such file or directory")); + Equals("No such file or directory")); } diff --git a/unittest/test_Util.cpp b/unittest/test_Util.cpp index bae807862..0b0e9a0d0 100644 --- a/unittest/test_Util.cpp +++ b/unittest/test_Util.cpp @@ -433,6 +433,12 @@ TEST_CASE("Util::read_file and Util::write_file") Util::write_file("test", "foo\nbar\n"); std::string data = Util::read_file("test"); CHECK(data == "foo\nbar\n"); + + CHECK_THROWS_WITH(Util::read_file("does/not/exist"), + Equals("No such file or directory")); + + CHECK_THROWS_WITH(Util::write_file("", "does/not/exist"), + Equals("No such file or directory")); } TEST_CASE("Util::remove_extension")