|
| 1 | +module helloworld; |
| 2 | + |
| 3 | +import configy.easy; |
| 4 | + |
| 5 | +import std.stdio; |
| 6 | +import std.typecons; |
| 7 | + |
| 8 | +struct FriendConfig |
| 9 | +{ |
| 10 | + string name; |
| 11 | + @Optional int age; |
| 12 | +} |
| 13 | + |
| 14 | +struct Config |
| 15 | +{ |
| 16 | + string user; |
| 17 | + SetInfo!int frequency; |
| 18 | + FriendConfig witness; |
| 19 | + FriendConfig[] attendee; |
| 20 | +} |
| 21 | + |
| 22 | +int main (string[] clargs) |
| 23 | +{ |
| 24 | + // This will read `args` (and modify it a la `getopt`), look up `config.yaml`, |
| 25 | + // and the environment using the binary name as prefix. |
| 26 | + CLIArgs args; |
| 27 | + args.parse(clargs); |
| 28 | + Nullable!Config configN = parseAppConfiguration!Config(args); |
| 29 | + if (configN.isNull()) |
| 30 | + return 1; |
| 31 | + auto config = configN.get(); |
| 32 | + |
| 33 | + writeln("Configuration: ", config); |
| 34 | + |
| 35 | + // From environment (`MYAPP_USER`) |
| 36 | + assert(config.user == "John Smith"); |
| 37 | + // From the command line |
| 38 | + assert(config.frequency == 42); |
| 39 | + assert(config.frequency.set == true); |
| 40 | + |
| 41 | + // Name comes from arg, age from env |
| 42 | + assert(config.witness == FriendConfig("Kevin Bacon", 121)); |
| 43 | + |
| 44 | + // From the configuration file |
| 45 | + assert(config.attendee.length == 2); |
| 46 | + assert(config.attendee[0] == FriendConfig("John Doe")); |
| 47 | + assert(config.attendee[1] == FriendConfig("Jany Dirkin", 27)); |
| 48 | + |
| 49 | + assert(clargs == [ "./myapp", "some", "positional", "arguments" ]); |
| 50 | + |
| 51 | + return 0; |
| 52 | +} |
| 53 | + |
| 54 | +private ConfigT parseAppConfiguration (ConfigT) (in CLIArgs args) |
| 55 | +{ |
| 56 | + import configy.backend.arguments; |
| 57 | + import configy.backend.environment; |
| 58 | + import configy.backend.multi; |
| 59 | + import configy.backend.node; |
| 60 | + import configy.backend.yaml; |
| 61 | + |
| 62 | + Mapping args_root = ArgumentBackend.make(args.overrides); |
| 63 | + Mapping env_root = EnvironmentBackend.make(`MYAPP`); |
| 64 | + Mapping yaml_root = parseFile(args.config_path); |
| 65 | + scope root = MultiBackend.make([args_root, env_root, yaml_root]); |
| 66 | + return parseConfig!ConfigT(root); |
| 67 | +} |
0 commit comments