userver: userver/fs/temp_file.hpp Source File
Loading...
Searching...
No Matches
temp_file.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/fs/temp_file.hpp
4/// @brief @copybrief fs::TempFile
5
6#include <string>
7#include <string_view>
8
9#include <userver/engine/task/task_processor_fwd.hpp>
10#include <userver/fs/blocking/temp_file.hpp>
11#include <userver/utils/not_null.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace fs {
16
17/// @ingroup userver_containers
18///
19/// @brief A unique temporary file. The file is deleted when the `TempFile`
20/// object is destroyed.
21/// @note The file has permissions=0600. Any newly created parent directories
22/// have permissions=0700.
23/// @note The newly created file is immediately opened with read-write
24/// permissions. The file descriptor can be accessed using `File`.
25class TempFile final {
26public:
27 /// @brief Create the file at the default path for temporary files
28 /// @throws std::runtime_error
29 static TempFile Create(engine::TaskProcessor& fs_task_processor);
30
31 /// @brief Create the file at the specified path
32 /// @param parent_path The directory where the temporary file will be created
33 /// @param name_prefix File name prefix, a random string will be added
34 /// after the prefix
35 /// @throws std::runtime_error
36 static TempFile
37 Create(std::string_view parent_path, std::string_view name_prefix, engine::TaskProcessor& fs_task_processor);
38
39 TempFile() = delete;
40 TempFile(TempFile&& other) noexcept = default;
41 TempFile& operator=(TempFile&& other) noexcept = default;
42 ~TempFile();
43
44 /// Take ownership of an existing file
45 static TempFile Adopt(std::string path, engine::TaskProcessor& fs_task_processor);
46
47 /// The file path
48 const std::string& GetPath() const;
49
50 /// @brief Remove the file early
51 /// @throws std::runtime_error
52 void Remove() &&;
53
54private:
55 TempFile(engine::TaskProcessor& fs_task_processor, fs::blocking::TempFile temp_file);
56
57 utils::NotNull<engine::TaskProcessor*> fs_task_processor_;
58 fs::blocking::TempFile temp_file_;
59};
60
61} // namespace fs
62
63USERVER_NAMESPACE_END