dotenv 0.1.0

dotenv implementation for D. Simplifies handling environment variables.


To use this package, run the following command in your project's root directory:

dotenv

dotenv implementation for D. Simplifies handling environment variables.

Environment variables are one of the factors of the 12 Factor App. dotenv helps you manage different environments, and extract data that is sensitive or likely to change into environment variables.

Getting Started

Create a .env file at the root directory of your app. An example might look like,

# MySQL credentials.
MYSQL_HOST = localhost
MYSQL_PORT = 3306
MYSQL_USER = root
MYSQL_PASS =

Variables are declared in NAME=value format, and lines starting with '#' are treated as comments.

Loading Env

Once you've created your file, it can be loaded using Env.load. Env.load also takes additional arguments if you need to customize its behaviour.

import dotenv;

void main()
{
    // Loads the .env file
    Env.load;

    // Loads from a different file name
    Env.load(".my-env");

    // Do not load system environment variables
    Env.load(".env", false);

    // Load only system environment variables
    Env.loadSystem;
}

By default, Env will also load the system environment variables. Multiple calls to Env.load can be made to load multiple dotenv files. If multiple variables are loaded under the same name, the newer value will override the previous one.

Accessing Variables

Once loaded, Env behaves like an associative-array. Variables are accessed by name (and are case-insensitive), and their values returned as strings.

Connection connectDB()
{
    return new Connection(
        Env["MYSQL_HOST"], Env["MYSQL_PORT"],
        Env["MYSQL_USER"], Env["MYSQL_PASS"]
    );
}

Env also provides property-like access (using opDispatch) to variables, but only to their uppercase names. The properties also accept an optional template argument, to perform a type conversion.

void dbInfo()
{
    string host = Env.MYSQL_HOST;
    ushort port = Env.MYSQL_PORT!ushort;

    // . . .
}

Modifying Variables

Since Env behaves like an associative-array, it can also be modified in much the same way.

unittest
{
    Env.load(".test-env");

    Env["MYSQL_USER"] = "test_user";
    Env.remove("MYSQL_PASS");

    // . . .
}

It also provides empty, length, keys, and values properties that behave as expected.

Planned Features

  • Support for JSON/SDLang dotenv files, for more complex variables
  • More customization during initialization

License

MIT

Authors:
  • Mihail-K
Dependencies:
none
Versions:
0.1.1 2016-May-16
0.1.0 2016-May-12
~master 2016-May-16
Show all 3 versions
Download Stats:
  • 0 downloads today

  • 3 downloads this week

  • 3 downloads this month

  • 98 downloads total

Score:
0.9
Short URL:
dotenv.dub.pm