From d08f1d5d468beb303a4bd80f7e37169c464cf942 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Mon, 18 Nov 2013 16:41:26 +0200 Subject: [PATCH] Add RAII class for atomic overwrites --- source/fs/redirectedpath.cpp | 38 ++++++++++++++++++++++++++++++++++++ source/fs/redirectedpath.h | 30 ++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 source/fs/redirectedpath.cpp create mode 100644 source/fs/redirectedpath.h diff --git a/source/fs/redirectedpath.cpp b/source/fs/redirectedpath.cpp new file mode 100644 index 0000000..6ca59cc --- /dev/null +++ b/source/fs/redirectedpath.cpp @@ -0,0 +1,38 @@ +#include +#include "redirectedpath.h" +#include "stat.h" +#include "utils.h" + +using namespace std; + +namespace Msp { +namespace FS { + +RedirectedPath::RedirectedPath(const Path &p, const char *ext): + Path(p.str()+ext), + original(p) +{ } + +RedirectedPath::RedirectedPath(const Path &p, const string &ext): + Path(p.str()+ext), + original(p) +{ } + +RedirectedPath::RedirectedPath(const Path &p, const Path &r): + Path(r), + original(p) +{ } + +RedirectedPath::~RedirectedPath() +{ + if(exists(*this)) + { + if(uncaught_exception()) + unlink(*this); + else + rename(*this, original); + } +} + +} // namespace FS +} // namespace Msp diff --git a/source/fs/redirectedpath.h b/source/fs/redirectedpath.h new file mode 100644 index 0000000..50a3609 --- /dev/null +++ b/source/fs/redirectedpath.h @@ -0,0 +1,30 @@ +#ifndef MSP_FS_REDIRECTEDPATH_H_ +#define MSP_FS_REDIRECTEDPATH_H_ + +#include "path.h" + +namespace Msp { +namespace FS { + +/** +Provides a redirected path for the lifetime of the object. When RedirectedPath +goes out of scope, it is renamed to the original path. If destruction happens +due to an exception, it is unlinked instead. The primary use for this is to +atomically overwrite a file with a new version. +*/ +class RedirectedPath: public Path +{ +private: + Path original; + +public: + explicit RedirectedPath(const Path &, const char * = ".tmp"); + RedirectedPath(const Path &, const std::string &); + RedirectedPath(const Path &, const Path &); + ~RedirectedPath(); +}; + +} // namespace FS +} // namespace Msp + +#endif -- 2.43.0