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 /// @param fs_task_processor The `engine::TaskProcessor` to use for the blocking fs operations
35 /// after the prefix
36 /// @throws std::runtime_error
37 static TempFile Create(
38 std::string_view parent_path,
39 std::string_view name_prefix,
40 engine::TaskProcessor& fs_task_processor
41 );
42
43 TempFile() = delete;
44 TempFile(TempFile&& other) noexcept = default;
45 TempFile& operator=(TempFile&& other) noexcept = default;
46 ~TempFile() noexcept;
47
48 /// Take ownership of an existing file
49 static TempFile Adopt(std::string path, engine::TaskProcessor& fs_task_processor);
50
51 /// The file path
52 const std::string& GetPath() const;
53
54 /// @brief Remove the file early
55 /// @throws std::runtime_error
56 void Remove() &&;
57
58private:
59 TempFile(engine::TaskProcessor& fs_task_processor, fs::blocking::TempFile temp_file);
60
61 utils::NotNull<engine::TaskProcessor*> fs_task_processor_;
62 fs::blocking::TempFile temp_file_;
63};
64
65} // namespace fs
66
67USERVER_NAMESPACE_END