From b9f2b9c789186d91f3e49350ba279e3c29fc27be Mon Sep 17 00:00:00 2001 From: Jason van Zyl Date: Mon, 31 Aug 2015 12:54:06 -0400 Subject: [PATCH] Apply injection options to an existing command Where a command factory is used to produce singleton commands, this change will allow the command to be reconfigured before execution. --- src/main/java/io/airlift/airline/Cli.java | 30 +++++++++++++++++++ .../java/io/airlift/airline/ParserUtil.java | 11 +++++++ 2 files changed, 41 insertions(+) diff --git a/src/main/java/io/airlift/airline/Cli.java b/src/main/java/io/airlift/airline/Cli.java index 2c4af5385..76369960e 100644 --- a/src/main/java/io/airlift/airline/Cli.java +++ b/src/main/java/io/airlift/airline/Cli.java @@ -36,6 +36,7 @@ import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; import static io.airlift.airline.ParserUtil.createInstance; +import static io.airlift.airline.ParserUtil.injectOptions; public class Cli { @@ -138,6 +139,35 @@ public C parse(CommandFactory commandFactory, Iterable args) commandFactory); } + public C parse(C commandInstance, String... args) + { + Preconditions.checkNotNull(args, "args is null"); + + Parser parser = new Parser(); + ParseState state = parser.parse(metadata, args); + + if (state.getCommand() == null) { + if (state.getGroup() != null) { + state = state.withCommand(state.getGroup().getDefaultCommand()); + } + else { + state = state.withCommand(metadata.getDefaultCommand()); + } + } + + validate(state); + + CommandMetadata command = state.getCommand(); + + return injectOptions(commandInstance, + command.getAllOptions(), + state.getParsedOptions(), + command.getArguments(), + state.getParsedArguments(), + command.getMetadataInjections(), + ImmutableMap., Object>of(GlobalMetadata.class, metadata)); + } + private void validate(ParseState state) { CommandMetadata command = state.getCommand(); diff --git a/src/main/java/io/airlift/airline/ParserUtil.java b/src/main/java/io/airlift/airline/ParserUtil.java index 46ede92a3..ccc26cd0b 100644 --- a/src/main/java/io/airlift/airline/ParserUtil.java +++ b/src/main/java/io/airlift/airline/ParserUtil.java @@ -37,6 +37,17 @@ public static T createInstance(Class type, // create the command instance T commandInstance = commandFactory.createInstance(type); + return injectOptions(commandInstance, options, parsedOptions, arguments, parsedArguments, metadataInjection, bindings); + } + + public static T injectOptions(T commandInstance, + Iterable options, + ListMultimap parsedOptions, + ArgumentsMetadata arguments, + Iterable parsedArguments, + Iterable metadataInjection, + Map, Object> bindings) + { // inject options for (OptionMetadata option : options) { List values = parsedOptions.get(option);