Skip to content

Commit

Permalink
Order parameters with the same order by name in usage()
Browse files Browse the repository at this point in the history
Parameters without order are sorted by name, do the same for parameters
with the same order for consistency.
  • Loading branch information
mnonnenmacher authored and mkarg committed Dec 21, 2023
1 parent 46b12bd commit 98028cf
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/main/java/com/beust/jcommander/JCommander.java
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
28 changes: 28 additions & 0 deletions src/test/java/com/beust/jcommander/ParameterOrderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}

0 comments on commit 98028cf

Please sign in to comment.