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