From d24970941c0cf419c6119b95e1a5a8c6dfc14869 Mon Sep 17 00:00:00 2001 From: Yann Locatelli Date: Fri, 9 Dec 2022 14:02:56 +0100 Subject: [PATCH] :sparkles: (filemanager): Add clear file --- libs/FileManagerKit/include/FileManagerKit.h | 1 + libs/FileManagerKit/source/FileManagerKit.cpp | 7 +++++ .../tests/FileManagerKit_test.cpp | 27 +++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/libs/FileManagerKit/include/FileManagerKit.h b/libs/FileManagerKit/include/FileManagerKit.h index fcd0ae66db..e939eda882 100644 --- a/libs/FileManagerKit/include/FileManagerKit.h +++ b/libs/FileManagerKit/include/FileManagerKit.h @@ -61,4 +61,5 @@ struct File : public interface::File, public mbed::NonCopyable { auto create_directory(const std::filesystem::path &path) -> bool; auto remove(const std::filesystem::path &path) -> bool; +void clear(const std::filesystem::path &path); } // namespace leka::FileManagerKit diff --git a/libs/FileManagerKit/source/FileManagerKit.cpp b/libs/FileManagerKit/source/FileManagerKit.cpp index cb3785b349..c09aab8dfa 100644 --- a/libs/FileManagerKit/source/FileManagerKit.cpp +++ b/libs/FileManagerKit/source/FileManagerKit.cpp @@ -20,3 +20,10 @@ auto FileManagerKit::remove(const std::filesystem::path &path) -> bool { return std::filesystem::remove(path); } + +void FileManagerKit::clear(const std::filesystem::path &path) +{ + if (std::filesystem::exists(path)) { + std::filesystem::resize_file(path, 0); + } +} diff --git a/libs/FileManagerKit/tests/FileManagerKit_test.cpp b/libs/FileManagerKit/tests/FileManagerKit_test.cpp index 5cd7a56fd4..54e92c6806 100644 --- a/libs/FileManagerKit/tests/FileManagerKit_test.cpp +++ b/libs/FileManagerKit/tests/FileManagerKit_test.cpp @@ -81,3 +81,30 @@ TEST_F(FileSystemTest, removeNotExistingDirectory) auto removed = FileManagerKit::remove(path_B); ASSERT_FALSE(removed); } + +TEST_F(FileSystemTest, clear) +{ + std::ofstream(path_A).put('a'); + + auto initial_file_size = std::filesystem::file_size(path_A); + auto initial_free_space = std::filesystem::space(path_A).free; + + EXPECT_NE(initial_file_size, 0); + + FileManagerKit::clear(path_A); + + auto final_file_size = std::filesystem::file_size(path_A); + auto final_free_space = std::filesystem::space(path_A).free; + + EXPECT_LT(final_file_size, initial_file_size); + EXPECT_GT(final_free_space, initial_free_space); +} + +TEST_F(FileSystemTest, clearNotExistingFile) +{ + auto removed = FileManagerKit::remove(path_A); + + FileManagerKit::clear(path_A); + + // nothing expected +}