From 7a24cd528f56a6ee3b8c16527eb4e68eca5eb901 Mon Sep 17 00:00:00 2001 From: Zefir Kirilov Date: Wed, 26 Nov 2025 11:53:46 +0200 Subject: [PATCH] Refine parser error messages for flags given `=` values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR improves the clarity of argument parser messages when a boolean flag is incorrectly provided with a value using `=`. Previously, cases like `-f=val` or `--flag=value` would produce misleading messages such as ‘unknown option '-f'’ even if the flag exists. Now, the parser reports more precise messages: - `unexpected '=' for option '-f'` - `unexpected '=' for option '--flag'` - `unexpected '=' in combined short options '-ff'` --- src/cmd/command.d | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/cmd/command.d b/src/cmd/command.d index ffaca0e..1212df0 100644 --- a/src/cmd/command.d +++ b/src/cmd/command.d @@ -330,9 +330,12 @@ public class Command { exit(program.printVersion()); if (program.helpOption() !is null && program.helpOption().matches(arg)) exit(printHelp()); + + const auto equalsIndex = arg.indexOf('='); + const string optName = equalsIndex >= 0 ? arg[0..equalsIndex] : arg; - if (arg.length > 2 && arg[0] == '-' && arg[1] != '-' && arg[2] != '=') { - foreach (c; arg[1 .. $]) { + if (optName.length > 2 && optName[0] == '-' && optName[1] != '-') { + foreach (c; optName[1..$]) { const shortArg = "-" ~ c; const(Flag) f = findFlag(shortArg); if (f !is null) { @@ -344,17 +347,19 @@ public class Command { error("missing value for option '" ~ shortArg ~ "'", 2); program.error("unknown option '" ~ shortArg ~ "'", 2); } + if (equalsIndex >= 0) + error("unexpected '=' in combined short options '" ~ optName ~ "'", 2); continue; } - const(Flag) flag = findFlag(arg); + const(Flag) flag = findFlag(optName); if (flag !is null) { + if (equalsIndex >= 0) + error("unexpected '=' for option '" ~ optName ~ "'", 2); parsedFlags[flag] = parsedFlags.get(flag, 0) + 1; continue; } - const auto equalsIndex = arg.indexOf('='); - const string optName = equalsIndex >= 0 ? arg[0..equalsIndex] : arg; const(Option) option = findOption(optName); if (option !is null) { string value;