summaryrefslogtreecommitdiff
path: root/src/AtomicFile.cpp
blob: 9c0f0cb3cb5104e62f575a281849f93a04933703 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (C) 2019-2022 Joel Rosdahl and other contributors
//
// See doc/AUTHORS.adoc for a complete list of contributors.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

#include "AtomicFile.hpp"

#include "TemporaryFile.hpp"
#include "Util.hpp"
#include "assertions.hpp"

#include <core/exceptions.hpp>
#include <fmtmacros.hpp>

AtomicFile::AtomicFile(const std::string& path, Mode mode) : m_path(path)
{
  TemporaryFile tmp_file(path);
  m_stream = fdopen(tmp_file.fd.release(), mode == Mode::binary ? "w+b" : "w+");
  m_tmp_path = std::move(tmp_file.path);
}

AtomicFile::~AtomicFile()
{
  if (m_stream) {
    // commit() was not called so remove the lingering temporary file.
    fclose(m_stream);
    Util::unlink_tmp(m_tmp_path);
  }
}

void
AtomicFile::write(std::string_view data)
{
  if (fwrite(data.data(), data.size(), 1, m_stream) != 1) {
    throw core::Error(
      FMT("failed to write data to {}: {}", m_path, strerror(errno)));
  }
}

void
AtomicFile::write(nonstd::span<const uint8_t> data)
{
  if (fwrite(data.data(), data.size(), 1, m_stream) != 1) {
    throw core::Error(
      FMT("failed to write data to {}: {}", m_path, strerror(errno)));
  }
}

void
AtomicFile::flush()
{
  if (fflush(m_stream) != 0) {
    throw core::Error(
      FMT("failed to flush data to {}: {}", m_path, strerror(errno)));
  }
}

void
AtomicFile::commit()
{
  ASSERT(m_stream);
  int result = fclose(m_stream);
  m_stream = nullptr;
  if (result == EOF) {
    Util::unlink_tmp(m_tmp_path);
    throw core::Error(
      FMT("failed to write data to {}: {}", m_path, strerror(errno)));
  }
  Util::rename(m_tmp_path, m_path);
}