View Javadoc
1   /*
2    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.pgm.opt;
12  
13  import org.eclipse.jgit.pgm.CommandCatalog;
14  import org.eclipse.jgit.pgm.CommandRef;
15  import org.eclipse.jgit.pgm.TextBuiltin;
16  import org.eclipse.jgit.pgm.internal.CLIText;
17  import org.kohsuke.args4j.CmdLineException;
18  import org.kohsuke.args4j.CmdLineParser;
19  import org.kohsuke.args4j.OptionDef;
20  import org.kohsuke.args4j.spi.OptionHandler;
21  import org.kohsuke.args4j.spi.Parameters;
22  import org.kohsuke.args4j.spi.Setter;
23  
24  /**
25   * Custom Argument handler for jgit command selection.
26   * <p>
27   * Translates a single argument string to a
28   * {@link org.eclipse.jgit.pgm.TextBuiltin} instance which we can execute at
29   * runtime with the remaining arguments of the parser.
30   */
31  public class SubcommandHandler extends OptionHandler<TextBuiltin> {
32  	private final org.eclipse.jgit.pgm.opt.CmdLineParser clp;
33  
34  	/**
35  	 * Create a new handler for the command name.
36  	 * <p>
37  	 * This constructor is used only by args4j.
38  	 *
39  	 * @param parser
40  	 *            a {@link org.kohsuke.args4j.CmdLineParser} object.
41  	 * @param option
42  	 *            a {@link org.kohsuke.args4j.OptionDef} object.
43  	 * @param setter
44  	 *            a {@link org.kohsuke.args4j.spi.Setter} object.
45  	 */
46  	public SubcommandHandler(final CmdLineParser parser,
47  			final OptionDef option, final Setter<? super TextBuiltin> setter) {
48  		super(parser, option, setter);
49  		clp = (org.eclipse.jgit.pgm.opt.CmdLineParser) parser;
50  	}
51  
52  	/** {@inheritDoc} */
53  	@Override
54  	public int parseArguments(Parameters params) throws CmdLineException {
55  		final String name = params.getParameter(0);
56  		final CommandRef cr = CommandCatalog.get(name);
57  		if (cr == null)
58  			throw new CmdLineException(clp,
59  					CLIText.format(CLIText.get().notAJgitCommand), name);
60  
61  		// Force option parsing to stop. Everything after us should
62  		// be arguments known only to this command and must not be
63  		// recognized by the current parser.
64  		//
65  		owner.stopOptionParsing();
66  		setter.addValue(cr.create());
67  		return 1;
68  	}
69  
70  	/** {@inheritDoc} */
71  	@Override
72  	public String getDefaultMetaVariable() {
73  		return CLIText.get().metaVar_command;
74  	}
75  }