diff options
author | Jan Korous <jkorous@apple.com> | 2019-09-05 18:10:29 +0000 |
---|---|---|
committer | Jan Korous <jkorous@apple.com> | 2019-09-05 18:10:29 +0000 |
commit | 00e04b0a6d51a415ea70133bbc2c6dad9cc72ecc (patch) | |
tree | fe983610f9e0f9f5d3524b9c75186c4af43d5b9b /llvm/lib/Support/FileUtilities.cpp | |
parent | 1465a40cf80fff585f02005d2eef7d4728202cf1 (diff) | |
download | llvm-00e04b0a6d51a415ea70133bbc2c6dad9cc72ecc.zip llvm-00e04b0a6d51a415ea70133bbc2c6dad9cc72ecc.tar.gz llvm-00e04b0a6d51a415ea70133bbc2c6dad9cc72ecc.tar.bz2 |
[Support] Add writeFileAtomically() to FileUtilities
Differential Revision: https://reviews.llvm.org/D66859
llvm-svn: 371103
Diffstat (limited to 'llvm/lib/Support/FileUtilities.cpp')
-rw-r--r-- | llvm/lib/Support/FileUtilities.cpp | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/llvm/lib/Support/FileUtilities.cpp b/llvm/lib/Support/FileUtilities.cpp index 62eb7bfd..b933692 100644 --- a/llvm/lib/Support/FileUtilities.cpp +++ b/llvm/lib/Support/FileUtilities.cpp @@ -15,6 +15,7 @@ #include "llvm/ADT/SmallString.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <cctype> #include <cmath> @@ -264,3 +265,37 @@ int llvm::DiffFilesWithTolerance(StringRef NameA, return CompareFailed; } + +Error llvm::writeFileAtomically(StringRef TempPathModel, StringRef FinalPath, + StringRef Buffer) { + SmallString<128> GeneratedUniqPath; + int TempFD; + if (const std::error_code Error = sys::fs::createUniqueFile( + TempPathModel.str(), TempFD, GeneratedUniqPath)) { + return createStringError( + Error, "failed to create temporary file with model \"%s\"", + TempPathModel.str().c_str()); + } + + raw_fd_ostream OS(TempFD, /*shouldClose=*/true); + OS.write(Buffer.data(), Buffer.size()); + OS.close(); + TempFD = -1; + + if (OS.has_error()) { + const std::error_code Error = OS.error(); + OS.clear_error(); + return createStringError(Error, "failed to write to \"%s\"", + GeneratedUniqPath.c_str()); + } + + if (const std::error_code Error = + sys::fs::rename(/*from=*/GeneratedUniqPath.c_str(), + /*to=*/FinalPath.str().c_str())) { + return createStringError(Error, "failed to rename file \"%s\" to \"%s\"", + GeneratedUniqPath.c_str(), + FinalPath.str().c_str()); + } + + return Error::success(); +} |