summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibCore/TempFile.cpp
blob: 527ad911e41dae5e7b5005c3c1bfd2f7308e462c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
 * Copyright (c) 2020-2021, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "TempFile.h"
#include <AK/Random.h>
#include <LibCore/DeprecatedFile.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>

namespace Core {

NonnullOwnPtr<TempFile> TempFile::create(Type type)
{
    return adopt_own(*new TempFile(type));
}

DeprecatedString TempFile::create_temp(Type type)
{
    char name_template[] = "/tmp/tmp.XXXXXX";
    switch (type) {
    case Type::File: {
        auto fd = mkstemp(name_template);
        VERIFY(fd >= 0);
        close(fd);
        break;
    }
    case Type::Directory: {
        auto fd = mkdtemp(name_template);
        VERIFY(fd != nullptr);
        break;
    }
    }
    return DeprecatedString { name_template };
}

TempFile::TempFile(Type type)
    : m_type(type)
    , m_path(create_temp(type))
{
}

TempFile::~TempFile()
{
    DeprecatedFile::RecursionMode recursion_allowed { DeprecatedFile::RecursionMode::Disallowed };
    if (m_type == Type::Directory)
        recursion_allowed = DeprecatedFile::RecursionMode::Allowed;

    auto rc = DeprecatedFile::remove(m_path, recursion_allowed);
    if (rc.is_error()) {
        warnln("File::remove failed: {}", rc.error().string_literal());
    }
}

}