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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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.FileOutputStream;
  51. import java.io.IOException;
  52. import java.io.OutputStream;
  53. import java.io.OutputStreamWriter;
  54. import java.io.PrintWriter;
  55. import java.text.MessageFormat;
  56. import java.util.ResourceBundle;
  57. import org.eclipse.jgit.lib.ObjectId;
  58. import org.eclipse.jgit.lib.Repository;
  59. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  60. import org.eclipse.jgit.revwalk.RevWalk;
  61. import org.eclipse.jgit.util.io.ThrowingPrintWriter;
  62. import org.kohsuke.args4j.CmdLineException;
  63. import org.kohsuke.args4j.Option;
  64. /**
  65. * Abstract command which can be invoked from the command line.
  66. * <p>
  67. * Commands are configured with a single "current" repository and then the
  68. * {@link #execute(String[])} method is invoked with the arguments that appear
  69. * on the command line after the command name.
  70. * <p>
  71. * Command constructors should perform as little work as possible as they may be
  72. * invoked very early during process loading, and the command may not execute
  73. * even though it was constructed.
  74. */
  75. public abstract class TextBuiltin {
  76. private String commandName;
  77. @Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" })
  78. private boolean help;
  79. /**
  80. * Writer to output to, typically this is standard output.
  81. *
  82. * @since 2.2
  83. */
  84. protected ThrowingPrintWriter outw;
  85. /**
  86. * Stream to output to, typically this is standard output.
  87. *
  88. * @since 2.2
  89. */
  90. protected OutputStream outs;
  91. /**
  92. * Stream to output to, typically this is standard output.
  93. *
  94. * @deprecated Use outw instead
  95. */
  96. protected PrintWriter out;
  97. /** Git repository the command was invoked within. */
  98. protected Repository db;
  99. /** Directory supplied via --git-dir command line option. */
  100. protected String gitdir;
  101. /** RevWalk used during command line parsing, if it was required. */
  102. protected RevWalk argWalk;
  103. final void setCommandName(final String name) {
  104. commandName = name;
  105. }
  106. /** @return true if {@link #db}/{@link #getRepository()} is required. */
  107. protected boolean requiresRepository() {
  108. return true;
  109. }
  110. /**
  111. * Initialize the command to work with a repository.
  112. *
  113. * @param repository
  114. * the opened repository that the command should work on.
  115. * @param gitDir
  116. * value of the {@code --git-dir} command line option, if
  117. * {@code repository} is null.
  118. */
  119. protected void init(final Repository repository, final String gitDir) {
  120. try {
  121. final String outputEncoding = repository != null ? repository
  122. .getConfig().getString("i18n", null, "logOutputEncoding") : null; //$NON-NLS-1$ //$NON-NLS-2$
  123. if (outs == null)
  124. outs = new FileOutputStream(FileDescriptor.out);
  125. BufferedWriter bufw;
  126. if (outputEncoding != null)
  127. bufw = new BufferedWriter(new OutputStreamWriter(outs,
  128. outputEncoding));
  129. else
  130. bufw = new BufferedWriter(new OutputStreamWriter(outs));
  131. out = new PrintWriter(bufw);
  132. outw = new ThrowingPrintWriter(bufw);
  133. } catch (IOException e) {
  134. throw die(CLIText.get().cannotCreateOutputStream);
  135. }
  136. if (repository != null && repository.getDirectory() != null) {
  137. db = repository;
  138. gitdir = repository.getDirectory().getAbsolutePath();
  139. } else {
  140. db = repository;
  141. gitdir = gitDir;
  142. }
  143. }
  144. /**
  145. * Parse arguments and run this command.
  146. *
  147. * @param args
  148. * command line arguments passed after the command name.
  149. * @throws Exception
  150. * an error occurred while processing the command. The main
  151. * framework will catch the exception and print a message on
  152. * standard error.
  153. */
  154. public final void execute(String[] args) throws Exception {
  155. parseArguments(args);
  156. run();
  157. }
  158. /**
  159. * Parses the command line arguments prior to running.
  160. * <p>
  161. * This method should only be invoked by {@link #execute(String[])}, prior
  162. * to calling {@link #run()}. The default implementation parses all
  163. * arguments into this object's instance fields.
  164. *
  165. * @param args
  166. * the arguments supplied on the command line, if any.
  167. */
  168. protected void parseArguments(final String[] args) {
  169. final CmdLineParser clp = new CmdLineParser(this);
  170. try {
  171. clp.parseArgument(args);
  172. } catch (CmdLineException err) {
  173. if (!help) {
  174. System.err.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
  175. System.exit(1);
  176. }
  177. }
  178. if (help) {
  179. printUsageAndExit(clp);
  180. }
  181. argWalk = clp.getRevWalkGently();
  182. }
  183. /**
  184. * Print the usage line
  185. *
  186. * @param clp
  187. */
  188. public void printUsageAndExit(final CmdLineParser clp) {
  189. printUsageAndExit("", clp); //$NON-NLS-1$
  190. }
  191. /**
  192. * Print an error message and the usage line
  193. *
  194. * @param message
  195. * @param clp
  196. */
  197. public void printUsageAndExit(final String message, final CmdLineParser clp) {
  198. PrintWriter writer = new PrintWriter(System.err);
  199. writer.println(message);
  200. writer.print("jgit "); //$NON-NLS-1$
  201. writer.print(commandName);
  202. clp.printSingleLineUsage(writer, getResourceBundle());
  203. writer.println();
  204. writer.println();
  205. clp.printUsage(writer, getResourceBundle());
  206. writer.println();
  207. writer.flush();
  208. System.exit(1);
  209. }
  210. /**
  211. * @return the resource bundle that will be passed to args4j for purpose
  212. * of string localization
  213. */
  214. protected ResourceBundle getResourceBundle() {
  215. return CLIText.get().resourceBundle();
  216. }
  217. /**
  218. * Perform the actions of this command.
  219. * <p>
  220. * This method should only be invoked by {@link #execute(String[])}.
  221. *
  222. * @throws Exception
  223. * an error occurred while processing the command. The main
  224. * framework will catch the exception and print a message on
  225. * standard error.
  226. */
  227. protected abstract void run() throws Exception;
  228. /**
  229. * @return the repository this command accesses.
  230. */
  231. public Repository getRepository() {
  232. return db;
  233. }
  234. ObjectId resolve(final String s) throws IOException {
  235. final ObjectId r = db.resolve(s);
  236. if (r == null)
  237. throw die(MessageFormat.format(CLIText.get().notARevision, s));
  238. return r;
  239. }
  240. /**
  241. * @param why
  242. * textual explanation
  243. * @return a runtime exception the caller is expected to throw
  244. */
  245. protected static Die die(final String why) {
  246. return new Die(why);
  247. }
  248. /**
  249. * @param why
  250. * textual explanation
  251. * @param cause
  252. * why the command has failed.
  253. * @return a runtime exception the caller is expected to throw
  254. */
  255. protected static Die die(final String why, final Throwable cause) {
  256. return new Die(why, cause);
  257. }
  258. String abbreviateRef(String dst, boolean abbreviateRemote) {
  259. if (dst.startsWith(R_HEADS))
  260. dst = dst.substring(R_HEADS.length());
  261. else if (dst.startsWith(R_TAGS))
  262. dst = dst.substring(R_TAGS.length());
  263. else if (abbreviateRemote && dst.startsWith(R_REMOTES))
  264. dst = dst.substring(R_REMOTES.length());
  265. return dst;
  266. }
  267. }