aboutsummaryrefslogtreecommitdiffstats
path: root/util/system/env.cpp
blob: ea81c3a1d08bcccd2e55d2f4bb4ce522c8083d8b (plain) (blame)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "env.h"

#include <util/generic/maybe.h>
#include <util/generic/string.h>
#include <util/generic/yexception.h>

#ifdef _win_
    #include <util/generic/vector.h>
    #include "winint.h"
#else
    #include <cerrno>
    #include <cstdlib>
#endif

/**
 * On Windows there may be many copies of enviroment variables, there at least two known, one is
 * manipulated by Win32 API, another by C runtime, so we must be consistent in the choice of
 * functions used to manipulate them.
 *
 * Relevant links:
 *  - http://bugs.python.org/issue16633
 *  - https://a.yandex-team.ru/review/108892/details
 */

TMaybe<TString> TryGetEnv(const TString& key) {
#ifdef _win_
    size_t len = GetEnvironmentVariableA(key.data(), nullptr, 0);

    if (len == 0) {
        if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
            return Nothing();
        }
        return TString{};
    }

    TVector<char> buffer(len);
    size_t bufferSize;
    do {
        bufferSize = buffer.size();
        len = GetEnvironmentVariableA(key.data(), buffer.data(), static_cast<DWORD>(bufferSize));
        if (len > bufferSize) {
            buffer.resize(len);
        }
    } while (len > bufferSize);

    return TString(buffer.data(), len);
#else
    const char* env = getenv(key.data());
    if (!env) {
        return Nothing();
    }
    return TString(env);
#endif
}

TString GetEnv(const TString& key, const TString& def) {
    TMaybe<TString> value = TryGetEnv(key);
    if (value.Defined()) {
        return *std::move(value);
    }
    return def;
}

void SetEnv(const TString& key, const TString& value) {
    bool isOk = false;
    int errorCode = 0;
#ifdef _win_
    isOk = SetEnvironmentVariable(key.data(), value.data());
    if (!isOk) {
        errorCode = GetLastError();
    }
#else
    isOk = (0 == setenv(key.data(), value.data(), true /*replace*/));
    if (!isOk) {
        errorCode = errno;
    }
#endif
    Y_ENSURE_EX(isOk, TSystemError() << "failed to SetEnv with error-code " << errorCode);
}

void UnsetEnv(const TString& key) {
    bool notFound = false;
#ifdef _win_
    bool ok = SetEnvironmentVariable(key.c_str(), NULL);
    notFound = !ok && (GetLastError() == ERROR_ENVVAR_NOT_FOUND);
#else
    bool ok = (0 == unsetenv(key.c_str()));
    #if defined(_darwin_)
    notFound = !ok && (errno == EINVAL);
    #endif
#endif
    Y_ENSURE_EX(ok || notFound, TSystemError() << "failed to unset environment variable " << key.Quote());
}