Hejsil / zig-clap

Command line argument parsing library
MIT License
939 stars 67 forks source link

Custom argument to value parsers #3

Closed Hejsil closed 6 years ago

Hejsil commented 6 years ago

Currently, we are able to parse strings to a few different types depending on the type of the fields we are trying to set.

I don't think we should try to support more than the basic types (and []const u8), but the user should be able to provide custom parser:

const Options = struct {
    a: std.Arraylist([]const u8),
};

fn addToArraylist(comptime T: type, arraylist: &T, arg: []const u8) !void {
    try arraylist.append(arg);
}

const parser = comptime Clap(Options).Builder
    .init(
        Options {
            .a = std.Arraylist([]const u8).init(std.debug.global_allocator),
        }
    )
    .command(
        Command.Builder
            .init("command")
            .arguments(
                []Argument {
                    Argument.Builder
                        .init("a")
                        .help("Add to 'a'")
                        .short('a')
                        .takesValue(addToArraylist)
                        .build(),
                }
            )
            .build()
    )
    .build();

This would allow command -a something -a "something else" to save both values passed to a.

This does not go against the goal of being a non-allocating clap. zig-clap will not allocate by default, but we can't stop users from allocating in custom argument parsing function.

Hejsil commented 6 years ago

We could replace the current strToValue function, with a set of standard parsers provided by zig-clap.