various tools I have been using throughout the years
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384const std = @import("std");
pub const OptionsTag = enum { settings, help };
pub const Options = union(OptionsTag) { settings: Settings, help: void,};
pub const Settings = struct { task_length: u32 = 26, task_break: u32 = 4, notifications: bool = true, file: ?[]const u8 = null,};
pub fn parseArgs(args: []const []const u8) !Options { var settings = Settings{};
var i: u32 = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (i + 1 < args.len and std.mem.eql(u8, arg, "-t")) { i += 1; settings.task_length = try std.fmt.parseInt(u32, args[i], 10); } else if (i + 1 < args.len and std.mem.eql(u8, arg, "-b")) { i += 1; settings.task_break = try std.fmt.parseInt(u32, args[i], 10); } else if (std.mem.eql(u8, arg, "-s")) { settings.notifications = false; } else if (i + 1 < args.len and std.mem.eql(u8, arg, "--file")) { i += 1; settings.file = args[i]; } else if (std.mem.eql(u8, arg, "-h")) { return .{ .help = void{} }; } else { return error.InvalidArgument; } }
return .{ .settings = settings };}
pub fn usage(allocator: std.mem.Allocator, program: []const u8) ![]u8 { const result = try std.fmt.allocPrint(allocator, \\Usage: {s} \\[-t <task_length>] Task length in minutes (default: 26 mins) \\[-b <task_break>] Task break length in minutes (default: 4 mins) \\[-s] Disable notifications \\[--file <path>] Write status to a file \\[-h] Show this help message \\ , .{program});
return result;}
test "parseArgs options" { const args = [_][]const u8{ "-t", "30", "-b", "20", "-s", };
const options = try parseArgs(&args); try std.testing.expectEqual(options.settings.task_length, 30); try std.testing.expectEqual(options.settings.task_break, 20); try std.testing.expectEqual(options.settings.notifications, false);}
test "parseArgs help" { const args = [_][]const u8{"-h"};
const options = try parseArgs(&args); try std.testing.expectEqual(options, OptionsTag.help);}
test "parseArgs nok" { const args = [_][]const u8{ "some", "junk", "arguments" };
const result = parseArgs(&args); try std.testing.expectError(error.InvalidArgument, result);}