1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/environment.h"
13 #include "base/string_util.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/utf_string_conversions.h"
22 class EnvironmentImpl
: public base::Environment
{
24 virtual bool GetVar(const char* variable_name
, std::string
* result
) {
25 if (GetVarImpl(variable_name
, result
))
28 // Some commonly used variable names are uppercase while others
29 // are lowercase, which is inconsistent. Let's try to be helpful
30 // and look for a variable name with the reverse case.
31 // I.e. HTTP_PROXY may be http_proxy for some users/systems.
32 char first_char
= variable_name
[0];
33 std::string alternate_case_var
;
34 if (first_char
>= 'a' && first_char
<= 'z')
35 alternate_case_var
= StringToUpperASCII(std::string(variable_name
));
36 else if (first_char
>= 'A' && first_char
<= 'Z')
37 alternate_case_var
= StringToLowerASCII(std::string(variable_name
));
40 return GetVarImpl(alternate_case_var
.c_str(), result
);
43 virtual bool SetVar(const char* variable_name
, const std::string
& new_value
) {
44 return SetVarImpl(variable_name
, new_value
);
47 virtual bool UnSetVar(const char* variable_name
) {
48 return UnSetVarImpl(variable_name
);
52 bool GetVarImpl(const char* variable_name
, std::string
* result
) {
54 const char* env_value
= getenv(variable_name
);
57 // Note that the variable may be defined but empty.
62 DWORD value_length
= ::GetEnvironmentVariable(
63 UTF8ToWide(variable_name
).c_str(), NULL
, 0);
64 if (value_length
== 0)
67 scoped_array
<wchar_t> value(new wchar_t[value_length
]);
68 ::GetEnvironmentVariable(UTF8ToWide(variable_name
).c_str(), value
.get(),
70 *result
= WideToUTF8(value
.get());
78 bool SetVarImpl(const char* variable_name
, const std::string
& new_value
) {
80 // On success, zero is returned.
81 return !setenv(variable_name
, new_value
.c_str(), 1);
83 // On success, a nonzero value is returned.
84 return !!SetEnvironmentVariable(UTF8ToWide(variable_name
).c_str(),
85 UTF8ToWide(new_value
).c_str());
89 bool UnSetVarImpl(const char* variable_name
) {
91 // On success, zero is returned.
92 return !unsetenv(variable_name
);
94 // On success, a nonzero value is returned.
95 return !!SetEnvironmentVariable(UTF8ToWide(variable_name
).c_str(), NULL
);
106 #if defined(OS_POSIX)
107 // On Posix systems, this variable contains the location of the user's home
108 // directory. (e.g, /home/username/).
109 const char kHome
[] = "HOME";
112 } // namespace env_vars
114 Environment::~Environment() {}
117 Environment
* Environment::Create() {
118 return new EnvironmentImpl();
121 bool Environment::HasVar(const char* variable_name
) {
122 return GetVar(variable_name
, NULL
);