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 8.8KB

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