Skip to content

Commit

Permalink
Return unused CLI args
Browse files Browse the repository at this point in the history
  • Loading branch information
Mihails Strasuns authored and mihails-strasuns committed Jan 3, 2019
1 parent 39d3977 commit 33df09c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
27 changes: 20 additions & 7 deletions source/simpleconfig/args.d
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ module simpleconfig.args;
import simpleconfig.attributes;

/// See `simpleconfig.readConfiguration`
public void readConfiguration (S) (ref S dst)
public string[] readConfiguration (S) (ref S dst)
{
static assert (is(S == struct), "Only structs are supported as configuration target");

import core.runtime;

readConfigurationImpl(dst, Runtime.args());
import core.runtime;
return readConfigurationImpl(dst, Runtime.args());
}

private template resolveName (alias Field)
Expand Down Expand Up @@ -37,16 +36,24 @@ unittest
static assert (resolveName!(S.field2).single == 'r');
}

private void readConfigurationImpl (S) (ref S dst, string[] src)
private string[] readConfigurationImpl (S) (ref S dst, string[] src)
{
import std.traits;
import std.algorithm;
import std.range.primitives;
import std.conv;

string[] remaining_args;
bool assign = false;

rt: foreach (idx, arg; src)
{
bool assign = false;
if (assign)
{
// skip argument of already processed flag
assign = false;
continue;
}

static foreach (Field; getSymbolsByUDA!(S, CLI))
{
Expand All @@ -62,7 +69,11 @@ private void readConfigurationImpl (S) (ref S dst, string[] src)
continue rt;
}
}

remaining_args ~= arg;
}

return remaining_args;
}

unittest
Expand All @@ -80,7 +91,7 @@ unittest

Config config;

readConfigurationImpl(config, [
auto remaining = readConfigurationImpl(config, [
"--field1", "value1",
"--alias", "42",
"-l", "value3",
Expand All @@ -91,4 +102,6 @@ unittest
assert(config.field2 == 42);
assert(config.field3 == "value3");
assert(config.field4 == "");

assert(remaining == [ "--field4", "ignored" ]);
}
9 changes: 7 additions & 2 deletions source/simpleconfig/package.d
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,24 @@ public import simpleconfig.attributes;
Params:
dst = struct instance which will store configuration data
and defines how it should be read
Returns:
CLI argument array with processed flags removed
*/
void readConfiguration (S) (ref S dst)
string[] readConfiguration (S) (ref S dst)
{
static assert (is(S == struct), "Only structs are supported as configuration target");

static import simpleconfig.file;
simpleconfig.file.readConfiguration(dst);

static import simpleconfig.args;
simpleconfig.args.readConfiguration(dst);
auto args = simpleconfig.args.readConfiguration(dst);

static if (is(typeof(S.finalizeConfig())))
dst.finalizeConfig();

return args;
}

///
Expand Down

0 comments on commit 33df09c

Please sign in to comment.