-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathenv.cppm
More file actions
79 lines (65 loc) · 2.26 KB
/
Copy pathenv.cppm
File metadata and controls
79 lines (65 loc) · 2.26 KB
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
// mcpp.platform.env — platform-aware environment variable operations.
//
// Windows: uses _putenv_s to mutate the calling process environment.
// POSIX: builds "KEY=val" shell prefix strings (no process mutation).
module;
#include <cstdlib>
#if defined(_WIN32)
#include <stdlib.h> // _putenv_s
#endif
export module mcpp.platform.env;
import std;
export namespace mcpp::platform::env {
// Get an environment variable. Returns nullopt if not set.
std::optional<std::string> get(std::string_view key);
// Set an environment variable in the current process.
// On POSIX this is a no-op by design — use build_env_prefix() instead
// to scope vars to a child process via command-line prefixing.
void set(const std::string& key, const std::string& value);
// Build a shell command prefix that injects the given env vars.
// Windows: calls set() for each var and returns "".
// POSIX: returns "KEY1='val1' KEY2='val2' " (caller prepends to command).
std::string build_env_prefix(
const std::vector<std::pair<std::string, std::string>>& vars);
} // namespace mcpp::platform::env
// ─── Implementation ──────────────────────────────────────────────────────
namespace mcpp::platform::env {
std::optional<std::string> get(std::string_view key) {
std::string k(key);
auto* v = std::getenv(k.c_str());
if (!v || !*v) return std::nullopt;
return std::string(v);
}
void set(const std::string& key, const std::string& value) {
#if defined(_WIN32)
_putenv_s(key.c_str(), value.c_str());
#else
// POSIX: intentional no-op. Use build_env_prefix() instead.
(void)key;
(void)value;
#endif
}
std::string build_env_prefix(
const std::vector<std::pair<std::string, std::string>>& vars)
{
#if defined(_WIN32)
for (auto& [k, v] : vars)
_putenv_s(k.c_str(), v.c_str());
return "";
#else
std::string prefix;
for (auto& [k, v] : vars) {
prefix += k;
prefix += '=';
prefix += '\'';
for (char c : v) {
if (c == '\'') prefix += "'\\''";
else prefix += c;
}
prefix += '\'';
prefix += ' ';
}
return prefix;
#endif
}
} // namespace mcpp::platform::env