Hejsil / zig-clap

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

Breaking: Type parameter parsing #69

Closed Hejsil closed 2 years ago

Hejsil commented 2 years ago

The new usage pattern is something like this:

const clap = @import("clap");
const std = @import("std");

const debug = std.debug;
const io = std.io;
const process = std.process;

pub fn main() !void {
    // First we specify what parameters our program can take.
    // We can use `parseParam` to parse a string to a `Param(Help)`
    const params = comptime [_]clap.Param(clap.Help){
        clap.parseParam("-h, --help             Display this help and exit.") catch unreachable,
        clap.parseParam("-n, --number <INT>     An option parameter, which takes a value.") catch unreachable,
        clap.parseParam("-s, --string <STR>...  An option parameter which can be specified multiple times.") catch unreachable,
        clap.parseParam("<FILE>...") catch unreachable,
    };

    // Declare our own parsers which are used to map the argument strings to other
    // types.
    const parsers = comptime .{
        .STR = clap.parsers.string,
        .FILE = clap.parsers.string,
        .INT = clap.parsers.int(usize, 10),
    };

    var diag = clap.Diagnostic{};
    var res = clap.parse(clap.Help, &params, parsers, .{
        .diagnostic = &diag,
    }) catch |err| {
        diag.report(io.getStdErr().writer(), err) catch {};
        return err;
    };
    defer res.deinit();

    if (res.args.help)
        debug.print("--help\n", .{});
    if (res.args.number) |n|
        debug.print("--number = {}\n", .{n});
    for (res.args.string) |s|
        debug.print("--string = {s}\n", .{s});
    for (res.positionals) |pos|
        debug.print("{s}\n", .{pos});
}

One can use clap.parsers.default instead when they just want something that parses some types usize, str, f32 and the like.

@mattnite @kristoff-it I know that you guys use clap so some thoughts would be nice :)

Hejsil commented 2 years ago

Investigate not having this old untyped api and just make the typed api the default. Pretty sure it is a superset of the old one.

EDIT: This comment is out of date

Hejsil commented 2 years ago

One thing that is more of a pain now is if you want all your arguments to just be strings, but you want the value names to be something custom. Before, this was easier.