1/*******************************************************************************
2 * Copyright (c) 2009, 2017 Mountainminds GmbH & Co. KG and Contributors
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 *    Marc R. Hoffmann - initial API and implementation
10 *
11 *******************************************************************************/
12package org.jacoco.cli.internal;
13
14import java.io.IOException;
15import java.io.PrintWriter;
16import java.io.Writer;
17
18import org.kohsuke.args4j.Argument;
19import org.kohsuke.args4j.CmdLineException;
20
21/**
22 * Entry point for all command line operations.
23 */
24public class Main extends Command {
25
26	private static final PrintWriter NUL = new PrintWriter(new Writer() {
27
28		@Override
29		public void write(final char[] arg0, final int arg1, final int arg2)
30				throws IOException {
31		}
32
33		@Override
34		public void flush() throws IOException {
35		}
36
37		@Override
38		public void close() throws IOException {
39		}
40	});
41
42	private final String[] args;
43
44	Main(final String... args) {
45		this.args = args;
46	}
47
48	@Argument(handler = CommandHandler.class, required = true)
49	Command command;
50
51	@Override
52	public String description() {
53		return "Command line interface for JaCoCo.";
54	}
55
56	@Override
57	public String usage(final CommandParser parser) {
58		return JAVACMD + "-help | <command>";
59	}
60
61	@Override
62	public int execute(PrintWriter out, final PrintWriter err)
63			throws Exception {
64
65		final CommandParser mainParser = new CommandParser(this);
66		try {
67			mainParser.parseArgument(args);
68		} catch (final CmdLineException e) {
69			err.println(e.getMessage());
70			err.println();
71			((CommandParser) e.getParser()).getCommand().printHelp(err);
72			return -1;
73		}
74
75		if (help) {
76			printHelp(out);
77			return 0;
78		}
79
80		if (command.help) {
81			command.printHelp(out);
82			return 0;
83		}
84
85		if (command.quiet) {
86			out = NUL;
87		}
88
89		return command.execute(out, err);
90	}
91
92	/**
93	 * Main entry point for program invocations.
94	 *
95	 * @param args
96	 *            program arguments
97	 * @throws Exception
98	 *             All internal exceptions are directly passed on to get printed
99	 *             on the console
100	 */
101	public static void main(final String... args) throws Exception {
102		new Main(args).execute(new PrintWriter(System.out, true),
103				new PrintWriter(System.err, true));
104	}
105
106}
107