Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298const std = @import("std");const config = @import("config");
const Options = @This();
output: []const u8 = "",relative: bool = false,append: bool = false,arguments: []const []const u8 = undefined,
const Option = enum(u8) { output = 'o', relative = 'r', append = 'a', version = 'V', help = 'h',};
fn usage(stderr: *std.Io.Writer) !void { try stderr.print("{s}", .{"Usage: " ++ config.name ++ " [-o OUTPUT] [-a] [-r] FILES...\n"});}
pub fn parse(stderr: *std.Io.Writer, allocator: std.mem.Allocator, args: std.process.Args) !Options { var it = try args.iterateAllocator(allocator); defer it.deinit();
_ = it.skip();
var errmsg: ?[]const u8 = null; return parseIter(allocator, &it, &errmsg) catch |err| { if (errmsg) |e| { try stderr.print("{s}: {s}\n", .{ config.name, e }); allocator.free(e); }
switch (err) { error.ShowHelp, error.InvalidOption, error.MissingArgument => try usage(stderr), error.ShowVersion => { try stderr.print("{s} {s}\n", .{ config.name, config.version }); }, else => {}, }
return err; };}
fn parseIter(allocator: std.mem.Allocator, iter: anytype, errmsg: *?[]const u8) !Options { var arguments: std.ArrayList([]const u8) = .empty; errdefer { for (arguments.items) |arg| allocator.free(arg); arguments.deinit(allocator); }
var options: Options = .{}; errdefer if (options.output.len > 0) allocator.free(options.output);
var next_option: ?Option = null; while (iter.next()) |arg| { if (std.mem.startsWith(u8, arg, "-") and arg.len > 1) { for (arg[1..]) |c| { if (next_option) |opt| { errmsg.* = try allocator.print( "Option '{c}' missing required argument.", .{@backingInt(opt)}, ); return error.MissingArgument; }
if (std.enums.fromInt(Option, c)) |opt| { switch (opt) { .output => next_option = opt, .relative => options.relative = true, .append => options.append = true, .help => return error.ShowHelp, .version => return error.ShowVersion, } } else { errmsg.* = try allocator.print("Unexpected option: '{c}'.", .{c}); return error.InvalidOption; } } } else if (next_option) |opt| { switch (opt) { .output => options.output = try allocator.dupe(u8, arg), // Unreachable: next_option is only ever set with the enum // values above else => unreachable, } next_option = null; } else { const a = try allocator.dupe(u8, arg); errdefer allocator.free(a); try arguments.append(allocator, a); } }
if (next_option) |opt| { errmsg.* = try allocator.print( "Option '{c}' missing required argument.", .{@backingInt(opt)}, ); return error.MissingArgument; }
if (options.output.len == 0) { options.output = try allocator.dupe(u8, "tags"); }
if (arguments.items.len == 0) { errmsg.* = try allocator.dupe(u8, "No files specified."); return error.MissingArgument; }
options.arguments = try arguments.toOwnedSlice(allocator); return options;}
pub fn deinit(self: *Options, allocator: std.mem.Allocator) void { if (self.output.len > 0) allocator.free(self.output); for (self.arguments) |arg| allocator.free(arg); allocator.free(self.arguments); self.* = undefined;}
const TestIterator = struct { args: []const []const u8, index: usize,
fn init(args: []const []const u8) TestIterator { return .{ .args = args, .index = 0, }; }
fn next(self: *TestIterator) ?[]const u8 { if (self.index < self.args.len) { defer self.index += 1; return self.args[self.index]; }
return null; }};
test "parseIter" { var errmsg: ?[]const u8 = null;
{ defer if (errmsg) |e| { std.testing.allocator.free(e); errmsg = null; };
// Default output value var it = TestIterator.init(&.{ "hello.zig", "world.zig", });
var options = try Options.parseIter(std.testing.allocator, &it, &errmsg); defer options.deinit(std.testing.allocator);
try std.testing.expect(errmsg == null); try std.testing.expectEqualStrings("tags", options.output); try std.testing.expectEqual(false, options.relative); try std.testing.expectEqual(false, options.append); try std.testing.expectEqual(@as(usize, 2), options.arguments.len); try std.testing.expectEqualStrings("hello.zig", options.arguments[0]); try std.testing.expectEqualStrings("world.zig", options.arguments[1]); }
{ defer if (errmsg) |e| { std.testing.allocator.free(e); errmsg = null; };
// Supplied output value var it = TestIterator.init(&.{ "-o", "foo", "-r", "hello.zig", });
var options = try Options.parseIter(std.testing.allocator, &it, &errmsg); defer options.deinit(std.testing.allocator);
try std.testing.expect(errmsg == null); try std.testing.expectEqualStrings("foo", options.output); try std.testing.expectEqual(true, options.relative); try std.testing.expectEqual(false, options.append); }
{ defer if (errmsg) |e| { std.testing.allocator.free(e); errmsg = null; };
// Can output to stdout var it = TestIterator.init(&.{ "-o", "-", "hello.zig", });
var options = try Options.parseIter(std.testing.allocator, &it, &errmsg); defer options.deinit(std.testing.allocator);
try std.testing.expect(errmsg == null); try std.testing.expectEqualStrings("-", options.output); }
{ defer if (errmsg) |e| { std.testing.allocator.free(e); errmsg = null; };
// error: Missing arguments var it = TestIterator.init(&.{ "-o", "foo", });
const options = Options.parseIter(std.testing.allocator, &it, &errmsg); try std.testing.expect(errmsg != null); try std.testing.expectError(error.MissingArgument, options); try std.testing.expectEqualStrings("No files specified.", errmsg.?); }
{ defer if (errmsg) |e| { std.testing.allocator.free(e); errmsg = null; };
// error: Missing option value var it = TestIterator.init(&.{ "hello.zig", "-o", });
const options = Options.parseIter(std.testing.allocator, &it, &errmsg); try std.testing.expectError(error.MissingArgument, options); try std.testing.expect(errmsg != null); try std.testing.expectEqualStrings("Option 'o' missing required argument.", errmsg.?); }
{ defer if (errmsg) |e| { std.testing.allocator.free(e); errmsg = null; };
// error: Missing option value var it = TestIterator.init(&.{ "-o", "-a", "hello.zig", });
const options = Options.parseIter(std.testing.allocator, &it, &errmsg); try std.testing.expectError(error.MissingArgument, options); try std.testing.expect(errmsg != null); try std.testing.expectEqualStrings("Option 'o' missing required argument.", errmsg.?); }
{ defer if (errmsg) |e| { std.testing.allocator.free(e); errmsg = null; };
// Multiple options var it = TestIterator.init(&.{ "-rao", "tags", "hello.zig", });
var options = try Options.parseIter(std.testing.allocator, &it, &errmsg); defer options.deinit(std.testing.allocator);
try std.testing.expect(errmsg == null); try std.testing.expectEqual(true, options.relative); try std.testing.expectEqual(true, options.append); }
{ defer if (errmsg) |e| { std.testing.allocator.free(e); errmsg = null; };
// error: Option after option that expects argument var it = TestIterator.init(&.{ "-roa", "tags", "hello.zig", });
const options = Options.parseIter(std.testing.allocator, &it, &errmsg); try std.testing.expectError(error.MissingArgument, options); try std.testing.expect(errmsg != null); try std.testing.expectEqualStrings("Option 'o' missing required argument.", errmsg.?); }}