1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 11:04:59 +00:00
serenity/Userland/Libraries/LibCore/TempFile.cpp
Caoimhe de18485a2f LibCore: Improve the TempFile wrapper
- We were using primitive versions of mkstemp and mkdtemp, they have
  been converted to use LibCore::System.
- If an error occurred whilst creating a temporary directory or file, it
  was thrown and the program would crash. Now, we use ErrorOr<T> so that
  the caller can handle the error accordingly
- The `Type` enumeration has been made private, and `create_temp` has
  been "split" (although rewritten) into create_temp_directory and
  create_temp_file. The old pattern of TempFile::create_temp(Type::File)
  felt a bit awkward, and TempFile::create_temp_file() feels a bit nicer
  to use! :^)

Once the Core::Filesystem PR is merged (#17789), it would be better for
this helper to be merged in with that. But until then, this is a nice
improvement.
2023-03-19 00:14:03 +00:00

43 lines
1.2 KiB
C++

/*
* Copyright (c) 2020-2023, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "TempFile.h"
#include <LibCore/DeprecatedFile.h>
#include <LibCore/System.h>
namespace Core {
ErrorOr<NonnullOwnPtr<TempFile>> TempFile::create_temp_directory()
{
char pattern[] = "/tmp/tmp.XXXXXX";
auto path = TRY(Core::System::mkdtemp(pattern));
return adopt_nonnull_own_or_enomem(new (nothrow) TempFile(Type::Directory, path));
}
ErrorOr<NonnullOwnPtr<TempFile>> TempFile::create_temp_file()
{
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));
}
TempFile::~TempFile()
{
// Temporary files aren't removed by anyone else, so we must do it ourselves.
auto recursion_mode = DeprecatedFile::RecursionMode::Disallowed;
if (m_type == Type::Directory)
recursion_mode = DeprecatedFile::RecursionMode::Allowed;
auto result = DeprecatedFile::remove(m_path, recursion_mode);
if (result.is_error()) {
warnln("Removal of temporary file failed: {}", result.error().string_literal());
}
}
}