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  const DWORD buffer_size =
40  ::GetEnvironmentVariableW(wide_key.data(), nullptr, 0);
41  if (buffer_size == 0) {
42  if (::GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
43  return None();
44  }
45 
46  return "";
47  }
48 
49  std::vector<wchar_t> environment;
50  environment.reserve(static_cast<size_t>(buffer_size));
51 
52  DWORD value_size =
53  ::GetEnvironmentVariableW(wide_key.data(), environment.data(), buffer_size);
54 
55  if (value_size == 0) {
56  // If `value_size == 0` here, that probably means the environment variable
57  // was deleted between when we checked and when we allocated the buffer.
58  if (::GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
59  return None();
60  }
61 
62  return "";
63  }
64 
65  return stringify(std::wstring(environment.data()));
66 }
67 
68 } // namespace os {
69 
70 #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)