From 224fa3657c29a24b94f55867046cbb94a3d04523 Mon Sep 17 00:00:00 2001 From: Alexei Samokvalov Date: Sat, 25 Jan 2025 10:53:07 +0100 Subject: [PATCH 1/2] Print help on errors --- src/app_runner.zig | 8 ++++++-- src/command.zig | 3 +++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/app_runner.zig b/src/app_runner.zig index 9a0c3a4..34c9549 100644 --- a/src/app_runner.zig +++ b/src/app_runner.zig @@ -8,6 +8,7 @@ const parser = @import("parser.zig"); const Parser = parser.Parser; const Printer = @import("Printer.zig"); const command = @import("command.zig"); +const help = @import("./help.zig"); pub const AppRunner = struct { // This arena and its allocator is intended to be used only for the value references @@ -65,7 +66,11 @@ pub const AppRunner = struct { return action; } else |err| { processError(err, cr.error_data orelse unreachable, app); - return ArgumentError; + if (app.help_config.print_help_on_error) { + _ = std.io.getStdOut().write("\n") catch unreachable; + try help.print_command_help(app, try cr.command_path.toOwnedSlice(), cr.global_options); + } + std.posix.exit(1); } } @@ -119,5 +124,4 @@ fn printError(app: *const App, comptime fmt: []const u8, args: anytype) void { p.format(": ", .{}); p.format(fmt, args); p.write(&.{'\n'}); - std.posix.exit(1); } diff --git a/src/command.zig b/src/command.zig index fa1587e..312ea2d 100644 --- a/src/command.zig +++ b/src/command.zig @@ -35,6 +35,9 @@ pub const HelpConfig = struct { color_option: []const u8 = "32", /// Color for error messages in help. color_error: []const u8 = "31;1", + + /// Whether to print last command help on errors like missing arguments or options. + print_help_on_error: bool = true, }; /// Structure representing a command. From 6894186dfac7ef712b32289ed0d42b31427ecf2a Mon Sep 17 00:00:00 2001 From: Alexei Samokvalov Date: Sat, 25 Jan 2025 10:58:30 +0100 Subject: [PATCH 2/2] Remove unused error --- src/app_runner.zig | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/app_runner.zig b/src/app_runner.zig index 34c9549..a200d01 100644 --- a/src/app_runner.zig +++ b/src/app_runner.zig @@ -50,8 +50,7 @@ pub const AppRunner = struct { return self.allocSlice(command.Command, args); } - pub const ArgumentError = error.ArgumentError; - pub const Error = Allocator.Error || error{ArgumentError}; + pub const Error = Allocator.Error; /// `getAction` returns the action function that should be called by the main app. pub fn getAction(self: *Self, app: *const App) Error!command.ExecFn {