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 with custom fs task processor
28 /// @throws std::runtime_error
29 static TempFile Create(engine::TaskProcessor& fs_task_processor);
30
31 /// @brief Create the file at the default path for temporary files
32 /// @throws std::runtime_error
33 static TempFile Create();
34
35 /// @brief Create the file at the specified path
36 /// @param parent_path The directory where the temporary file will be created
37 /// @param name_prefix File name prefix, a random string will be added
38 /// @param fs_task_processor The `engine::TaskProcessor` to use for the blocking fs operations
39 /// after the prefix
40 /// @throws std::runtime_error
41 static TempFile Create(
42 std::string_view parent_path,
43 std::string_view name_prefix,
44 engine::TaskProcessor& fs_task_processor
45 );
46
47 TempFile();
48 TempFile(TempFile&& other) noexcept = default;
49 TempFile& operator=(TempFile&& other) noexcept = default;
50 ~TempFile() noexcept;
51
52 /// Take ownership of an existing file
53 static TempFile Adopt(std::string path, engine::TaskProcessor& fs_task_processor);
54
55 /// The file path
56 const std::string& GetPath() const;
57
58 /// @brief Remove the file early
59 /// @throws std::runtime_error
60 void Remove() &&;
61
62private:
63 TempFile(engine::TaskProcessor& fs_task_processor, fs::blocking::TempFile temp_file);
64
65 utils::NotNull<engine::TaskProcessor*> fs_task_processor_;
66 fs::blocking::TempFile temp_file_;
67};
68
69} // namespace fs
70
71USERVER_NAMESPACE_END