Skip to content

Commit

Permalink
feat: Allow for the assignment separator to be configured
Browse files Browse the repository at this point in the history
  • Loading branch information
Hejsil committed Jul 18, 2024
1 parent 39fce9b commit 0ba0c9a
Show file tree
Hide file tree
Showing 4 changed files with 188 additions and 116 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ pub fn main() !void {
var res = clap.parse(clap.Help, &params, parsers, .{
.diagnostic = &diag,
.allocator = gpa.allocator(),
// The assignment separator can be configured. `--number=1` and `--number:1` is now
// allowed.
.assignment_separators = "=:",
}) catch |err| {
diag.report(io.getStdErr().writer(), err) catch {};
return err;
Expand Down
23 changes: 23 additions & 0 deletions clap.zig
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ test "clap" {
testing.refAllDecls(@This());
}

pub const default_assignment_separators = "=";

/// The names a `Param` can have.
pub const Names = struct {
/// '-' prefix
Expand Down Expand Up @@ -643,6 +645,7 @@ test "Diagnostic.report" {
pub const ParseOptions = struct {
allocator: mem.Allocator,
diagnostic: ?*Diagnostic = null,
assignment_separators: []const u8 = default_assignment_separators,
};

/// Same as `parseEx` but uses the `args.OsIterator` by default.
Expand All @@ -662,6 +665,7 @@ pub fn parse(
// Let's reuse the arena from the `OSIterator` since we already have it.
.allocator = arena.allocator(),
.diagnostic = opt.diagnostic,
.assignment_separators = opt.assignment_separators,
});

return Result(Id, params, value_parsers){
Expand Down Expand Up @@ -733,6 +737,7 @@ pub fn parseEx(
.params = params,
.iter = iter,
.diagnostic = opt.diagnostic,
.assignment_separators = opt.assignment_separators,
};
while (try stream.next()) |arg| {
// TODO: We cannot use `try` inside the inline for because of a compiler bug that
Expand Down Expand Up @@ -955,6 +960,24 @@ test "str and u64" {
defer res.deinit();
}

test "different assignment separators" {
const params = comptime parseParamsComptime(
\\-a, --aa <usize>...
\\
);

var iter = args.SliceIterator{
.args = &.{ "-a=0", "--aa=1", "-a:2", "--aa:3" },
};
var res = try parseEx(Help, &params, parsers.default, &iter, .{
.allocator = testing.allocator,
.assignment_separators = "=:",
});
defer res.deinit();

try testing.expectEqualSlices(usize, &.{ 0, 1, 2, 3 }, res.args.aa);
}

test "everything" {
const params = comptime parseParamsComptime(
\\-a, --aa
Expand Down
Loading

0 comments on commit 0ba0c9a

Please sign in to comment.