From 49c47b24c1f1f82738f752abd0c404c33a95750b Mon Sep 17 00:00:00 2001 From: Ryan Ernst Date: Fri, 22 Apr 2016 14:09:35 -0700 Subject: [PATCH] Cli: Improve output for usage errors When a cli throws a USAGE error, it is implied that the user did something wrong, and probably needs help in understanding the cli arguments. This change adds help output before the usage error is printed. --- .../java/org/elasticsearch/cli/Command.java | 3 +++ .../org/elasticsearch/cli/CommandTests.java | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/core/src/main/java/org/elasticsearch/cli/Command.java b/core/src/main/java/org/elasticsearch/cli/Command.java index 9e6afdd6638..1fc7c9fe74f 100644 --- a/core/src/main/java/org/elasticsearch/cli/Command.java +++ b/core/src/main/java/org/elasticsearch/cli/Command.java @@ -56,6 +56,9 @@ public abstract class Command { terminal.println(Terminal.Verbosity.SILENT, "ERROR: " + e.getMessage()); return ExitCodes.USAGE; } catch (UserError e) { + if (e.exitCode == ExitCodes.USAGE) { + printHelp(terminal); + } terminal.println(Terminal.Verbosity.SILENT, "ERROR: " + e.getMessage()); return e.exitCode; } diff --git a/core/src/test/java/org/elasticsearch/cli/CommandTests.java b/core/src/test/java/org/elasticsearch/cli/CommandTests.java index 153bd4600b9..1f50ad4c13b 100644 --- a/core/src/test/java/org/elasticsearch/cli/CommandTests.java +++ b/core/src/test/java/org/elasticsearch/cli/CommandTests.java @@ -34,6 +34,16 @@ public class CommandTests extends ESTestCase { } } + static class UsageErrorCommand extends Command { + UsageErrorCommand() { + super("Throws a usage error"); + } + @Override + protected void execute(Terminal terminal, OptionSet options) throws Exception { + throw new UserError(ExitCodes.USAGE, "something was no good"); + } + } + static class NoopCommand extends Command { boolean executed = false; NoopCommand() { @@ -120,4 +130,15 @@ public class CommandTests extends ESTestCase { assertEquals(output, ExitCodes.DATA_ERROR, status); assertTrue(output, output.contains("ERROR: Bad input")); } + + public void testUsageError() throws Exception { + MockTerminal terminal = new MockTerminal(); + UsageErrorCommand command = new UsageErrorCommand(); + String[] args = {}; + int status = command.main(args, terminal); + String output = terminal.getOutput(); + assertEquals(output, ExitCodes.USAGE, status); + assertTrue(output, output.contains("Throws a usage error")); + assertTrue(output, output.contains("ERROR: something was no good")); + } }