From 98028cf25fd8395f7a17840b900cb23a24a41b12 Mon Sep 17 00:00:00 2001 From: Martin Nonnenmacher Date: Fri, 26 Jan 2018 17:28:39 +0100 Subject: [PATCH] Order parameters with the same order by name in usage() Parameters without order are sorted by name, do the same for parameters with the same order for consistency. --- .../java/com/beust/jcommander/JCommander.java | 3 +- .../beust/jcommander/ParameterOrderTest.java | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/beust/jcommander/JCommander.java b/src/main/java/com/beust/jcommander/JCommander.java index 5e559426..3f40806c 100644 --- a/src/main/java/com/beust/jcommander/JCommander.java +++ b/src/main/java/com/beust/jcommander/JCommander.java @@ -190,7 +190,8 @@ public int compare(ParameterDescription p0, ParameterDescription p1) { return a0.category().compareTo(a1.category()); } if (a0 != null && a0.order() != -1 && a1 != null && a1.order() != -1) { - return Integer.compare(a0.order(), a1.order()); + int comp = Integer.compare(a0.order(), a1.order()); + return comp != 0 ? comp : p0.getLongestName().compareTo(p1.getLongestName()); } else if (a0 != null && a0.order() != -1) { return -1; } else if (a1 != null && a1.order() != -1) { diff --git a/src/test/java/com/beust/jcommander/ParameterOrderTest.java b/src/test/java/com/beust/jcommander/ParameterOrderTest.java index d823b07e..c3397ac8 100644 --- a/src/test/java/com/beust/jcommander/ParameterOrderTest.java +++ b/src/test/java/com/beust/jcommander/ParameterOrderTest.java @@ -104,4 +104,32 @@ public void testOrder(Object cmd, String ... expected) { } Assert.assertEquals(order, Arrays.asList(expected)); } + + private static class WithoutOrder { + @Parameter(names = "--arg_b") + public boolean isB; + @Parameter(names = "--arg_c") + public boolean isC; + @Parameter(names = "--arg_a") + public boolean isA; + } + + @Test + public void parametersWithoutOrder() { + testOrder(new WithoutOrder(), "--arg_a", "--arg_b", "--arg_c"); + } + + private static class WithSameOrder { + @Parameter(order=0, names = "--arg_b") + public boolean isB; + @Parameter(order=0, names = "--arg_c") + public boolean isC; + @Parameter(order=0, names = "--arg_a") + public boolean isA; + } + + @Test + public void parametersWithSameOrder() { + testOrder(new WithSameOrder(), "--arg_a", "--arg_b", "--arg_c"); + } }