flags: rewrite to allow [:0]const u8 arguments

This also cleans up the code by using @Type(), eliminating the need
for the argFlag() and boolFlag() functions.

Allowing [:0]const u8 arguments makes this parser useful for
river-control commands as well.
This commit is contained in:
Isaac Freund 2022-12-28 19:47:09 +01:00
parent ad1dbb1180
commit 16cbe5f469
No known key found for this signature in database
GPG Key ID: 86DED400DDFD7A11
4 changed files with 99 additions and 104 deletions

View File

@ -1,96 +1,88 @@
// This file is part of river, a dynamic tiling wayland compositor. // Zero allocation argument parsing for unix-like systems.
// Released under the Zero Clause BSD (0BSD) license:
// //
// Copyright 2021 The River Developers // Copyright 2023 Isaac Freund
// //
// This program is free software: you can redistribute it and/or modify // Permission to use, copy, modify, and/or distribute this software for any
// it under the terms of the GNU General Public License as published by // purpose with or without fee is hereby granted.
// the Free Software Foundation, version 3.
// //
// This program is distributed in the hope that it will be useful, // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// but WITHOUT ANY WARRANTY; without even the implied warranty of // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// GNU General Public License for more details. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// You should have received a copy of the GNU General Public License // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// along with this program. If not, see <https://www.gnu.org/licenses/>. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
const std = @import("std"); const std = @import("std");
const cstr = std.cstr; const mem = std.mem;
pub const Flag = struct { pub const Flag = struct {
name: [*:0]const u8, name: []const u8,
kind: enum { boolean, arg }, 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 { return struct {
const Self = @This(); pub const Result = struct {
const FlagData = struct {
name: [*:0]const u8,
value: union {
boolean: bool,
arg: ?[*:0]const u8,
},
};
/// Remaining args after the recognized flags /// Remaining args after the recognized flags
args: [][*:0]const u8, args: []const Arg,
/// Data obtained from parsed flags /// Data obtained from parsed flags
flag_data: [flags.len]FlagData = blk: { flags: Flags,
// Init all flags to false/null
var flag_data: [flags.len]FlagData = undefined; pub const Flags = flags_type: {
inline for (flags) |flag, i| { var fields: []const std.builtin.TypeInfo.StructField = &.{};
flag_data[i] = switch (flag.kind) { inline for (flags) |flag| {
const field: std.builtin.TypeInfo.StructField = switch (flag.kind) {
.boolean => .{ .boolean => .{
.name = flag.name, .name = flag.name,
.value = .{ .boolean = false }, .field_type = bool,
.default_value = false,
.is_comptime = false,
.alignment = @alignOf(bool),
}, },
.arg => .{ .arg => .{
.name = flag.name, .name = flag.name,
.value = .{ .arg = null }, .field_type = ?[:0]const u8,
.default_value = @as(??[:0]const u8, @as(?[:0]const u8, null)),
.is_comptime = false,
.alignment = @alignOf(?[:0]const u8),
}, },
}; };
fields = fields ++ [_]std.builtin.TypeInfo.StructField{field};
} }
break :blk flag_data; break :flags_type @Type(.{ .Struct = .{
}, .layout = .Auto,
.fields = fields,
pub fn boolFlag(self: Self, flag_name: [*:0]const u8) bool { .decls = &.{},
for (self.flag_data) |flag_data| { .is_tuple = false,
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);
}
}
unreachable; // Invalid flag_name
}
}; };
}
pub fn parse(args: [][*:0]const u8, comptime flags: []const Flag) !ParseResult(flags) { pub fn parse(args: []const Arg) !Result {
var ret: ParseResult(flags) = .{ .args = undefined }; var result_flags: Result.Flags = .{};
var arg_idx: usize = 0; var i: usize = 0;
while (arg_idx < args.len) : (arg_idx += 1) { while (i < args.len) : (i += 1) {
var parsed_flag = false; var parsed_flag = false;
inline for (flags) |flag, flag_idx| { inline for (flags) |flag| {
if (cstr.cmp(flag.name, args[arg_idx]) == 0) { if (mem.eql(u8, flag.name, mem.span(args[i]))) {
switch (flag.kind) { switch (flag.kind) {
.boolean => ret.flag_data[flag_idx].value.boolean = true, .boolean => @field(result_flags, flag.name) = true,
.arg => { .arg => {
arg_idx += 1; i += 1;
if (arg_idx == args.len) { if (i == args.len) {
std.log.err("option '" ++ flag.name ++ std.log.err("option '" ++ flag.name ++
"' requires an argument but none was provided!", .{}); "' requires an argument but none was provided!", .{});
return error.MissingFlagArgument; return error.MissingFlagArgument;
} }
ret.flag_data[flag_idx].value.arg = args[arg_idx]; @field(result_flags, flag.name) = mem.span(args[i]);
}, },
} }
parsed_flag = true; parsed_flag = true;
@ -99,7 +91,10 @@ pub fn parse(args: [][*:0]const u8, comptime flags: []const Flag) !ParseResult(f
if (!parsed_flag) break; if (!parsed_flag) break;
} }
ret.args = args[arg_idx..]; return Result{
.args = args[i..],
return ret; .flags = result_flags,
};
}
};
} }

View File

@ -44,16 +44,16 @@ pub var server: Server = undefined;
pub fn main() anyerror!void { pub fn main() anyerror!void {
// This line is here because of https://github.com/ziglang/zig/issues/7807 // This line is here because of https://github.com/ziglang/zig/issues/7807
const argv: [][*:0]const u8 = os.argv; const argv: [][*:0]const u8 = os.argv;
const result = flags.parse(argv[1..], &[_]flags.Flag{ const result = flags.parser([*:0]const u8, &.{
.{ .name = "-h", .kind = .boolean }, .{ .name = "-h", .kind = .boolean },
.{ .name = "-version", .kind = .boolean }, .{ .name = "-version", .kind = .boolean },
.{ .name = "-c", .kind = .arg }, .{ .name = "-c", .kind = .arg },
.{ .name = "-log-level", .kind = .arg }, .{ .name = "-log-level", .kind = .arg },
}) catch { }).parse(argv[1..]) catch {
try io.getStdErr().writeAll(usage); try io.getStdErr().writeAll(usage);
os.exit(1); os.exit(1);
}; };
if (result.boolFlag("-h")) { if (result.flags.@"-h") {
try io.getStdOut().writeAll(usage); try io.getStdOut().writeAll(usage);
os.exit(0); os.exit(0);
} }
@ -63,11 +63,11 @@ pub fn main() anyerror!void {
os.exit(1); os.exit(1);
} }
if (result.boolFlag("-version")) { if (result.flags.@"-version") {
try io.getStdOut().writeAll(build_options.version ++ "\n"); try io.getStdOut().writeAll(build_options.version ++ "\n");
os.exit(0); os.exit(0);
} }
if (result.argFlag("-log-level")) |level| { if (result.flags.@"-log-level") |level| {
if (mem.eql(u8, level, std.log.Level.err.asText())) { if (mem.eql(u8, level, std.log.Level.err.asText())) {
runtime_log_level = .err; runtime_log_level = .err;
} else if (mem.eql(u8, level, std.log.Level.warn.asText())) { } else if (mem.eql(u8, level, std.log.Level.warn.asText())) {
@ -83,7 +83,7 @@ pub fn main() anyerror!void {
} }
} }
const startup_command = blk: { const startup_command = blk: {
if (result.argFlag("-c")) |command| { if (result.flags.@"-c") |command| {
break :blk try util.gpa.dupeZ(u8, command); break :blk try util.gpa.dupeZ(u8, command);
} else { } else {
break :blk try defaultInitPath(); break :blk try defaultInitPath();

View File

@ -65,18 +65,18 @@ pub fn main() !void {
fn _main() !void { fn _main() !void {
// This line is here because of https://github.com/ziglang/zig/issues/7807 // This line is here because of https://github.com/ziglang/zig/issues/7807
const argv: [][*:0]const u8 = os.argv; const argv: [][*:0]const u8 = os.argv;
const result = flags.parse(argv[1..], &[_]flags.Flag{ const result = flags.parser([*:0]const u8, &.{
.{ .name = "-h", .kind = .boolean }, .{ .name = "-h", .kind = .boolean },
.{ .name = "-version", .kind = .boolean }, .{ .name = "-version", .kind = .boolean },
}) catch { }).parse(argv[1..]) catch {
try io.getStdErr().writeAll(usage); try io.getStdErr().writeAll(usage);
os.exit(1); os.exit(1);
}; };
if (result.boolFlag("-h")) { if (result.flags.@"-h") {
try io.getStdOut().writeAll(usage); try io.getStdOut().writeAll(usage);
os.exit(0); os.exit(0);
} }
if (result.boolFlag("-version")) { if (result.flags.@"-version") {
try io.getStdOut().writeAll(@import("build_options").version ++ "\n"); try io.getStdOut().writeAll(@import("build_options").version ++ "\n");
os.exit(0); os.exit(0);
} }

View File

@ -306,7 +306,7 @@ const Output = struct {
pub fn main() !void { pub fn main() !void {
// https://github.com/ziglang/zig/issues/7807 // https://github.com/ziglang/zig/issues/7807
const argv: [][*:0]const u8 = os.argv; const argv: [][*:0]const u8 = os.argv;
const result = flags.parse(argv[1..], &[_]flags.Flag{ const result = flags.parser([*:0]const u8, &[_]flags.Flag{
.{ .name = "-h", .kind = .boolean }, .{ .name = "-h", .kind = .boolean },
.{ .name = "-version", .kind = .boolean }, .{ .name = "-version", .kind = .boolean },
.{ .name = "-view-padding", .kind = .arg }, .{ .name = "-view-padding", .kind = .arg },
@ -314,37 +314,37 @@ pub fn main() !void {
.{ .name = "-main-location", .kind = .arg }, .{ .name = "-main-location", .kind = .arg },
.{ .name = "-main-count", .kind = .arg }, .{ .name = "-main-count", .kind = .arg },
.{ .name = "-main-ratio", .kind = .arg }, .{ .name = "-main-ratio", .kind = .arg },
}) catch { }).parse(argv[1..]) catch {
try std.io.getStdErr().writeAll(usage); try std.io.getStdErr().writeAll(usage);
os.exit(1); os.exit(1);
}; };
if (result.boolFlag("-h")) { if (result.flags.@"-h") {
try std.io.getStdOut().writeAll(usage); try std.io.getStdOut().writeAll(usage);
os.exit(0); os.exit(0);
} }
if (result.args.len != 0) fatalPrintUsage("unknown option '{s}'", .{result.args[0]}); if (result.args.len != 0) fatalPrintUsage("unknown option '{s}'", .{result.args[0]});
if (result.boolFlag("-version")) { if (result.flags.@"-version") {
try std.io.getStdOut().writeAll(@import("build_options").version ++ "\n"); try std.io.getStdOut().writeAll(@import("build_options").version ++ "\n");
os.exit(0); os.exit(0);
} }
if (result.argFlag("-view-padding")) |raw| { if (result.flags.@"-view-padding") |raw| {
view_padding = fmt.parseUnsigned(u31, raw, 10) catch view_padding = fmt.parseUnsigned(u31, raw, 10) catch
fatalPrintUsage("invalid value '{s}' provided to -view-padding", .{raw}); fatalPrintUsage("invalid value '{s}' provided to -view-padding", .{raw});
} }
if (result.argFlag("-outer-padding")) |raw| { if (result.flags.@"-outer-padding") |raw| {
outer_padding = fmt.parseUnsigned(u31, raw, 10) catch outer_padding = fmt.parseUnsigned(u31, raw, 10) catch
fatalPrintUsage("invalid value '{s}' provided to -outer-padding", .{raw}); fatalPrintUsage("invalid value '{s}' provided to -outer-padding", .{raw});
} }
if (result.argFlag("-main-location")) |raw| { if (result.flags.@"-main-location") |raw| {
default_main_location = std.meta.stringToEnum(Location, raw) orelse default_main_location = std.meta.stringToEnum(Location, raw) orelse
fatalPrintUsage("invalid value '{s}' provided to -main-location", .{raw}); fatalPrintUsage("invalid value '{s}' provided to -main-location", .{raw});
} }
if (result.argFlag("-main-count")) |raw| { if (result.flags.@"-main-count") |raw| {
default_main_count = fmt.parseUnsigned(u31, raw, 10) catch default_main_count = fmt.parseUnsigned(u31, raw, 10) catch
fatalPrintUsage("invalid value '{s}' provided to -main-count", .{raw}); fatalPrintUsage("invalid value '{s}' provided to -main-count", .{raw});
} }
if (result.argFlag("-main-ratio")) |raw| { if (result.flags.@"-main-ratio") |raw| {
default_main_ratio = fmt.parseFloat(f64, raw) catch { default_main_ratio = fmt.parseFloat(f64, raw) catch {
fatalPrintUsage("invalid value '{s}' provided to -main-ratio", .{raw}); fatalPrintUsage("invalid value '{s}' provided to -main-ratio", .{raw});
}; };