2022-01-07 16:22:39 +02:00
|
|
|
/*
|
2023-03-18 00:05:35 +00:00
|
|
|
* Copyright (c) 2020-2023, the SerenityOS developers.
|
2022-01-07 16:22:39 +02:00
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "TempFile.h"
|
2023-02-08 21:08:01 +01:00
|
|
|
#include <LibCore/DeprecatedFile.h>
|
2023-03-18 00:05:35 +00:00
|
|
|
#include <LibCore/System.h>
|
2022-01-07 16:22:39 +02:00
|
|
|
|
|
|
|
namespace Core {
|
|
|
|
|
2023-03-18 00:05:35 +00:00
|
|
|
ErrorOr<NonnullOwnPtr<TempFile>> TempFile::create_temp_directory()
|
2022-01-07 16:22:39 +02:00
|
|
|
{
|
2023-03-18 00:05:35 +00:00
|
|
|
char pattern[] = "/tmp/tmp.XXXXXX";
|
2022-01-07 16:22:39 +02:00
|
|
|
|
2023-03-18 00:05:35 +00:00
|
|
|
auto path = TRY(Core::System::mkdtemp(pattern));
|
|
|
|
return adopt_nonnull_own_or_enomem(new (nothrow) TempFile(Type::Directory, path));
|
2022-01-07 16:22:39 +02:00
|
|
|
}
|
|
|
|
|
2023-03-18 00:05:35 +00:00
|
|
|
ErrorOr<NonnullOwnPtr<TempFile>> TempFile::create_temp_file()
|
2022-01-07 16:22:39 +02:00
|
|
|
{
|
2023-03-18 00:05:35 +00:00
|
|
|
char file_path[] = "/tmp/tmp.XXXXXX";
|
|
|
|
TRY(Core::System::mkstemp(file_path));
|
|
|
|
|
|
|
|
auto string = TRY(String::from_utf8({ file_path, sizeof file_path }));
|
|
|
|
return adopt_nonnull_own_or_enomem(new (nothrow) TempFile(Type::File, string));
|
2022-01-07 16:22:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
TempFile::~TempFile()
|
|
|
|
{
|
2023-03-18 00:05:35 +00:00
|
|
|
// Temporary files aren't removed by anyone else, so we must do it ourselves.
|
|
|
|
auto recursion_mode = DeprecatedFile::RecursionMode::Disallowed;
|
2022-01-07 16:22:39 +02:00
|
|
|
if (m_type == Type::Directory)
|
2023-03-18 00:05:35 +00:00
|
|
|
recursion_mode = DeprecatedFile::RecursionMode::Allowed;
|
2022-01-07 16:22:39 +02:00
|
|
|
|
2023-03-18 00:05:35 +00:00
|
|
|
auto result = DeprecatedFile::remove(m_path, recursion_mode);
|
|
|
|
if (result.is_error()) {
|
|
|
|
warnln("Removal of temporary file failed: {}", result.error().string_literal());
|
2022-01-07 16:22:39 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|