View Javadoc
1   /*
2    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.pgm.opt;
45  
46  import java.io.IOException;
47  import java.io.Writer;
48  import java.lang.reflect.Field;
49  import java.util.ArrayList;
50  import java.util.Iterator;
51  import java.util.List;
52  import java.util.ResourceBundle;
53  
54  import org.eclipse.jgit.lib.ObjectId;
55  import org.eclipse.jgit.lib.Repository;
56  import org.eclipse.jgit.pgm.Die;
57  import org.eclipse.jgit.pgm.TextBuiltin;
58  import org.eclipse.jgit.pgm.internal.CLIText;
59  import org.eclipse.jgit.revwalk.RevCommit;
60  import org.eclipse.jgit.revwalk.RevTree;
61  import org.eclipse.jgit.revwalk.RevWalk;
62  import org.eclipse.jgit.transport.RefSpec;
63  import org.eclipse.jgit.treewalk.AbstractTreeIterator;
64  import org.kohsuke.args4j.CmdLineException;
65  import org.kohsuke.args4j.IllegalAnnotationError;
66  import org.kohsuke.args4j.NamedOptionDef;
67  import org.kohsuke.args4j.OptionDef;
68  import org.kohsuke.args4j.OptionHandlerRegistry;
69  import org.kohsuke.args4j.spi.OptionHandler;
70  import org.kohsuke.args4j.spi.RestOfArgumentsHandler;
71  import org.kohsuke.args4j.spi.Setter;
72  
73  /**
74   * Extended command line parser which handles --foo=value arguments.
75   * <p>
76   * The args4j package does not natively handle --foo=value and instead prefers
77   * to see --foo value on the command line. Many users are used to the GNU style
78   * --foo=value long option, so we convert from the GNU style format to the
79   * args4j style format prior to invoking args4j for parsing.
80   */
81  public class CmdLineParser extends org.kohsuke.args4j.CmdLineParser {
82  	static {
83  		OptionHandlerRegistry registry = OptionHandlerRegistry.getRegistry();
84  		registry.registerHandler(AbstractTreeIterator.class,
85  				AbstractTreeIteratorHandler.class);
86  		registry.registerHandler(ObjectId.class, ObjectIdHandler.class);
87  		registry.registerHandler(RefSpec.class, RefSpecHandler.class);
88  		registry.registerHandler(RevCommit.class, RevCommitHandler.class);
89  		registry.registerHandler(RevTree.class, RevTreeHandler.class);
90  		registry.registerHandler(List.class, OptionWithValuesListHandler.class);
91  	}
92  
93  	private final Repository db;
94  
95  	private RevWalk walk;
96  
97  	private boolean seenHelp;
98  
99  	private TextBuiltin cmd;
100 
101 	/**
102 	 * Creates a new command line owner that parses arguments/options and set
103 	 * them into the given object.
104 	 *
105 	 * @param bean
106 	 *            instance of a class annotated by
107 	 *            {@link org.kohsuke.args4j.Option} and
108 	 *            {@link org.kohsuke.args4j.Argument}. this object will receive
109 	 *            values.
110 	 * @throws IllegalAnnotationError
111 	 *             if the option bean class is using args4j annotations
112 	 *             incorrectly.
113 	 */
114 	public CmdLineParser(Object bean) {
115 		this(bean, null);
116 	}
117 
118 	/**
119 	 * Creates a new command line owner that parses arguments/options and set
120 	 * them into the given object.
121 	 *
122 	 * @param bean
123 	 *            instance of a class annotated by
124 	 *            {@link org.kohsuke.args4j.Option} and
125 	 *            {@link org.kohsuke.args4j.Argument}. this object will receive
126 	 *            values.
127 	 * @param repo
128 	 *            repository this parser can translate options through.
129 	 * @throws IllegalAnnotationError
130 	 *             if the option bean class is using args4j annotations
131 	 *             incorrectly.
132 	 */
133 	public CmdLineParser(Object bean, Repository repo) {
134 		super(bean);
135 		if (bean instanceof TextBuiltin) {
136 			cmd = (TextBuiltin) bean;
137 		}
138 		if (repo == null && cmd != null) {
139 			repo = cmd.getRepository();
140 		}
141 		this.db = repo;
142 	}
143 
144 	/** {@inheritDoc} */
145 	@Override
146 	public void parseArgument(String... args) throws CmdLineException {
147 		final ArrayList<String> tmp = new ArrayList<>(args.length);
148 		for (int argi = 0; argi < args.length; argi++) {
149 			final String str = args[argi];
150 			if (str.equals("--")) { //$NON-NLS-1$
151 				while (argi < args.length)
152 					tmp.add(args[argi++]);
153 				break;
154 			}
155 
156 			if (str.startsWith("--")) { //$NON-NLS-1$
157 				final int eq = str.indexOf('=');
158 				if (eq > 0) {
159 					tmp.add(str.substring(0, eq));
160 					tmp.add(str.substring(eq + 1));
161 					continue;
162 				}
163 			}
164 
165 			tmp.add(str);
166 
167 			if (containsHelp(args)) {
168 				// suppress exceptions on required parameters if help is present
169 				seenHelp = true;
170 				// stop argument parsing here
171 				break;
172 			}
173 		}
174 		List<OptionHandler> backup = null;
175 		if (seenHelp) {
176 			backup = unsetRequiredOptions();
177 		}
178 
179 		try {
180 			super.parseArgument(tmp.toArray(new String[0]));
181 		} catch (Die e) {
182 			if (!seenHelp) {
183 				throw e;
184 			}
185 			printToErrorWriter(CLIText.fatalError(e.getMessage()));
186 		} finally {
187 			// reset "required" options to defaults for correct command printout
188 			if (backup != null && !backup.isEmpty()) {
189 				restoreRequiredOptions(backup);
190 			}
191 			seenHelp = false;
192 		}
193 	}
194 
195 	private void printToErrorWriter(String error) {
196 		if (cmd == null) {
197 			System.err.println(error);
198 		} else {
199 			try {
200 				cmd.getErrorWriter().println(error);
201 			} catch (IOException e1) {
202 				System.err.println(error);
203 			}
204 		}
205 	}
206 
207 	private List<OptionHandler> unsetRequiredOptions() {
208 		List<OptionHandler> options = getOptions();
209 		List<OptionHandler> backup = new ArrayList<>(options);
210 		for (Iterator<OptionHandler> iterator = options.iterator(); iterator
211 				.hasNext();) {
212 			OptionHandler handler = iterator.next();
213 			if (handler.option instanceof NamedOptionDef
214 					&& handler.option.required()) {
215 				iterator.remove();
216 			}
217 		}
218 		return backup;
219 	}
220 
221 	private void restoreRequiredOptions(List<OptionHandler> backup) {
222 		List<OptionHandler> options = getOptions();
223 		options.clear();
224 		options.addAll(backup);
225 	}
226 
227 	/**
228 	 * Check if array contains help option
229 	 *
230 	 * @param args
231 	 *            non null
232 	 * @return true if the given array contains help option
233 	 * @since 4.2
234 	 */
235 	protected boolean containsHelp(String... args) {
236 		return TextBuiltin.containsHelp(args);
237 	}
238 
239 	/**
240 	 * Get the repository this parser translates values through.
241 	 *
242 	 * @return the repository, if specified during construction.
243 	 */
244 	public Repository getRepository() {
245 		if (db == null)
246 			throw new IllegalStateException(CLIText.get().noGitRepositoryConfigured);
247 		return db;
248 	}
249 
250 	/**
251 	 * Get the revision walker used to support option parsing.
252 	 *
253 	 * @return the revision walk used by this option parser.
254 	 */
255 	public RevWalk getRevWalk() {
256 		if (walk == null)
257 			walk = new RevWalk(getRepository());
258 		return walk;
259 	}
260 
261 	/**
262 	 * Get the revision walker used to support option parsing.
263 	 * <p>
264 	 * This method does not initialize the RevWalk and may return null.
265 	 *
266 	 * @return the revision walk used by this option parser, or null.
267 	 */
268 	public RevWalk getRevWalkGently() {
269 		return walk;
270 	}
271 
272 	class MyOptionDef extends OptionDef {
273 
274 		public MyOptionDef(OptionDef o) {
275 			super(o.usage(), o.metaVar(), o.required(), o.help(), o.hidden(),
276 					o.handler(), o.isMultiValued());
277 		}
278 
279 		@Override
280 		public String toString() {
281 			if (metaVar() == null)
282 				return "ARG"; //$NON-NLS-1$
283 			try {
284 				Field field = CLIText.class.getField(metaVar());
285 				String ret = field.get(CLIText.get()).toString();
286 				return ret;
287 			} catch (Exception e) {
288 				e.printStackTrace(System.err);
289 				return metaVar();
290 			}
291 		}
292 
293 		@Override
294 		public boolean required() {
295 			return seenHelp ? false : super.required();
296 		}
297 	}
298 
299 	/** {@inheritDoc} */
300 	@Override
301 	protected OptionHandler createOptionHandler(OptionDef o, Setter setter) {
302 		if (o instanceof NamedOptionDef)
303 			return super.createOptionHandler(o, setter);
304 		else
305 			return super.createOptionHandler(new MyOptionDef(o), setter);
306 
307 	}
308 
309 	/** {@inheritDoc} */
310 	@Override
311 	public void printSingleLineUsage(Writer w, ResourceBundle rb) {
312 		List<OptionHandler> options = getOptions();
313 		if (options.isEmpty()) {
314 			super.printSingleLineUsage(w, rb);
315 			return;
316 		}
317 		List<OptionHandler> backup = new ArrayList<>(options);
318 		boolean changed = sortRestOfArgumentsHandlerToTheEnd(options);
319 		try {
320 			super.printSingleLineUsage(w, rb);
321 		} finally {
322 			if (changed) {
323 				options.clear();
324 				options.addAll(backup);
325 			}
326 		}
327 	}
328 
329 	private boolean sortRestOfArgumentsHandlerToTheEnd(
330 			List<OptionHandler> options) {
331 		for (int i = 0; i < options.size(); i++) {
332 			OptionHandler handler = options.get(i);
333 			if (handler instanceof RestOfArgumentsHandler
334 					|| handler instanceof PathTreeFilterHandler) {
335 				options.remove(i);
336 				options.add(handler);
337 				return true;
338 			}
339 		}
340 		return false;
341 	}
342 }