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

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