Created
July 21, 2017 07:19
-
-
Save ashigeru/44c9bef55cc3f4f9dfd95efe404e6918 to your computer and use it in GitHub Desktop.
sub-sub-commands on JCommander
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SubSubCommands { | |
public static void main(String[] args) { | |
exec("a"); | |
exec("b"); | |
exec("a", "c"); | |
/* | |
args: [a] | |
program: "root a" | |
command: [A] | |
args: [b] | |
program: "root b" | |
command: [B] | |
args: [a, c] | |
program: "root a c" | |
command: [C] | |
*/ | |
} | |
static void exec(String... args) { | |
JCommander root = JCommander.newBuilder() | |
.programName("root") | |
.build(); | |
addCommand(root, "A", "a"); | |
addCommand(root, "B", "b"); | |
addCommand(root, "C", "a", "c"); | |
root.parse(args); | |
JCommander cmd = findCommander(root); | |
System.out.printf("args: %s%n", Arrays.toString(args)); | |
System.out.printf(" program: \"%s\"%n", cmd.getProgramName()); | |
System.out.printf(" command: %s%n", cmd.getObjects()); | |
} | |
private static void addCommand(JCommander root, Object object, String... commands) { | |
JCommander current = root; | |
for (int i = 0, n = commands.length - 1; i < n; i++) { | |
JCommander next = current.getCommands().get(commands[i]); | |
assert next != null; | |
current = next; | |
} | |
String last = commands[commands.length - 1]; | |
current.addCommand(last, object); | |
JCommander cmd = current.getCommands().get(last); | |
cmd.setProgramName(Stream.concat( | |
Stream.of(root.getProgramName()), | |
Arrays.stream(commands)).collect(Collectors.joining(" "))); | |
} | |
private static JCommander findCommander(JCommander root) { | |
JCommander current = root; | |
while (true) { | |
String cmd = current.getParsedAlias(); | |
if (cmd == null) { | |
return current; | |
} else { | |
current = current.getCommands().get(cmd); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment