aboutsummaryrefslogtreecommitdiff
path: root/org.jacoco.cli/src/org/jacoco/cli/internal/Command.java
blob: 5e83b8b7a64e1b8f136719d6481c201cff994096 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*******************************************************************************
 * Copyright (c) 2009, 2017 Mountainminds GmbH & Co. KG and Contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Marc R. Hoffmann - initial API and implementation
 *
 *******************************************************************************/
package org.jacoco.cli.internal;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.kohsuke.args4j.Option;

/**
 * Common interface for all commands.
 */
public abstract class Command {

	/**
	 * Common command line prefix.
	 */
	public static final String JAVACMD = "java -jar jacococli.jar ";

	/**
	 * Flag whether help should be printed for this command.
	 */
	@Option(name = "-help", usage = "show help", help = true)
	public boolean help = false;

	/**
	 * @return Short description of the command.
	 */
	public abstract String description();

	/**
	 * @return name of the command
	 */
	public String name() {
		return getClass().getSimpleName().toLowerCase();
	}

	/**
	 * @param parser
	 *            parser for this command
	 * @return usage string displayed for help
	 */
	public String usage(final CommandParser parser) {
		final StringWriter writer = new StringWriter();
		parser.printSingleLineUsage(writer, null);
		return JAVACMD + name() + writer;
	}

	/**
	 * Executes the given command.
	 * 
	 * @param out
	 *            std out
	 * @param err
	 *            std err
	 * @return exit code, should be 0 for normal operation
	 * @throws Exception
	 *             any exception that my occur during execution
	 */
	public abstract int execute(PrintWriter out, PrintWriter err)
			throws Exception;

	/**
	 * Prints textual help for this command.
	 * 
	 * @param writer
	 *            output destination
	 */
	protected void printHelp(final PrintWriter writer) {
		final CommandParser parser = new CommandParser(this);
		writer.println("Usage: " + parser.getCommand().usage(parser));
		writer.println(description());
		parser.printUsage(writer, null);
	}

}