Skip to content

Instantly share code, notes, and snippets.

@sirtony
Last active August 29, 2015 14:08
Show Gist options
  • Save sirtony/bda1b47ccc62484f7e78 to your computer and use it in GitHub Desktop.
Save sirtony/bda1b47ccc62484f7e78 to your computer and use it in GitHub Desktop.
A simple class to modify environment variables (Windows-only).
module envy;
version( Windows ):
private {
import std.windows.registry;
}
private enum ENV_KEY = "Environment";
public enum EnvironmentScope
{
System,
User,
}
public final class EnvironmentVariable
{
private Key _root;
private string _name;
private string _value;
public string name() @property
{
return this._name;
}
public string value() @property
{
return this._value;
}
public void value( string str ) @property
{
this._value = str;
}
public this( string name, EnvironmentScope scope_ = EnvironmentScope.User )
{
this._name = name;
string[] path = [ ];
final switch( scope_ )
{
case EnvironmentScope.System:
this._root = Registry.localMachine();
path = [ "SYSTEM", "CurrentControlSet", "Control", "Session Manager" ];
break;
case EnvironmentScope.User:
this._root = Registry.currentUser();
break;
}
path ~= ENV_KEY;
foreach( n; path )
this._root = this._root.getKey( n );
this.value = this._root.getValue( name ).value_EXPAND_SZ;
}
public EnvironmentVariable opAssign( string str )
{
this.value = str;
return this;
}
public EnvironmentVariable opOpAssign( string op )( string str ) if( op == "~=" )
{
this.value ~= str;
return this;
}
public void remove()
{
this._root.deleteValue( this.name );
this._root.flush();
}
public void update()
{
this._root.setValue( this.name, this.value );
this._root.flush();
}
}
import std.stdio : writeln;
import std.path : pathSeparator;
import std.array : split;
import envy;
//Prints the PATH environment variable for the current user.
void main()
{
auto path = new EnvironmentVariable( "PATH" );
path.value.split( pathSeparator ).writeln();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment