/src/serenity/Userland/Libraries/LibFileSystem/TempFile.cpp
Line | Count | Source |
1 | | /* |
2 | | * Copyright (c) 2020-2023, the SerenityOS developers. |
3 | | * Copyright (c) 2023, Cameron Youell <cameronyouell@gmail.com> |
4 | | * |
5 | | * SPDX-License-Identifier: BSD-2-Clause |
6 | | */ |
7 | | |
8 | | #include <LibCore/System.h> |
9 | | #include <LibFileSystem/FileSystem.h> |
10 | | #include <LibFileSystem/TempFile.h> |
11 | | |
12 | | namespace FileSystem { |
13 | | |
14 | | TempFile::~TempFile() |
15 | 0 | { |
16 | | // Temporary files aren't removed by anyone else, so we must do it ourselves. |
17 | 0 | auto recursion_mode = RecursionMode::Disallowed; |
18 | 0 | if (m_type == Type::Directory) |
19 | 0 | recursion_mode = RecursionMode::Allowed; |
20 | |
|
21 | 0 | auto result = FileSystem::remove(m_path, recursion_mode); |
22 | 0 | if (result.is_error()) |
23 | 0 | warnln("Removal of temporary file failed '{}': {}", m_path, result.error().string_literal()); |
24 | 0 | } |
25 | | |
26 | | ErrorOr<NonnullOwnPtr<TempFile>> TempFile::create_temp_directory() |
27 | 0 | { |
28 | 0 | char pattern[] = "/tmp/tmp.XXXXXX"; |
29 | |
|
30 | 0 | auto path = TRY(Core::System::mkdtemp(pattern)); |
31 | 0 | return adopt_nonnull_own_or_enomem(new (nothrow) TempFile(Type::Directory, move(path))); |
32 | 0 | } |
33 | | |
34 | | ErrorOr<NonnullOwnPtr<TempFile>> TempFile::create_temp_file() |
35 | 0 | { |
36 | 0 | char file_path[] = "/tmp/tmp.XXXXXX"; |
37 | | // FIXME: Most callers will probably want to open the file, so find a |
38 | | // way to propagate the fd. |
39 | 0 | auto fd = TRY(Core::System::mkstemp(file_path)); |
40 | 0 | TRY(Core::System::close(fd)); |
41 | |
|
42 | 0 | auto path = ByteString(file_path, strlen(file_path)); |
43 | 0 | return adopt_nonnull_own_or_enomem(new (nothrow) TempFile(Type::File, move(path))); |
44 | 0 | } |
45 | | |
46 | | } |