Let commands specify their own default output if none is provided by the user

This commit is contained in:
AsamK 2021-08-20 18:43:54 +02:00
parent af292d8f0e
commit ef2a013db3

View file

@ -67,8 +67,7 @@ public class App {
parser.addArgument("-o", "--output") parser.addArgument("-o", "--output")
.help("Choose to output in plain text or JSON") .help("Choose to output in plain text or JSON")
.type(Arguments.enumStringType(OutputType.class)) .type(Arguments.enumStringType(OutputType.class));
.setDefault(OutputType.PLAIN_TEXT);
parser.addArgument("--service-environment") parser.addArgument("--service-environment")
.help("Choose the server environment to use.") .help("Choose the server environment to use.")
@ -90,19 +89,22 @@ public class App {
} }
public void init() throws CommandException { public void init() throws CommandException {
var outputType = ns.<OutputType>get("output");
var outputWriter = outputType == OutputType.JSON
? new JsonWriterImpl(System.out)
: new PlainTextWriterImpl(System.out);
var commandKey = ns.getString("command"); var commandKey = ns.getString("command");
var command = Commands.getCommand(commandKey); var command = Commands.getCommand(commandKey);
if (command == null) { if (command == null) {
throw new UserErrorException("Command not implemented!"); throw new UserErrorException("Command not implemented!");
} }
if (!command.getSupportedOutputTypes().contains(outputType)) { var outputTypeInput = ns.<OutputType>get("output");
throw new UserErrorException("Command doesn't support output type " + outputType.toString()); var outputType = outputTypeInput == null
? command.getSupportedOutputTypes().stream().findFirst().orElse(null)
: outputTypeInput;
var outputWriter = outputType == null
? null
: outputType == OutputType.JSON ? new JsonWriterImpl(System.out) : new PlainTextWriterImpl(System.out);
if (outputWriter != null && !command.getSupportedOutputTypes().contains(outputType)) {
throw new UserErrorException("Command doesn't support output type " + outputType);
} }
var username = ns.getString("username"); var username = ns.getString("username");