Apache Mesos
getenv.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_WINDOWS_GETENV_HPP__
14 #define __STOUT_OS_WINDOWS_GETENV_HPP__
15 
16 #include <memory>
17 #include <string>
18 
19 #include <stout/none.hpp>
20 #include <stout/option.hpp>
21 #include <stout/stringify.hpp>
22 #include <stout/windows.hpp>
23 
24 
25 namespace os {
26 
27 // Looks in the environment variables for the specified key and
28 // returns a string representation of its value. If no environment
29 // variable matching key is found, None() is returned.
30 inline Option<std::string> getenv(const std::string& key)
31 {
32  std::wstring wide_key = wide_stringify(key);
33 
34  // NOTE: The double-call to `::GetEnvironmentVariable` here uses the first
35  // call to get the size of the variable's value, and then again to retrieve
36  // the value itself. It is possible to have `::GetEnvironmentVariable`
37  // allocate the space for this, but we explicitly do it this way to avoid
38  // that.
39  DWORD buffer_size = ::GetEnvironmentVariableW(wide_key.data(), nullptr, 0);
40  if (buffer_size == 0) {
41  if (::GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
42  return None();
43  }
44 
45  return "";
46  }
47 
48  std::vector<wchar_t> environment;
49  environment.reserve(static_cast<size_t>(buffer_size));
50 
51  DWORD value_size =
52  ::GetEnvironmentVariableW(wide_key.data(), environment.data(), buffer_size);
53 
54  if (value_size == 0) {
55  // If `value_size == 0` here, that probably means the environment variable
56  // was deleted between when we checked and when we allocated the buffer.
57  if (::GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
58  return None();
59  }
60 
61  return "";
62  }
63 
64  return stringify(std::wstring(environment.data()));
65 }
66 
67 } // namespace os {
68 
69 #endif // __STOUT_OS_WINDOWS_GETENV_HPP__
Definition: posix_signalhandler.hpp:23
Option< std::string > getenv(const std::string &key)
Definition: getenv.hpp:29
std::map< std::string, std::string > environment()
Definition: environment.hpp:24
Definition: none.hpp:27
std::string stringify(int flags)