~novakane/rivercarro

913e829d7cda39ca3add411a70dbbb4d40f01eea — Hugo Machet 1 year, 1 month ago 5423e6e
common: Update flags to latest version
2 files changed, 88 insertions(+), 96 deletions(-)

M common/flags.zig
M src/main.zig
M common/flags.zig => common/flags.zig +68 -74
@@ 1,7 1,7 @@
// Zero allocation argument parsing for unix-like systems.
// Released under the Zero Clause BSD (0BSD) license:
//
// Copyright 2022 Isaac Freund
// Copyright 2023 Isaac Freund
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.


@@ 15,91 15,85 @@
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

const std = @import("std");
const cstr = std.cstr;
const mem = std.mem;

pub const Flag = struct {
    name: [*:0]const u8,
    name: []const u8,
    kind: enum { boolean, arg },
};

pub fn ParseResult(comptime flags: []const Flag) type {
pub fn parser(comptime Arg: type, comptime flags: []const Flag) type {
    switch (Arg) {
        // TODO consider allowing []const u8
        [:0]const u8, [*:0]const u8 => {}, // ok
        else => @compileError("invalid argument type: " ++ @typeName(Arg)),
    }
    return struct {
        const Self = @This();

        const FlagData = struct {
            name: [*:0]const u8,
            value: union {
                boolean: bool,
                arg: ?[*:0]const u8,
            },
        };

        /// Remaining args after the recognized flags
        args: [][*:0]const u8,
        /// Data obtained from parsed flags
        flag_data: [flags.len]FlagData = blk: {
            // Init all flags to false/null
            var flag_data: [flags.len]FlagData = undefined;
            inline for (flags) |flag, i| {
                flag_data[i] = switch (flag.kind) {
                    .boolean => .{
                        .name = flag.name,
                        .value = .{ .boolean = false },
                    },
                    .arg => .{
                        .name = flag.name,
                        .value = .{ .arg = null },
                    },
                };
            }
            break :blk flag_data;
        },
        pub const Result = struct {
            /// Remaining args after the recognized flags
            args: []const Arg,
            /// Data obtained from parsed flags
            flags: Flags,

        pub fn boolFlag(self: Self, flag_name: [*:0]const u8) bool {
            for (self.flag_data) |flag_data| {
                if (cstr.cmp(flag_data.name, flag_name) == 0) return flag_data.value.boolean;
            }
            unreachable; // Invalid flag_name
        }

        pub fn argFlag(self: Self, flag_name: [*:0]const u8) ?[:0]const u8 {
            for (self.flag_data) |flag_data| {
                if (cstr.cmp(flag_data.name, flag_name) == 0) {
                    return std.mem.span(flag_data.value.arg);
            pub const Flags = flags_type: {
                var fields: []const std.builtin.Type.StructField = &.{};
                inline for (flags) |flag| {
                    const field: std.builtin.Type.StructField = switch (flag.kind) {
                        .boolean => .{
                            .name = flag.name,
                            .field_type = bool,
                            .default_value = &false,
                            .is_comptime = false,
                            .alignment = @alignOf(bool),
                        },
                        .arg => .{
                            .name = flag.name,
                            .field_type = ?[:0]const u8,
                            .default_value = &@as(?[:0]const u8, null),
                            .is_comptime = false,
                            .alignment = @alignOf(?[:0]const u8),
                        },
                    };
                    fields = fields ++ [_]std.builtin.Type.StructField{field};
                }
            }
            unreachable; // Invalid flag_name
        }
    };
}
                break :flags_type @Type(.{ .Struct = .{
                    .layout = .Auto,
                    .fields = fields,
                    .decls = &.{},
                    .is_tuple = false,
                } });
            };
        };

pub fn parse(args: [][*:0]const u8, comptime flags: []const Flag) !ParseResult(flags) {
    var ret: ParseResult(flags) = .{ .args = undefined };
        pub fn parse(args: []const Arg) !Result {
            var result_flags: Result.Flags = .{};

    var arg_idx: usize = 0;
    while (arg_idx < args.len) : (arg_idx += 1) {
        var parsed_flag = false;
        inline for (flags) |flag, flag_idx| {
            if (cstr.cmp(flag.name, args[arg_idx]) == 0) {
                switch (flag.kind) {
                    .boolean => ret.flag_data[flag_idx].value.boolean = true,
                    .arg => {
                        arg_idx += 1;
                        if (arg_idx == args.len) {
                            std.log.err("option '" ++ flag.name ++
                                "' requires an argument but none was provided!", .{});
                            return error.MissingFlagArgument;
            var i: usize = 0;
            outer: while (i < args.len) : (i += 1) {
                inline for (flags) |flag| {
                    if (mem.eql(u8, "-" ++ flag.name, mem.span(args[i]))) {
                        switch (flag.kind) {
                            .boolean => @field(result_flags, flag.name) = true,
                            .arg => {
                                i += 1;
                                if (i == args.len) {
                                    std.log.err("option '-" ++ flag.name ++
                                        "' requires an argument but none was provided!", .{});
                                    return error.MissingFlagArgument;
                                }
                                @field(result_flags, flag.name) = mem.span(args[i]);
                            },
                        }
                        ret.flag_data[flag_idx].value.arg = args[arg_idx];
                    },
                        continue :outer;
                    }
                }
                parsed_flag = true;
                break;
            }
        }
        if (!parsed_flag) break;
    }

    ret.args = args[arg_idx..];

    return ret;
            return Result{
                .args = args[i..],
                .flags = result_flags,
            };
        }
    };
}

M src/main.zig => src/main.zig +20 -22
@@ 396,52 396,50 @@ const Output = struct {
};

pub fn main() !void {
    // https://github.com/ziglang/zig/issues/7807
    const argv: [][*:0]const u8 = os.argv;
    const res = flags.parse(argv[1..], &[_]flags.Flag{
        .{ .name = "-h", .kind = .boolean },
        .{ .name = "-version", .kind = .boolean },
        .{ .name = "-no-smart-gaps", .kind = .boolean },
        .{ .name = "-inner-gaps", .kind = .arg },
        .{ .name = "-outer-gaps", .kind = .arg },
        .{ .name = "-main-location", .kind = .arg },
        .{ .name = "-main-count", .kind = .arg },
        .{ .name = "-main-ratio", .kind = .arg },
        .{ .name = "-width-ratio", .kind = .arg },
    }) catch {
    const res = flags.parser([*:0]const u8, &.{
        .{ .name = "h", .kind = .boolean },
        .{ .name = "version", .kind = .boolean },
        .{ .name = "no-smart-gaps", .kind = .boolean },
        .{ .name = "inner-gaps", .kind = .arg },
        .{ .name = "outer-gaps", .kind = .arg },
        .{ .name = "main-location", .kind = .arg },
        .{ .name = "main-count", .kind = .arg },
        .{ .name = "main-ratio", .kind = .arg },
        .{ .name = "width-ratio", .kind = .arg },
    }).parse(os.argv[1..]) catch {
        try std.io.getStdErr().writeAll(usage);
        os.exit(1);
    };
    if (res.args.len != 0) fatal_usage("Unknown option '{s}'", .{res.args[0]});

    if (res.boolFlag("-h")) {
    if (res.flags.h) {
        try io.getStdOut().writeAll(usage);
        os.exit(0);
    }
    if (res.boolFlag("-version")) {
    if (res.flags.version) {
        try io.getStdOut().writeAll(build_options.version ++ "\n");
        os.exit(0);
    }
    if (res.boolFlag("-no-smart-gaps")) {
    if (res.flags.@"no-smart-gaps") {
        cfg.smart_gaps = false;
    }
    if (res.argFlag("-inner-gaps")) |raw| {
    if (res.flags.@"inner-gaps") |raw| {
        cfg.inner_gaps = fmt.parseUnsigned(u31, raw, 10) catch
            fatal_usage("Invalid value '{s}' provided to -inner-gaps", .{raw});
    }
    if (res.argFlag("-outer-gaps")) |raw| {
    if (res.flags.@"outer-gaps") |raw| {
        cfg.outer_gaps = fmt.parseUnsigned(u31, raw, 10) catch
            fatal_usage("Invalid value '{s}' provided to -outer-gaps", .{raw});
    }
    if (res.argFlag("-main-location")) |raw| {
    if (res.flags.@"main-location") |raw| {
        cfg.main_location = std.meta.stringToEnum(Location, raw) orelse
            fatal_usage("Invalid value '{s}' provided to -main-location", .{raw});
    }
    if (res.argFlag("-main-count")) |raw| {
    if (res.flags.@"main-count") |raw| {
        cfg.main_count = fmt.parseUnsigned(u31, raw, 10) catch
            fatal_usage("Invalid value '{s}' provided to -main-count", .{raw});
    }
    if (res.argFlag("-main-ratio")) |raw| {
    if (res.flags.@"main-ratio") |raw| {
        cfg.main_ratio = fmt.parseFloat(f64, raw) catch {
            fatal_usage("Invalid value '{s}' provided to -main-ratio", .{raw});
        };


@@ 449,7 447,7 @@ pub fn main() !void {
            fatal_usage("Invalid value '{s}' provided to -main-ratio", .{raw});
        }
    }
    if (res.argFlag("-width-ratio")) |raw| {
    if (res.flags.@"width-ratio") |raw| {
        cfg.width_ratio = fmt.parseFloat(f64, raw) catch {
            fatal_usage("Invalid value '{s}' provided to -width-ratio", .{raw});
        };