Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utility function to get the size of a file #28

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ if(BUILD_TESTING)

ament_add_gtest(test_split test/test_split.cpp)

ament_add_gtest(test_filesystem_helper test/test_filesystem_helper.cpp)
ament_add_gmock(test_filesystem_helper test/test_filesystem_helper.cpp)

ament_add_gtest(test_find_and_replace test/test_find_and_replace.cpp)

Expand Down
20 changes: 20 additions & 0 deletions include/rcpputils/filesystem_helper.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@

#include <algorithm>
#include <string>
#include <system_error>
#include <vector>

#ifdef _WIN32
Expand Down Expand Up @@ -217,6 +218,25 @@ inline path remove_extension(const path & file_path, int n_times = 1)
return new_path;
}

/**
* For a regular file p, returns the size determined as if by reading the st_size member of the
* structure obtained by stat.
* If p does not exist, reports an error.
*
* \param file_path Path to examine.
* \return The size of the file, in bytes.
*/
inline std::uintmax_t file_size(const path & file_path)
{
if (!file_path.exists()) {
std::error_code ec(ENOENT, std::system_category());
throw std::system_error(ec, "Path does not exist");
}
struct stat stat_buffer {};
int rc = stat(file_path.string().c_str(), &stat_buffer);
return rc == 0 ? static_cast<size_t>(stat_buffer.st_size) : 0;
}

#undef RCPPUTILS_IMPL_OS_DIRSEP

} // namespace fs
Expand Down
100 changes: 100 additions & 0 deletions test/temporary_directory_fixture.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright 2018, Bosch Software Innovations GmbH.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef TEMPORARY_DIRECTORY_FIXTURE_HPP_
#define TEMPORARY_DIRECTORY_FIXTURE_HPP_

#include <gmock/gmock.h>

#include <string>

#ifdef _WIN32
# include <direct.h>
# include <Windows.h>
#else
# include <unistd.h>
# include <sys/types.h>
# include <dirent.h>
#endif


class TemporaryDirectoryFixture : public ::testing::Test
{
public:
TemporaryDirectoryFixture()
{
char template_char[] = "tmp_test_dir.XXXXXX";
#ifdef _WIN32
char temp_path[255];
GetTempPathA(255, temp_path);
_mktemp_s(template_char, strnlen(template_char, 20) + 1);
temporary_dir_path_ = std::string(temp_path) + std::string(template_char);
_mkdir(temporary_dir_path_.c_str());
#else
char * dir_name = mkdtemp(template_char);
temporary_dir_path_ = dir_name;
#endif
}
Comment on lines +81 to +91

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs some cleanup.


~TemporaryDirectoryFixture() override
{
remove_directory_recursively(temporary_dir_path_);
}

void remove_directory_recursively(const std::string & directory_path)
{
#ifdef _WIN32
// We need a string of type PCZZTSTR, which is a double null terminated char ptr
size_t length = strlen(directory_path.c_str());
TCHAR * temp_dir = new TCHAR[length + 2];
memcpy(temp_dir, temporary_dir_path_.c_str(), length);
temp_dir[length] = 0;
temp_dir[length + 1] = 0; // double null terminated

SHFILEOPSTRUCT file_options;
file_options.hwnd = nullptr;
file_options.wFunc = FO_DELETE; // delete (recursively)
file_options.pFrom = temp_dir;
file_options.pTo = nullptr;
file_options.fFlags = FOF_NOCONFIRMATION | FOF_SILENT; // do not prompt user
file_options.fAnyOperationsAborted = FALSE;
file_options.lpszProgressTitle = nullptr;
file_options.hNameMappings = nullptr;

SHFileOperation(&file_options);
delete[] temp_dir;
#else
DIR * dir = opendir(directory_path.c_str());
if (!dir) {
return;
}
struct dirent * directory_entry;
while ((directory_entry = readdir(dir)) != nullptr) {
// Make sure to not call ".." or "." entries in directory (might delete everything)
if (strcmp(directory_entry->d_name, ".") != 0 && strcmp(directory_entry->d_name, "..") != 0) {
if (directory_entry->d_type == DT_DIR) {
remove_directory_recursively(directory_path + "/" + directory_entry->d_name);
}
remove((directory_path + "/" + directory_entry->d_name).c_str());
}
}
closedir(dir);
remove(temporary_dir_path_.c_str());
#endif
}

std::string temporary_dir_path_;
};

#endif // TEMPORARY_DIRECTORY_FIXTURE_HPP_
50 changes: 50 additions & 0 deletions test/test_filesystem_helper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,42 @@

#include <gtest/gtest.h>

#include <fstream>
#include <string>

#include "rcpputils/filesystem_helper.hpp"
#include "temporary_directory_fixture.hpp"

#ifdef _WIN32
static constexpr const bool is_win32 = true;
#else
static constexpr const bool is_win32 = false;
#endif

namespace
{
/**
* Create a file with a specific size specified in MiB.
*
* @param uri Path to the file to create.
* @param size File size in MiB
*/
void create_file(const std::string & uri, int size)
{
std::ofstream out{uri};
if (!out) {
throw std::runtime_error("Unable to write file.");
}
const auto file_text = "test";
const auto file_size = size * 1024 * 1024;
const auto num_iterations = file_size / static_cast<int>(strlen(file_text));

for (int i = 0; i < num_iterations; i++) {
out << file_text;
}
}
} // namespace

using path = rcpputils::fs::path;

std::string build_extension_path()
Expand Down Expand Up @@ -188,3 +214,27 @@ TEST(TestFilesystemHelper, remove_extension_no_extension)
p = rcpputils::fs::remove_extension(p);
EXPECT_EQ("foo", p.string());
}

class FilesystemHelperFixture : public TemporaryDirectoryFixture {};

TEST_F(FilesystemHelperFixture, get_file_size)
{
const auto expected_file_size_mib = 1;
rcpputils::fs::path file_name("file1.txt");
const auto uri = path(temporary_dir_path_) / file_name;
create_file(uri.string(), expected_file_size_mib);

const auto file_size = rcpputils::fs::file_size(uri);
const std::uintmax_t expected_file_size_bytes = expected_file_size_mib * 1024 * 1024;
EXPECT_EQ(file_size, expected_file_size_bytes);
}

TEST_F(FilesystemHelperFixture, get_file_size_file_does_not_exist)
{
rcpputils::fs::path file_name("file1.txt");
const auto uri = path(temporary_dir_path_) / file_name;
EXPECT_THROW(
{rcpputils::fs::file_size(uri);},
std::system_error
);
}