"vscode:/vscode.git/clone" did not exist on "4e92bc577e8d20fb7634ea27ce32d8ed7858015b"
tmp_dir.cpp 1.73 KB
Newer Older
Paul Fultz II's avatar
Paul Fultz II committed
1
2
3
#include <migraphx/tmp_dir.hpp>
#include <migraphx/env.hpp>
#include <migraphx/errors.hpp>
4
#include <migraphx/process.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
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
#include <algorithm>
#include <random>
#include <thread>
#include <sstream>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {

MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_DEBUG_SAVE_TEMP_DIR)

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();
38
    auto clk = std::chrono::steady_clock::now().time_since_epoch().count();
Paul Fultz II's avatar
Paul Fultz II committed
39
    std::stringstream ss;
40
    ss << std::hex << prefix << "-" << pid << "-" << tid << "-" << clk << "-" << random_string(16);
Paul Fultz II's avatar
Paul Fultz II committed
41
42
43
    return ss.str();
}

44
45
46
tmp_dir::tmp_dir(const std::string& prefix)
    : path(fs::temp_directory_path() /
           unique_string(prefix.empty() ? "migraphx" : "migraphx-" + prefix))
Paul Fultz II's avatar
Paul Fultz II committed
47
48
49
50
51
52
{
    fs::create_directories(this->path);
}

void tmp_dir::execute(const std::string& exe, const std::string& args) const
{
53
    process{exe + " " + args}.cwd(this->path).exec();
Paul Fultz II's avatar
Paul Fultz II committed
54
55
56
57
58
59
60
61
62
63
64
65
}

tmp_dir::~tmp_dir()
{
    if(!enabled(MIGRAPHX_DEBUG_SAVE_TEMP_DIR{}))
    {
        fs::remove_all(this->path);
    }
}

} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx