Skip to content

Commit

Permalink
Make FileUtil::CreateDirectory idempotent.
Browse files Browse the repository at this point in the history
* If the directory already exists, returns OkStatus and does nothing.
* Will suppress the warning in the beginning of logging.
* Will fix #900

PiperOrigin-RevId: 629129254
  • Loading branch information
hiroyuki-komatsu committed Apr 29, 2024
1 parent fb04bfe commit 68e99df
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/base/file_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,10 @@ absl::Status FileUtil::CreateDirectory(const std::string &path) {
}

absl::Status FileUtilImpl::CreateDirectory(const std::string &path) const {
// If the path already exists, returns OkStatus and does nothing.
if (const absl::Status status = DirectoryExists(path); status.ok()) {
return absl::OkStatus();
}
#if defined(_WIN32)
const std::wstring wide = win32::Utf8ToWide(path);
if (wide.empty()) {
Expand Down
1 change: 1 addition & 0 deletions src/base/file_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ class FileUtil {
~FileUtil() = delete;

// Creates a directory. Does not create directories in the way to the path.
// If the directory already exists, returns OkStatus and does nothing.
static absl::Status CreateDirectory(const std::string &path);

// Removes an empty directory.
Expand Down
3 changes: 3 additions & 0 deletions src/base/file_util_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ TEST(FileUtilTest, CreateDirectory) {
EXPECT_OK(FileUtil::CreateDirectory(dirpath));
EXPECT_OK(FileUtil::DirectoryExists(dirpath));

// Create the same directory again.
EXPECT_OK(FileUtil::CreateDirectory(dirpath));

// Delete the directory.
ASSERT_OK(FileUtil::RemoveDirectory(dirpath));
ASSERT_FALSE(FileUtil::FileExists(dirpath).ok());
Expand Down

0 comments on commit 68e99df

Please sign in to comment.