From 4206b022b6137aba08d6efcb2a907fdd12570081 Mon Sep 17 00:00:00 2001 From: Elad <18193363+elad335@users.noreply.github.com> Date: Thu, 31 Oct 2024 20:29:10 +0200 Subject: [PATCH] Win32/File.cpp: Use ReplaceFile for hardlink overwrite --- Utilities/File.cpp | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/Utilities/File.cpp b/Utilities/File.cpp index b73be0a8cf..89d53f9407 100644 --- a/Utilities/File.cpp +++ b/Utilities/File.cpp @@ -2490,7 +2490,8 @@ bool fs::pending_file::commit(bool overwrite) const auto ws1 = to_wchar(m_path); - const HANDLE file_handle = CreateFileW(ws1.get(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); + const HANDLE file_handle = !overwrite ? INVALID_HANDLE_VALUE + : CreateFileW(ws1.get(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); while (file_handle != INVALID_HANDLE_VALUE) { @@ -2551,6 +2552,12 @@ bool fs::pending_file::commit(bool overwrite) CloseHandle(file_handle); break; } + + if (!hardlink_paths.empty()) + { + // REPLACEFILE_WRITE_THROUGH is not supported + file.sync(); + } #endif file.close(); @@ -2558,14 +2565,19 @@ bool fs::pending_file::commit(bool overwrite) #ifdef _WIN32 const auto ws2 = to_wchar(m_dest); - if (MoveFileExW(ws1.get(), ws2.get(), overwrite ? MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH : MOVEFILE_WRITE_THROUGH)) - { - for (auto&& path : hardlink_paths) - { - // Recreate hard links - CreateHardLinkW(path.c_str(), ws2.get(), NULL); - } + bool ok = false; + if (hardlink_paths.empty()) + { + ok = MoveFileExW(ws1.get(), ws2.get(), overwrite ? MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH : MOVEFILE_WRITE_THROUGH); + } + else + { + ok = ReplaceFileW(ws1.get(), ws2.get(), nullptr, 0, nullptr, nullptr); + } + + if (ok) + { // Disable the destructor m_path.clear(); return true;