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.

TextBuiltin.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*
  2. * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.pgm;
  45. import static org.eclipse.jgit.lib.Constants.R_HEADS;
  46. import static org.eclipse.jgit.lib.Constants.R_REMOTES;
  47. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  48. import java.io.BufferedWriter;
  49. import java.io.FileDescriptor;
  50. import java.io.FileInputStream;
  51. import java.io.FileOutputStream;
  52. import java.io.IOException;
  53. import java.io.InputStream;
  54. import java.io.OutputStream;
  55. import java.io.OutputStreamWriter;
  56. import java.text.MessageFormat;
  57. import java.util.ResourceBundle;
  58. import org.eclipse.jgit.lib.ObjectId;
  59. import org.eclipse.jgit.lib.Repository;
  60. import org.eclipse.jgit.pgm.internal.CLIText;
  61. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  62. import org.eclipse.jgit.revwalk.RevWalk;
  63. import org.eclipse.jgit.util.io.ThrowingPrintWriter;
  64. import org.kohsuke.args4j.CmdLineException;
  65. import org.kohsuke.args4j.Option;
  66. /**
  67. * Abstract command which can be invoked from the command line.
  68. * <p>
  69. * Commands are configured with a single "current" repository and then the
  70. * {@link #execute(String[])} method is invoked with the arguments that appear
  71. * on the command line after the command name.
  72. * <p>
  73. * Command constructors should perform as little work as possible as they may be
  74. * invoked very early during process loading, and the command may not execute
  75. * even though it was constructed.
  76. */
  77. public abstract class TextBuiltin {
  78. private String commandName;
  79. @Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" })
  80. private boolean help;
  81. /**
  82. * Input stream, typically this is standard input.
  83. *
  84. * @since 3.4
  85. */
  86. protected InputStream ins;
  87. /**
  88. * Writer to output to, typically this is standard output.
  89. *
  90. * @since 2.2
  91. */
  92. protected ThrowingPrintWriter outw;
  93. /**
  94. * Stream to output to, typically this is standard output.
  95. *
  96. * @since 2.2
  97. */
  98. protected OutputStream outs;
  99. /**
  100. * Error writer, typically this is standard error.
  101. *
  102. * @since 3.4
  103. */
  104. protected ThrowingPrintWriter errw;
  105. /**
  106. * Error output stream, typically this is standard error.
  107. *
  108. * @since 3.4
  109. */
  110. protected OutputStream errs;
  111. /** Git repository the command was invoked within. */
  112. protected Repository db;
  113. /** Directory supplied via --git-dir command line option. */
  114. protected String gitdir;
  115. /** RevWalk used during command line parsing, if it was required. */
  116. protected RevWalk argWalk;
  117. final void setCommandName(final String name) {
  118. commandName = name;
  119. }
  120. /** @return true if {@link #db}/{@link #getRepository()} is required. */
  121. protected boolean requiresRepository() {
  122. return true;
  123. }
  124. /**
  125. * Initialize the command to work with a repository.
  126. *
  127. * @param repository
  128. * the opened repository that the command should work on.
  129. * @param gitDir
  130. * value of the {@code --git-dir} command line option, if
  131. * {@code repository} is null.
  132. */
  133. protected void init(final Repository repository, final String gitDir) {
  134. try {
  135. final String outputEncoding = repository != null ? repository
  136. .getConfig().getString("i18n", null, "logOutputEncoding") : null; //$NON-NLS-1$ //$NON-NLS-2$
  137. if (ins == null)
  138. ins = new FileInputStream(FileDescriptor.in);
  139. if (outs == null)
  140. outs = new FileOutputStream(FileDescriptor.out);
  141. if (errs == null)
  142. errs = new FileOutputStream(FileDescriptor.err);
  143. BufferedWriter outbufw;
  144. if (outputEncoding != null)
  145. outbufw = new BufferedWriter(new OutputStreamWriter(outs,
  146. outputEncoding));
  147. else
  148. outbufw = new BufferedWriter(new OutputStreamWriter(outs));
  149. outw = new ThrowingPrintWriter(outbufw);
  150. BufferedWriter errbufw;
  151. if (outputEncoding != null)
  152. errbufw = new BufferedWriter(new OutputStreamWriter(errs,
  153. outputEncoding));
  154. else
  155. errbufw = new BufferedWriter(new OutputStreamWriter(errs));
  156. errw = new ThrowingPrintWriter(errbufw);
  157. } catch (IOException e) {
  158. throw die(CLIText.get().cannotCreateOutputStream);
  159. }
  160. if (repository != null && repository.getDirectory() != null) {
  161. db = repository;
  162. gitdir = repository.getDirectory().getAbsolutePath();
  163. } else {
  164. db = repository;
  165. gitdir = gitDir;
  166. }
  167. }
  168. /**
  169. * Parse arguments and run this command.
  170. *
  171. * @param args
  172. * command line arguments passed after the command name.
  173. * @throws Exception
  174. * an error occurred while processing the command. The main
  175. * framework will catch the exception and print a message on
  176. * standard error.
  177. */
  178. public final void execute(String[] args) throws Exception {
  179. parseArguments(args);
  180. run();
  181. }
  182. /**
  183. * Parses the command line arguments prior to running.
  184. * <p>
  185. * This method should only be invoked by {@link #execute(String[])}, prior
  186. * to calling {@link #run()}. The default implementation parses all
  187. * arguments into this object's instance fields.
  188. *
  189. * @param args
  190. * the arguments supplied on the command line, if any.
  191. * @throws IOException
  192. */
  193. protected void parseArguments(final String[] args) throws IOException {
  194. final CmdLineParser clp = new CmdLineParser(this);
  195. help = containsHelp(args);
  196. try {
  197. clp.parseArgument(args);
  198. } catch (CmdLineException err) {
  199. this.errw.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
  200. if (help) {
  201. printUsage("", clp); //$NON-NLS-1$
  202. }
  203. throw die(true, err);
  204. }
  205. if (help) {
  206. printUsage("", clp); //$NON-NLS-1$
  207. throw new TerminatedByHelpException();
  208. }
  209. argWalk = clp.getRevWalkGently();
  210. }
  211. /**
  212. * Print the usage line
  213. *
  214. * @param clp
  215. * @throws IOException
  216. */
  217. public void printUsageAndExit(final CmdLineParser clp) throws IOException {
  218. printUsageAndExit("", clp); //$NON-NLS-1$
  219. }
  220. /**
  221. * Print an error message and the usage line
  222. *
  223. * @param message
  224. * @param clp
  225. * @throws IOException
  226. */
  227. public void printUsageAndExit(final String message, final CmdLineParser clp) throws IOException {
  228. printUsage(message, clp);
  229. throw die(true);
  230. }
  231. /**
  232. * @param message
  233. * non null
  234. * @param clp
  235. * parser used to print options
  236. * @throws IOException
  237. * @since 4.2
  238. */
  239. protected void printUsage(final String message, final CmdLineParser clp)
  240. throws IOException {
  241. errw.println(message);
  242. errw.print("jgit "); //$NON-NLS-1$
  243. errw.print(commandName);
  244. clp.printSingleLineUsage(errw, getResourceBundle());
  245. errw.println();
  246. errw.println();
  247. clp.printUsage(errw, getResourceBundle());
  248. errw.println();
  249. errw.flush();
  250. }
  251. /**
  252. * @return the resource bundle that will be passed to args4j for purpose
  253. * of string localization
  254. */
  255. protected ResourceBundle getResourceBundle() {
  256. return CLIText.get().resourceBundle();
  257. }
  258. /**
  259. * Perform the actions of this command.
  260. * <p>
  261. * This method should only be invoked by {@link #execute(String[])}.
  262. *
  263. * @throws Exception
  264. * an error occurred while processing the command. The main
  265. * framework will catch the exception and print a message on
  266. * standard error.
  267. */
  268. protected abstract void run() throws Exception;
  269. /**
  270. * @return the repository this command accesses.
  271. */
  272. public Repository getRepository() {
  273. return db;
  274. }
  275. ObjectId resolve(final String s) throws IOException {
  276. final ObjectId r = db.resolve(s);
  277. if (r == null)
  278. throw die(MessageFormat.format(CLIText.get().notARevision, s));
  279. return r;
  280. }
  281. /**
  282. * @param why
  283. * textual explanation
  284. * @return a runtime exception the caller is expected to throw
  285. */
  286. protected static Die die(final String why) {
  287. return new Die(why);
  288. }
  289. /**
  290. * @param why
  291. * textual explanation
  292. * @param cause
  293. * why the command has failed.
  294. * @return a runtime exception the caller is expected to throw
  295. */
  296. protected static Die die(final String why, final Throwable cause) {
  297. return new Die(why, cause);
  298. }
  299. /**
  300. * @param aborted
  301. * boolean indicating that the execution has been aborted before running
  302. * @return a runtime exception the caller is expected to throw
  303. * @since 3.4
  304. */
  305. protected static Die die(boolean aborted) {
  306. return new Die(aborted);
  307. }
  308. /**
  309. * @param aborted
  310. * boolean indicating that the execution has been aborted before
  311. * running
  312. * @param cause
  313. * why the command has failed.
  314. * @return a runtime exception the caller is expected to throw
  315. * @since 4.2
  316. */
  317. protected static Die die(boolean aborted, final Throwable cause) {
  318. return new Die(aborted, cause);
  319. }
  320. String abbreviateRef(String dst, boolean abbreviateRemote) {
  321. if (dst.startsWith(R_HEADS))
  322. dst = dst.substring(R_HEADS.length());
  323. else if (dst.startsWith(R_TAGS))
  324. dst = dst.substring(R_TAGS.length());
  325. else if (abbreviateRemote && dst.startsWith(R_REMOTES))
  326. dst = dst.substring(R_REMOTES.length());
  327. return dst;
  328. }
  329. /**
  330. * @param args
  331. * non null
  332. * @return true if the given array contains help option
  333. * @since 4.2
  334. */
  335. public static boolean containsHelp(String[] args) {
  336. for (String str : args) {
  337. if (str.equals("-h") || str.equals("--help")) { //$NON-NLS-1$ //$NON-NLS-2$
  338. return true;
  339. }
  340. }
  341. return false;
  342. }
  343. /**
  344. * Exception thrown by {@link TextBuiltin} if it proceeds 'help' option
  345. *
  346. * @since 4.2
  347. */
  348. public static class TerminatedByHelpException extends Die {
  349. private static final long serialVersionUID = 1L;
  350. /**
  351. * Default constructor
  352. */
  353. public TerminatedByHelpException() {
  354. super(true);
  355. }
  356. }
  357. }