1 // Copyright (c) 2012 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
,
25 std::string
* result
) OVERRIDE
{
26 if (GetVarImpl(variable_name
, result
))
29 // Some commonly used variable names are uppercase while others
30 // are lowercase, which is inconsistent. Let's try to be helpful
31 // and look for a variable name with the reverse case.
32 // I.e. HTTP_PROXY may be http_proxy for some users/systems.
33 char first_char
= variable_name
[0];
34 std::string alternate_case_var
;
35 if (first_char
>= 'a' && first_char
<= 'z')
36 alternate_case_var
= StringToUpperASCII(std::string(variable_name
));
37 else if (first_char
>= 'A' && first_char
<= 'Z')
38 alternate_case_var
= StringToLowerASCII(std::string(variable_name
));
41 return GetVarImpl(alternate_case_var
.c_str(), result
);
44 virtual bool SetVar(const char* variable_name
,
45 const std::string
& new_value
) OVERRIDE
{
46 return SetVarImpl(variable_name
, new_value
);
49 virtual bool UnSetVar(const char* variable_name
) OVERRIDE
{
50 return UnSetVarImpl(variable_name
);
54 bool GetVarImpl(const char* variable_name
, std::string
* result
) {
56 const char* env_value
= getenv(variable_name
);
59 // Note that the variable may be defined but empty.
64 DWORD value_length
= ::GetEnvironmentVariable(
65 UTF8ToWide(variable_name
).c_str(), NULL
, 0);
66 if (value_length
== 0)
69 scoped_ptr
<wchar_t[]> value(new wchar_t[value_length
]);
70 ::GetEnvironmentVariable(UTF8ToWide(variable_name
).c_str(), value
.get(),
72 *result
= WideToUTF8(value
.get());
80 bool SetVarImpl(const char* variable_name
, const std::string
& new_value
) {
82 // On success, zero is returned.
83 return !setenv(variable_name
, new_value
.c_str(), 1);
85 // On success, a nonzero value is returned.
86 return !!SetEnvironmentVariable(UTF8ToWide(variable_name
).c_str(),
87 UTF8ToWide(new_value
).c_str());
91 bool UnSetVarImpl(const char* variable_name
) {
93 // On success, zero is returned.
94 return !unsetenv(variable_name
);
96 // On success, a nonzero value is returned.
97 return !!SetEnvironmentVariable(UTF8ToWide(variable_name
).c_str(), NULL
);
108 #if defined(OS_POSIX)
109 // On Posix systems, this variable contains the location of the user's home
110 // directory. (e.g, /home/username/).
111 const char kHome
[] = "HOME";
114 } // namespace env_vars
116 Environment::~Environment() {}
119 Environment
* Environment::Create() {
120 return new EnvironmentImpl();
123 bool Environment::HasVar(const char* variable_name
) {
124 return GetVar(variable_name
, NULL
);