You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CmdLineParser.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. package org.eclipse.jgit.pgm.opt;
  44. import java.io.IOException;
  45. import java.io.Writer;
  46. import java.lang.reflect.Field;
  47. import java.util.ArrayList;
  48. import java.util.Collections;
  49. import java.util.Iterator;
  50. import java.util.List;
  51. import java.util.ResourceBundle;
  52. import org.eclipse.jgit.lib.ObjectId;
  53. import org.eclipse.jgit.lib.Repository;
  54. import org.eclipse.jgit.pgm.Die;
  55. import org.eclipse.jgit.pgm.TextBuiltin;
  56. import org.eclipse.jgit.pgm.internal.CLIText;
  57. import org.eclipse.jgit.revwalk.RevCommit;
  58. import org.eclipse.jgit.revwalk.RevTree;
  59. import org.eclipse.jgit.revwalk.RevWalk;
  60. import org.eclipse.jgit.transport.RefSpec;
  61. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  62. import org.kohsuke.args4j.Argument;
  63. import org.kohsuke.args4j.CmdLineException;
  64. import org.kohsuke.args4j.IllegalAnnotationError;
  65. import org.kohsuke.args4j.NamedOptionDef;
  66. import org.kohsuke.args4j.Option;
  67. import org.kohsuke.args4j.OptionDef;
  68. import org.kohsuke.args4j.spi.OptionHandler;
  69. import org.kohsuke.args4j.spi.RestOfArgumentsHandler;
  70. import org.kohsuke.args4j.spi.Setter;
  71. /**
  72. * Extended command line parser which handles --foo=value arguments.
  73. * <p>
  74. * The args4j package does not natively handle --foo=value and instead prefers
  75. * to see --foo value on the command line. Many users are used to the GNU style
  76. * --foo=value long option, so we convert from the GNU style format to the
  77. * args4j style format prior to invoking args4j for parsing.
  78. */
  79. public class CmdLineParser extends org.kohsuke.args4j.CmdLineParser {
  80. static {
  81. registerHandler(AbstractTreeIterator.class,
  82. AbstractTreeIteratorHandler.class);
  83. registerHandler(ObjectId.class, ObjectIdHandler.class);
  84. registerHandler(RefSpec.class, RefSpecHandler.class);
  85. registerHandler(RevCommit.class, RevCommitHandler.class);
  86. registerHandler(RevTree.class, RevTreeHandler.class);
  87. registerHandler(List.class, OptionWithValuesListHandler.class);
  88. }
  89. private final Repository db;
  90. private RevWalk walk;
  91. private boolean seenHelp;
  92. private TextBuiltin cmd;
  93. /**
  94. * Creates a new command line owner that parses arguments/options and set
  95. * them into the given object.
  96. *
  97. * @param bean
  98. * instance of a class annotated by {@link Option} and
  99. * {@link Argument}. this object will receive values.
  100. *
  101. * @throws IllegalAnnotationError
  102. * if the option bean class is using args4j annotations
  103. * incorrectly.
  104. */
  105. public CmdLineParser(final Object bean) {
  106. this(bean, null);
  107. }
  108. /**
  109. * Creates a new command line owner that parses arguments/options and set
  110. * them into the given object.
  111. *
  112. * @param bean
  113. * instance of a class annotated by {@link Option} and
  114. * {@link Argument}. this object will receive values.
  115. * @param repo
  116. * repository this parser can translate options through.
  117. * @throws IllegalAnnotationError
  118. * if the option bean class is using args4j annotations
  119. * incorrectly.
  120. */
  121. public CmdLineParser(final Object bean, Repository repo) {
  122. super(bean);
  123. if (bean instanceof TextBuiltin) {
  124. cmd = (TextBuiltin) bean;
  125. }
  126. if (repo == null && cmd != null) {
  127. repo = cmd.getRepository();
  128. }
  129. this.db = repo;
  130. }
  131. @Override
  132. public void parseArgument(final String... args) throws CmdLineException {
  133. final ArrayList<String> tmp = new ArrayList<>(args.length);
  134. for (int argi = 0; argi < args.length; argi++) {
  135. final String str = args[argi];
  136. if (str.equals("--")) { //$NON-NLS-1$
  137. while (argi < args.length)
  138. tmp.add(args[argi++]);
  139. break;
  140. }
  141. if (str.startsWith("--")) { //$NON-NLS-1$
  142. final int eq = str.indexOf('=');
  143. if (eq > 0) {
  144. tmp.add(str.substring(0, eq));
  145. tmp.add(str.substring(eq + 1));
  146. continue;
  147. }
  148. }
  149. tmp.add(str);
  150. if (containsHelp(args)) {
  151. // suppress exceptions on required parameters if help is present
  152. seenHelp = true;
  153. // stop argument parsing here
  154. break;
  155. }
  156. }
  157. List<OptionHandler> backup = null;
  158. if (seenHelp) {
  159. backup = unsetRequiredOptions();
  160. }
  161. try {
  162. super.parseArgument(tmp.toArray(new String[tmp.size()]));
  163. } catch (Die e) {
  164. if (!seenHelp) {
  165. throw e;
  166. }
  167. printToErrorWriter(CLIText.fatalError(e.getMessage()));
  168. } finally {
  169. // reset "required" options to defaults for correct command printout
  170. if (backup != null && !backup.isEmpty()) {
  171. restoreRequiredOptions(backup);
  172. }
  173. seenHelp = false;
  174. }
  175. }
  176. private void printToErrorWriter(String error) {
  177. if (cmd == null) {
  178. System.err.println(error);
  179. } else {
  180. try {
  181. cmd.getErrorWriter().println(error);
  182. } catch (IOException e1) {
  183. System.err.println(error);
  184. }
  185. }
  186. }
  187. private List<OptionHandler> unsetRequiredOptions() {
  188. List<OptionHandler> options = getOptions();
  189. List<OptionHandler> backup = new ArrayList<>(options);
  190. for (Iterator<OptionHandler> iterator = options.iterator(); iterator
  191. .hasNext();) {
  192. OptionHandler handler = iterator.next();
  193. if (handler.option instanceof NamedOptionDef
  194. && handler.option.required()) {
  195. iterator.remove();
  196. }
  197. }
  198. return backup;
  199. }
  200. private void restoreRequiredOptions(List<OptionHandler> backup) {
  201. List<OptionHandler> options = getOptions();
  202. options.clear();
  203. options.addAll(backup);
  204. }
  205. /**
  206. * @param args
  207. * non null
  208. * @return true if the given array contains help option
  209. * @since 4.2
  210. */
  211. protected boolean containsHelp(final String... args) {
  212. return TextBuiltin.containsHelp(args);
  213. }
  214. /**
  215. * Get the repository this parser translates values through.
  216. *
  217. * @return the repository, if specified during construction.
  218. */
  219. public Repository getRepository() {
  220. if (db == null)
  221. throw new IllegalStateException(CLIText.get().noGitRepositoryConfigured);
  222. return db;
  223. }
  224. /**
  225. * Get the revision walker used to support option parsing.
  226. *
  227. * @return the revision walk used by this option parser.
  228. */
  229. public RevWalk getRevWalk() {
  230. if (walk == null)
  231. walk = new RevWalk(getRepository());
  232. return walk;
  233. }
  234. /**
  235. * Get the revision walker used to support option parsing.
  236. * <p>
  237. * This method does not initialize the RevWalk and may return null.
  238. *
  239. * @return the revision walk used by this option parser, or null.
  240. */
  241. public RevWalk getRevWalkGently() {
  242. return walk;
  243. }
  244. class MyOptionDef extends OptionDef {
  245. public MyOptionDef(OptionDef o) {
  246. super(o.usage(), o.metaVar(), o.required(), o.handler(), o
  247. .isMultiValued());
  248. }
  249. @Override
  250. public String toString() {
  251. if (metaVar() == null)
  252. return "ARG"; //$NON-NLS-1$
  253. try {
  254. Field field = CLIText.class.getField(metaVar());
  255. String ret = field.get(CLIText.get()).toString();
  256. return ret;
  257. } catch (Exception e) {
  258. e.printStackTrace(System.err);
  259. return metaVar();
  260. }
  261. }
  262. @Override
  263. public boolean required() {
  264. return seenHelp ? false : super.required();
  265. }
  266. }
  267. @Override
  268. protected OptionHandler createOptionHandler(OptionDef o, Setter setter) {
  269. if (o instanceof NamedOptionDef)
  270. return super.createOptionHandler(o, setter);
  271. else
  272. return super.createOptionHandler(new MyOptionDef(o), setter);
  273. }
  274. @SuppressWarnings("unchecked")
  275. private List<OptionHandler> getOptions() {
  276. List<OptionHandler> options = null;
  277. try {
  278. Field field = org.kohsuke.args4j.CmdLineParser.class
  279. .getDeclaredField("options"); //$NON-NLS-1$
  280. field.setAccessible(true);
  281. options = (List<OptionHandler>) field.get(this);
  282. } catch (NoSuchFieldException | SecurityException
  283. | IllegalArgumentException | IllegalAccessException e) {
  284. // ignore
  285. }
  286. if (options == null) {
  287. return Collections.emptyList();
  288. }
  289. return options;
  290. }
  291. @Override
  292. public void printSingleLineUsage(Writer w, ResourceBundle rb) {
  293. List<OptionHandler> options = getOptions();
  294. if (options.isEmpty()) {
  295. super.printSingleLineUsage(w, rb);
  296. return;
  297. }
  298. List<OptionHandler> backup = new ArrayList<>(options);
  299. boolean changed = sortRestOfArgumentsHandlerToTheEnd(options);
  300. try {
  301. super.printSingleLineUsage(w, rb);
  302. } finally {
  303. if (changed) {
  304. options.clear();
  305. options.addAll(backup);
  306. }
  307. }
  308. }
  309. private boolean sortRestOfArgumentsHandlerToTheEnd(
  310. List<OptionHandler> options) {
  311. for (int i = 0; i < options.size(); i++) {
  312. OptionHandler handler = options.get(i);
  313. if (handler instanceof RestOfArgumentsHandler
  314. || handler instanceof PathTreeFilterHandler) {
  315. options.remove(i);
  316. options.add(handler);
  317. return true;
  318. }
  319. }
  320. return false;
  321. }
  322. }