From 1c8cc16b660d8933c48b1f8c5321542985c92c04 Mon Sep 17 00:00:00 2001 From: Jimmi Holst Christensen Date: Tue, 22 Jul 2025 10:49:49 +0200 Subject: feat: Add `clap.helpToFile` The code for printing help became quite verbose after writegate. Writing help to a file like stdout and stderr is very common, so this wrapper provides a default, buffered way to report to a file. --- README.md | 8 ++------ clap.zig | 13 +++++++++++++ example/help.zig | 8 ++------ 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 8db67c9..6a1435f 100644 --- a/README.md +++ b/README.md @@ -365,12 +365,8 @@ pub fn main() !void { // where `Id` has a `description` and `value` method (`Param(Help)` is one such parameter). // The last argument contains options as to how `help` should print those parameters. Using // `.{}` means the default options. - if (res.args.help != 0) { - var buf: [1024]u8 = undefined; - var stderr = std.fs.File.stderr().writer(&buf); - try clap.help(&stderr.interface, clap.Help, ¶ms, .{}); - return stderr.interface.flush(); - } + if (res.args.help != 0) + return clap.helpToFile(.stderr(), clap.Help, ¶ms, .{}); } const clap = @import("clap"); diff --git a/clap.zig b/clap.zig index c4dd801..4a001ce 100644 --- a/clap.zig +++ b/clap.zig @@ -1367,6 +1367,19 @@ pub const HelpOptions = struct { spacing_between_parameters: usize = 1, }; +/// Wrapper around `help`, which writes to a file in a buffered manner +pub fn helpToFile( + file: std.fs.File, + comptime Id: type, + params: []const Param(Id), + opt: HelpOptions, +) !void { + var buf: [1024]u8 = undefined; + var writer = file.writer(&buf); + try help(&writer.interface, Id, params, opt); + return writer.end(); +} + /// Print a slice of `Param` formatted as a help string to `writer`. This function expects /// `Id` to have the methods `description` and `value` which are used by `help` to describe /// each parameter. Using `Help` as `Id` is good choice. diff --git a/example/help.zig b/example/help.zig index 676a56a..5c88d83 100644 --- a/example/help.zig +++ b/example/help.zig @@ -17,12 +17,8 @@ pub fn main() !void { // where `Id` has a `description` and `value` method (`Param(Help)` is one such parameter). // The last argument contains options as to how `help` should print those parameters. Using // `.{}` means the default options. - if (res.args.help != 0) { - var buf: [1024]u8 = undefined; - var stderr = std.fs.File.stderr().writer(&buf); - try clap.help(&stderr.interface, clap.Help, ¶ms, .{}); - return stderr.interface.flush(); - } + if (res.args.help != 0) + return clap.helpToFile(.stderr(), clap.Help, ¶ms, .{}); } const clap = @import("clap"); -- cgit v1.2.3