William A. Kennington III | e774345 | 2022-08-12 17:39:44 -0700 | [diff] [blame] | 1 | #include <cstdlib> |
William A. Kennington III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 2 | #include <stdplus/fd/fmt.hpp> |
| 3 | #include <stdplus/fd/ops.hpp> |
William A. Kennington III | e774345 | 2022-08-12 17:39:44 -0700 | [diff] [blame] | 4 | #include <stdplus/util/cexec.hpp> |
| 5 | #include <sys/stat.h> |
William A. Kennington III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 6 | |
| 7 | namespace stdplus |
| 8 | { |
| 9 | namespace fd |
| 10 | { |
| 11 | |
William A. Kennington III | a4f71f9 | 2022-08-18 14:17:00 -0700 | [diff] [blame^] | 12 | FormatBuffer::FormatBuffer(Fd& fd, size_t max) : fd(fd), max(max) |
William A. Kennington III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 13 | { |
| 14 | } |
| 15 | |
| 16 | FormatBuffer::~FormatBuffer() noexcept(false) |
| 17 | { |
| 18 | flush(); |
| 19 | } |
| 20 | |
| 21 | void FormatBuffer::flush() |
| 22 | { |
| 23 | if (buf.size() > 0) |
| 24 | { |
William A. Kennington III | a4f71f9 | 2022-08-18 14:17:00 -0700 | [diff] [blame^] | 25 | writeExact(fd, buf); |
William A. Kennington III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 26 | buf.clear(); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | void FormatBuffer::writeIfNeeded() |
| 31 | { |
| 32 | if (buf.size() >= max) |
| 33 | { |
| 34 | flush(); |
| 35 | } |
| 36 | } |
| 37 | |
William A. Kennington III | e774345 | 2022-08-12 17:39:44 -0700 | [diff] [blame] | 38 | FormatToFile::FormatToFile(std::string_view tmpl) : |
| 39 | tmpname(tmpl), |
| 40 | fd(CHECK_ERRNO(mkstemp(tmpname.data()), |
| 41 | [&](int error) { |
| 42 | auto msg = fmt::format("mkstemp({})", tmpname); |
| 43 | tmpname.clear(); |
| 44 | throw std::system_error(error, std::generic_category(), |
| 45 | msg); |
| 46 | })), |
| 47 | buf(fd) |
| 48 | { |
| 49 | } |
| 50 | |
| 51 | FormatToFile::~FormatToFile() |
| 52 | { |
| 53 | if (!tmpname.empty()) |
| 54 | { |
| 55 | std::error_code ec; |
| 56 | std::filesystem::remove(tmpname, ec); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | void FormatToFile::commit(const std::filesystem::path& out, int mode) |
| 61 | { |
| 62 | { |
| 63 | buf.flush(); |
| 64 | auto ifd = std::move(fd); |
| 65 | } |
| 66 | CHECK_ERRNO(chmod(tmpname.c_str(), mode), [&](int error) { |
| 67 | throw std::system_error(error, std::generic_category(), |
| 68 | fmt::format("chmod({}, {})", tmpname, mode)); |
| 69 | }); |
| 70 | std::filesystem::rename(tmpname, out); |
| 71 | tmpname.clear(); |
| 72 | } |
| 73 | |
William A. Kennington III | 4f5711c | 2022-08-12 17:01:53 -0700 | [diff] [blame] | 74 | } // namespace fd |
| 75 | } // namespace stdplus |