zconfig

Library that easily serializes and deserializes config files or directly provide them through the command line based on a given annotated struct.

Members

Enums

ConfigFile
enum ConfigFile

Special option that allows pointing to another config file (ignoring the default). Can only be provided through the command line arguments. A config struct may only have one ConfigFile annotation. Otherwise an error is thrown.

OnlyCLI
enum OnlyCLI

Do not serialize and deserialize this option from the config file. The option will only be available through the command line arguments.

PassThrough
enum PassThrough

Getopt PassThrough.

Required
enum Required

Getopt Required. If the option is not provided an exception will be thrown.

Functions

getConfigArguments
string[] getConfigArguments(string filename, string[] args)

Creates an argument array that contains the options provided in the config file.

initializeConfig
ConfigType initializeConfig(string[] args, bool helpWanted)

Calls getopt with the provided args array. Usually you want to first call getConfigArguments and merge the command line arguments with the config arguments. Which then get passed to this function.

writeExampleConfigFile
void writeExampleConfigFile(string filename)

Writes an example config file to the provided filename. If a struct member does not provide a default value then .init is used as the default value.

Structs

Desc
struct Desc

Adds a description to the option which will be shown in the command line when -h is provided and in the config file.

Section
struct Section

Describes a section. When a struct member is annotated with it then the member will be written underneath [section].

Short
struct Short

Provides an alternative option name. This is mostly convenient on the command line.

Examples

Basic use-case

struct MyConfig
{
    @Desc("My number.")
    int number;
    @Desc("My bool.")
    bool toggle;
}

enum usage = "My program version 1.0 does things.";

int main(string[] args)
{
    string[] configArgs = getConfigArguments!Config("myconf.conf", args);

    if (configArgs.length > 0)
    {
        import std.array : insertInPlace;

        // Prepend them into the command line args
        args.insertInPlace(1, configArgs);
    }

    MyConfig conf;
    bool helpWanted = false;

    import std.getopt : GetOptException;
    try
    {
        conf = initializeConfig!(MyConfig, usage)(args, helpWanted);
    }
    catch (GetOptException e)
    {
        import std.stdio : stderr;
        stderr.writefln("Invalid argument: %s", e.msg);
        return 1;
    }

    if (helpWanted)
    {
        return 0;
    }
}

Meta