Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/src/Progmasoft/Runner/Files.cpp
blob: 68bde53762866a8d4ea07d8a83fb6abb25b1ed65 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright (c) 2026 Progmasoft.
// SPDX-License-Identifier: MPL-2.0 WITH AdditionRef-Progmasoft-Exception-1.1
#include "Files.hpp"

#include "Hash.hpp"
#include "Process.hpp"

#if defined(_WIN32)
#    include <fcntl.h>
#    include <io.h>
#    include <share.h>
#    include <sys/stat.h>
#else
#    include <fcntl.h>
#    include <sys/stat.h>
#    include <unistd.h>
#endif

#include <atomic>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <system_error>
#include <thread>

namespace Progmasoft::Catch3::Runner
{
    namespace
    {
        /// Creates `path` only if it does not exist, in one atomic step.
        bool
        CreateExclusively(const std::filesystem::path &path)
        {
#if defined(_WIN32)
            int descriptor = -1;
            if (_wsopen_s(&descriptor,
                          path.wstring().c_str(),
                          _O_CREAT | _O_EXCL | _O_WRONLY,
                          _SH_DENYNO,
                          _S_IREAD | _S_IWRITE) != 0)
            {
                return false;
            }
            _close(descriptor);
            return true;
#else
            const int descriptor = open(path.c_str(),
                                        O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC,
                                        S_IRUSR | S_IWUSR);
            if (descriptor < 0)
            {
                return false;
            }
            close(descriptor);
            return true;
#endif
        }
    } // namespace

    FileLock::FileLock(const std::filesystem::path &file,
                       std::chrono::milliseconds wait,
                       std::chrono::milliseconds stale)
        : path_{file.string() + ".lock"}
    {
        std::error_code error;
        std::filesystem::create_directories(path_.parent_path(), error);
        const auto deadline = std::chrono::steady_clock::now() + wait;
        while (true)
        {
            if (CreateExclusively(path_))
            {
                held_ = true;
                return;
            }
            const auto written = std::filesystem::last_write_time(path_, error);
            if (!error &&
                std::filesystem::file_time_type::clock::now() - written > stale)
            {
                std::filesystem::remove(path_, error);
                continue;
            }
            if (std::chrono::steady_clock::now() >= deadline)
            {
                return;
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }

    FileLock::~FileLock()
    {
        if (held_)
        {
            std::error_code error;
            std::filesystem::remove(path_, error);
        }
    }

    Expected<std::string>
    ReadFile(const std::filesystem::path &file)
    {
        std::ifstream input(file, std::ios::binary);
        if (!input)
        {
            return Error{"cannot read '" + file.string() + "'"};
        }
        std::ostringstream contents;
        contents << input.rdbuf();
        if (input.bad())
        {
            return Error{"cannot read '" + file.string() + "'"};
        }
        return contents.str();
    }

    Status
    WriteFileAtomically(const std::filesystem::path &file,
                        std::string_view contents)
    {
        std::error_code error;
        if (file.has_parent_path())
        {
            std::filesystem::create_directories(file.parent_path(), error);
        }
        const auto temporary =
            std::filesystem::path{file.string() + "." + UniqueName() + ".tmp"};
        {
            std::ofstream output(temporary, std::ios::binary | std::ios::trunc);
            output.write(contents.data(),
                         static_cast<std::streamsize>(contents.size()));
            if (!output)
            {
                output.close();
                std::filesystem::remove(temporary, error);
                return Error{"cannot write '" + file.string() + "'"};
            }
        }
        std::filesystem::rename(temporary, file, error);
        if (error)
        {
            std::error_code ignored;
            std::filesystem::remove(temporary, ignored);
            return Error{"cannot replace '" + file.string() +
                         "': " + error.message()};
        }
        return Status::Ok();
    }

    Status
    CreatePrivateFile(const std::filesystem::path &file)
    {
#if defined(_WIN32)
        std::error_code error;
        const auto status = std::filesystem::symlink_status(file, error);
        if (!error && std::filesystem::exists(status) &&
            !std::filesystem::is_regular_file(status))
        {
            return Error{"'" + file.string() + "' is not a regular file"};
        }
        int descriptor = -1;
        if (_wsopen_s(&descriptor,
                      file.wstring().c_str(),
                      _O_CREAT | _O_TRUNC | _O_WRONLY | _O_NOINHERIT,
                      _SH_DENYNO,
                      _S_IREAD | _S_IWRITE) != 0)
        {
            return Error{"cannot create '" + file.string() + "'"};
        }
        _close(descriptor);
        return Status::Ok();
#else
        int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NONBLOCK;
#    if defined(O_NOFOLLOW)
        flags |= O_NOFOLLOW;
#    endif
        const int descriptor = open(file.c_str(), flags, S_IRUSR | S_IWUSR);
        if (descriptor < 0)
        {
            return Error{"cannot create '" + file.string() + "'"};
        }
        struct stat information = {};
        if (fstat(descriptor, &information) != 0 ||
            !S_ISREG(information.st_mode))
        {
            close(descriptor);
            return Error{"'" + file.string() + "' is not a regular file"};
        }
        // A file that existed keeps its mode; make it private too.
        fchmod(descriptor, S_IRUSR | S_IWUSR);
        close(descriptor);
        return Status::Ok();
#endif
    }

    std::string
    UniqueName()
    {
        static std::atomic<unsigned> counter{0};
        std::ostringstream text;
        text << CurrentProcessId() << '-'
             << std::chrono::steady_clock::now().time_since_epoch().count()
             << '-' << std::this_thread::get_id() << '-' << ++counter;
        return ToHex(Fnv1a64(text.str()));
    }
} // namespace Progmasoft::Catch3::Runner