}
nonstd::expected<void, std::string>
-write_file(const std::string& path, std::string_view data)
+write_file(const std::string& path, std::string_view data, InPlace in_place)
{
+ if (in_place == InPlace::no) {
+ unlink(path.c_str());
+ }
Fd fd(open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_TEXT, 0666));
if (!fd) {
return nonstd::make_unexpected(strerror(errno));
}
nonstd::expected<void, std::string>
-write_file(const std::string& path, nonstd::span<const uint8_t> data)
+write_file(const std::string& path,
+ nonstd::span<const uint8_t> data,
+ InPlace in_place)
{
+ if (in_place == InPlace::no) {
+ unlink(path.c_str());
+ }
Fd fd(open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666));
if (!fd) {
return nonstd::make_unexpected(strerror(errno));
// --- Interface ---
+enum class InPlace { yes, no };
+
void create_cachedir_tag(const std::string& dir);
// Read data from `fd` until end of file and call `data_receiver` with the read
nonstd::expected<void, std::string>
write_fd(int fd, const void* data, size_t size);
-// Write text `data` to `path`.
+// Write text `data` to `path`. If `in_place` is no, unlink any existing file
+// first (i.e., break hard links).
nonstd::expected<void, std::string> write_file(const std::string& path,
- std::string_view data);
+ std::string_view data,
+ InPlace in_place = InPlace::no);
-// Write binary `data` to `path`.
-nonstd::expected<void, std::string>
-write_file(const std::string& path, nonstd::span<const uint8_t> data);
+// Write binary `data` to `path`. If `in_place` is no, unlink any existing
+// file first (i.e., break hard links).
+nonstd::expected<void, std::string> write_file(const std::string& path,
+ nonstd::span<const uint8_t> data,
+ InPlace in_place = InPlace::no);
} // namespace util
CHECK(a_stat.same_inode_as(a_stat));
CHECK(!a_stat.same_inode_as(b_stat));
- util::write_file("a", "change size");
+ util::write_file("a", "change size", util::InPlace::yes);
auto new_a_stat = Stat::stat("a");
CHECK(new_a_stat.same_inode_as(a_stat));
CHECK(stat_a.inode() == stat_b.inode());
CHECK(stat_a.same_inode_as(stat_b));
- util::write_file("a", "1234567");
+ util::write_file("a", "1234567", util::InPlace::yes);
stat_a = Stat::stat("a");
stat_b = Stat::stat("b");