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.util.AbstractList;
15
16import org.jacoco.cli.internal.commands.AllCommands;
17import org.kohsuke.args4j.CmdLineException;
18import org.kohsuke.args4j.CmdLineParser;
19import org.kohsuke.args4j.OptionDef;
20import org.kohsuke.args4j.spi.Messages;
21import org.kohsuke.args4j.spi.OptionHandler;
22import org.kohsuke.args4j.spi.Parameters;
23import org.kohsuke.args4j.spi.Setter;
24
25/**
26 * {@link OptionHandler} which uses {@link CommandParser} internally to provide
27 * help context also for sub-commands.
28 */
29public class CommandHandler extends OptionHandler<Command> {
30
31	/**
32	 * This constructor is required by the args4j framework.
33	 *
34	 * @param parser
35	 * @param option
36	 * @param setter
37	 */
38	public CommandHandler(final CmdLineParser parser, final OptionDef option,
39			final Setter<Object> setter) {
40		super(parser,
41				new OptionDef(AllCommands.names(), "<command>",
42						option.required(), option.help(), option.hidden(),
43						CommandHandler.class, option.isMultiValued()) {
44				}, setter);
45	}
46
47	@Override
48	public int parseArguments(final Parameters params) throws CmdLineException {
49		final String subCmd = params.getParameter(0);
50
51		for (final Command c : AllCommands.get()) {
52			if (c.name().equals(subCmd)) {
53				parseSubArguments(c, params);
54				setter.addValue(c);
55				return params.size(); // consume all the remaining tokens
56			}
57		}
58
59		throw new CmdLineException(owner,
60				Messages.ILLEGAL_OPERAND.format(option.toString(), subCmd));
61	}
62
63	private void parseSubArguments(final Command c, final Parameters params)
64			throws CmdLineException {
65		final CmdLineParser p = new CommandParser(c);
66		p.parseArgument(new AbstractList<String>() {
67			@Override
68			public String get(final int index) {
69				try {
70					return params.getParameter(index + 1);
71				} catch (final CmdLineException e) {
72					// invalid index was accessed.
73					throw new IndexOutOfBoundsException();
74				}
75			}
76
77			@Override
78			public int size() {
79				return params.size() - 1;
80			}
81		});
82	}
83
84	@Override
85	public String getDefaultMetaVariable() {
86		return "<command>";
87	}
88
89}
90