1 /******************************************************************************* 2 * Copyright (c) 2009, 2021 Mountainminds GmbH & Co. KG and Contributors 3 * This program and the accompanying materials are made available under 4 * the terms of the Eclipse Public License 2.0 which is available at 5 * http://www.eclipse.org/legal/epl-2.0 6 * 7 * SPDX-License-Identifier: EPL-2.0 8 * 9 * Contributors: 10 * Marc R. Hoffmann - initial API and implementation 11 * 12 *******************************************************************************/ 13 package org.jacoco.cli.internal; 14 15 import java.io.PrintWriter; 16 import java.io.StringWriter; 17 18 import org.kohsuke.args4j.Option; 19 20 /** 21 * Common interface for all commands. 22 */ 23 public abstract class Command { 24 25 /** 26 * Common command line prefix. 27 */ 28 public static final String JAVACMD = "java -jar jacococli.jar "; 29 30 /** 31 * Flag whether help should be printed for this command. 32 */ 33 @Option(name = "--help", usage = "show help", help = true) 34 public boolean help = false; 35 36 /** 37 * Flag whether output to stdout should be suppressed. 38 */ 39 @Option(name = "--quiet", usage = "suppress all output on stdout") 40 public boolean quiet = false; 41 42 /** 43 * @return Short description of the command. 44 */ description()45 public abstract String description(); 46 47 /** 48 * @return name of the command 49 */ name()50 public String name() { 51 return getClass().getSimpleName().toLowerCase(); 52 } 53 54 /** 55 * @param parser 56 * parser for this command 57 * @return usage string displayed for help 58 */ usage(final CommandParser parser)59 public String usage(final CommandParser parser) { 60 final StringWriter writer = new StringWriter(); 61 parser.printSingleLineUsage(writer, null); 62 return JAVACMD + name() + writer; 63 } 64 65 /** 66 * Executes the given command. 67 * 68 * @param out 69 * std out 70 * @param err 71 * std err 72 * @return exit code, should be 0 for normal operation 73 * @throws Exception 74 * any exception that my occur during execution 75 */ execute(PrintWriter out, PrintWriter err)76 public abstract int execute(PrintWriter out, PrintWriter err) 77 throws Exception; 78 79 /** 80 * Prints textual help for this command. 81 * 82 * @param writer 83 * output destination 84 */ printHelp(final PrintWriter writer)85 protected void printHelp(final PrintWriter writer) { 86 final CommandParser parser = new CommandParser(this); 87 writer.println(description()); 88 writer.println(); 89 writer.println("Usage: " + parser.getCommand().usage(parser)); 90 parser.printUsage(writer, null); 91 } 92 93 } 94