1 /* 2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"). 5 * You may not use this file except in compliance with the License. 6 * A copy of the License is located at 7 * 8 * http://aws.amazon.com/apache2.0 9 * 10 * or in the "license" file accompanying this file. This file is distributed 11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 * express or implied. See the License for the specific language governing 13 * permissions and limitations under the License. 14 */ 15 16 package software.amazon.awssdk.release; 17 18 import java.util.stream.Stream; 19 import org.apache.commons.cli.CommandLine; 20 import org.apache.commons.cli.CommandLineParser; 21 import org.apache.commons.cli.DefaultParser; 22 import org.apache.commons.cli.HelpFormatter; 23 import org.apache.commons.cli.Option; 24 import org.apache.commons.cli.Options; 25 import org.apache.commons.cli.ParseException; 26 import software.amazon.awssdk.utils.Logger; 27 28 public abstract class Cli { 29 private final Logger log = Logger.loggerFor(Cli.class); 30 private final Option[] optionsToAdd; 31 Cli(Option... optionsToAdd)32 public Cli(Option... optionsToAdd) { 33 this.optionsToAdd = optionsToAdd; 34 } 35 run(String[] args)36 public final void run(String[] args) { 37 Options options = new Options(); 38 Stream.of(optionsToAdd).forEach(options::addOption); 39 40 CommandLineParser parser = new DefaultParser(); 41 HelpFormatter help = new HelpFormatter(); 42 43 try { 44 CommandLine commandLine = parser.parse(options, args); 45 run(commandLine); 46 } catch (ParseException e) { 47 log.error(() -> "Invalid input: " + e.getMessage()); 48 help.printHelp(getClass().getSimpleName(), options); 49 throw new Error(); 50 } catch (Exception e) { 51 log.error(() -> "Script execution failed.", e); 52 throw new Error(); 53 } 54 } 55 requiredOption(String longCommand, String description)56 protected static Option requiredOption(String longCommand, String description) { 57 Option option = optionalOption(longCommand, description); 58 option.setRequired(true); 59 return option; 60 } 61 optionalOption(String longCommand, String description)62 protected static Option optionalOption(String longCommand, String description) { 63 return new Option(null, longCommand, true, description); 64 } 65 optionalMultiValueOption(String longCommand, String description)66 protected static Option optionalMultiValueOption(String longCommand, String description) { 67 return Option.builder() 68 .longOpt(longCommand) 69 .desc(description) 70 .hasArgs() 71 .build(); 72 } 73 run(CommandLine commandLine)74 protected abstract void run(CommandLine commandLine) throws Exception; 75 } 76