Posted: 02/12/07 14:41:35
Thanks for the replies. Two more functions that might be useful. One sets a var, the other gets a var by name without copying the whole env into an AA. Tested with phobos on linux, but should work with tango (no time to install tango there)
import tango.text.convert.Utf;
import tango.sys.Common;
version (Windows)
{
pragma (lib, "kernel32.lib");
extern (Windows)
{
int SetEnvironmentVariableW(wchar*, wchar*);
uint GetEnvironmentVariableW(wchar*, wchar*, uint);
const int ERROR_ENVVAR_NOT_FOUND = 203;
}
}
else
import tango.stdc.posix.stdlib;
// This one might go into tango.sys.Common
class SysException : Exception
{
int code;
this(char[] msg, int errorCode = 0)
{
super(msg);
code = errorCode;
}
this()
{
this(SysError.lastMsg, SysError.lastCode);
}
this(int errorCode)
{
this(SysError.lookup(errorCode), errorCode);
}
}
// Undefines the variable, if value is null or empty string
void setEnv(char[] variable, char[] value = null)
{
version (Windows)
{
wchar* var, val;
var = (toUtf16(variable) ~ "\0").ptr;
if (value.length > 0)
val = (toUtf16(value) ~ "\0").ptr;
if (!SetEnvironmentVariableW(var, val))
throw new SysException();
}
else
{
int result;
if (value.length == 0)
unsetenv((variable ~ '\0').ptr);
else
result = setenv((variable ~ '\0').ptr, (value ~ '\0').ptr, 1);
if (result != 0)
throw new SysException();
}
}
// Returns null if the variable does not exist
char[] getEnv(char[] variable)
{
version (Windows)
{
wchar[] var = toUtf16(variable) ~ "\0";
uint size = GetEnvironmentVariableW(var.ptr, cast(wchar*)null, 0);
if (size == 0)
{
if (SysError.lastCode == ERROR_ENVVAR_NOT_FOUND)
{
return null;
}
else
throw new SysException();
}
wchar[] buffer = new wchar[size];
size = GetEnvironmentVariableW(var.ptr, buffer.ptr, size);
if (size == 0)
throw new SysException();
return toUtf8(buffer[0..size]);
}
else
{
char* ptr = getenv(variable.ptr);
if (ptr is null)
return null;
return ptr[0..strlen(ptr)].dup;
}
}
unittest
{
const char[] VAR = "TESTENVVAR";
const char[] VAL1 = "VAL1";
const char[] VAL2 = "VAL2";
assert(getEnv(VAR) is null);
setEnv(VAR, VAL1);
assert(getEnv(VAR) == VAL1);
setEnv(VAR, VAL2);
assert(getEnv(VAR) == VAL2);
setEnv(VAR, null);
assert(getEnv(VAR) is null);
setEnv(VAR, VAL1);
setEnv(VAR, "");
assert(getEnv(VAR) is null);
}