tmp_dir.cpp 1.37 KB
Newer Older
Paul Fultz II's avatar
Paul Fultz II committed
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
#include <rtc/tmp_dir.hpp>
#include <algorithm>
#include <random>
#include <thread>
#include <unistd.h>

namespace rtc {
std::string random_string(std::string::size_type length)
{
    static const std::string& chars = "0123456789"
                                      "abcdefghijklmnopqrstuvwxyz"
                                      "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    std::mt19937 rg{std::random_device{}()};
    std::uniform_int_distribution<std::string::size_type> pick(0, chars.length() - 1);

    std::string str(length, 0);
    std::generate(str.begin(), str.end(), [&] { return chars[pick(rg)]; });

    return str;
}

std::string unique_string(const std::string& prefix)
{
    auto pid = getpid();
    auto tid = std::this_thread::get_id();
    auto clk = std::chrono::steady_clock::now().time_since_epoch().count();
    std::stringstream ss;
    ss << std::hex << prefix << "-" << pid << "-" << tid << "-" << clk << "-" << random_string(16);
    return ss.str();
}

tmp_dir::tmp_dir(const std::string& prefix)
34
    : path(CK::fs::temp_directory_path() /
Paul Fultz II's avatar
Paul Fultz II committed
35
36
           unique_string(prefix.empty() ? "ck-rtc" : "ck-rtc-" + prefix))
{
37
    CK::fs::create_directories(this->path);
Paul Fultz II's avatar
Paul Fultz II committed
38
39
40
41
42
43
44
45
}

void tmp_dir::execute(const std::string& cmd) const
{
    std::string s = "cd " + path.string() + "; " + cmd;
    std::system(s.c_str());
}

46
tmp_dir::~tmp_dir() { CK::fs::remove_all(this->path); }
Paul Fultz II's avatar
Paul Fultz II committed
47

arai713's avatar
arai713 committed
48
} // namespace rtc