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.

Main.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. * Copyright (C) 2006, 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 java.io.File;
  46. import java.io.IOException;
  47. import java.io.PrintWriter;
  48. import java.lang.reflect.InvocationTargetException;
  49. import java.net.MalformedURLException;
  50. import java.net.URL;
  51. import java.text.MessageFormat;
  52. import java.util.ArrayList;
  53. import java.util.List;
  54. import org.eclipse.jgit.awtui.AwtAuthenticator;
  55. import org.eclipse.jgit.awtui.AwtCredentialsProvider;
  56. import org.eclipse.jgit.errors.TransportException;
  57. import org.eclipse.jgit.lib.Repository;
  58. import org.eclipse.jgit.lib.RepositoryBuilder;
  59. import org.eclipse.jgit.pgm.internal.CLIText;
  60. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  61. import org.eclipse.jgit.pgm.opt.SubcommandHandler;
  62. import org.eclipse.jgit.util.CachedAuthenticator;
  63. import org.kohsuke.args4j.Argument;
  64. import org.kohsuke.args4j.CmdLineException;
  65. import org.kohsuke.args4j.ExampleMode;
  66. import org.kohsuke.args4j.Option;
  67. /** Command line entry point. */
  68. public class Main {
  69. @Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" })
  70. private boolean help;
  71. @Option(name = "--version", usage = "usage_displayVersion")
  72. private boolean version;
  73. @Option(name = "--show-stack-trace", usage = "usage_displayThejavaStackTraceOnExceptions")
  74. private boolean showStackTrace;
  75. @Option(name = "--git-dir", metaVar = "metaVar_gitDir", usage = "usage_setTheGitRepositoryToOperateOn")
  76. private String gitdir;
  77. @Argument(index = 0, metaVar = "metaVar_command", required = true, handler = SubcommandHandler.class)
  78. private TextBuiltin subcommand;
  79. @Argument(index = 1, metaVar = "metaVar_arg")
  80. private List<String> arguments = new ArrayList<String>();
  81. /**
  82. * Execute the command line.
  83. *
  84. * @param argv
  85. * arguments.
  86. */
  87. public static void main(final String[] argv) {
  88. new Main().run(argv);
  89. }
  90. /**
  91. * Parse the command line and execute the requested action.
  92. *
  93. * Subclasses should allocate themselves and then invoke this method:
  94. *
  95. * <pre>
  96. * class ExtMain {
  97. * public static void main(String[] argv) {
  98. * new ExtMain().run(argv);
  99. * }
  100. * }
  101. * </pre>
  102. *
  103. * @param argv
  104. * arguments.
  105. */
  106. protected void run(final String[] argv) {
  107. try {
  108. if (!installConsole()) {
  109. AwtAuthenticator.install();
  110. AwtCredentialsProvider.install();
  111. }
  112. configureHttpProxy();
  113. execute(argv);
  114. } catch (Die err) {
  115. if (err.isAborted())
  116. System.exit(1);
  117. System.err.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
  118. if (showStackTrace)
  119. err.printStackTrace();
  120. System.exit(128);
  121. } catch (Exception err) {
  122. // Try to detect errno == EPIPE and exit normally if that happens
  123. // There may be issues with operating system versions and locale,
  124. // but we can probably assume that these messages will not be thrown
  125. // under other circumstances.
  126. if (err.getClass() == IOException.class) {
  127. // Linux, OS X
  128. if (err.getMessage().equals("Broken pipe")) //$NON-NLS-1$
  129. System.exit(0);
  130. // Windows
  131. if (err.getMessage().equals("The pipe is being closed")) //$NON-NLS-1$
  132. System.exit(0);
  133. }
  134. if (!showStackTrace && err.getCause() != null
  135. && err instanceof TransportException)
  136. System.err.println(MessageFormat.format(CLIText.get().fatalError, err.getCause().getMessage()));
  137. if (err.getClass().getName().startsWith("org.eclipse.jgit.errors.")) { //$NON-NLS-1$
  138. System.err.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
  139. if (showStackTrace)
  140. err.printStackTrace();
  141. System.exit(128);
  142. }
  143. err.printStackTrace();
  144. System.exit(1);
  145. }
  146. if (System.out.checkError()) {
  147. System.err.println(CLIText.get().unknownIoErrorStdout);
  148. System.exit(1);
  149. }
  150. if (System.err.checkError()) {
  151. // No idea how to present an error here, most likely disk full or
  152. // broken pipe
  153. System.exit(1);
  154. }
  155. }
  156. private void execute(final String[] argv) throws Exception {
  157. final CmdLineParser clp = new CmdLineParser(this);
  158. PrintWriter writer = new PrintWriter(System.err);
  159. try {
  160. clp.parseArgument(argv);
  161. } catch (CmdLineException err) {
  162. if (argv.length > 0 && !help && !version) {
  163. writer.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
  164. writer.flush();
  165. System.exit(1);
  166. }
  167. }
  168. if (argv.length == 0 || help) {
  169. final String ex = clp.printExample(ExampleMode.ALL, CLIText.get().resourceBundle());
  170. writer.println("jgit" + ex + " command [ARG ...]"); //$NON-NLS-1$
  171. if (help) {
  172. writer.println();
  173. clp.printUsage(writer, CLIText.get().resourceBundle());
  174. writer.println();
  175. } else if (subcommand == null) {
  176. writer.println();
  177. writer.println(CLIText.get().mostCommonlyUsedCommandsAre);
  178. final CommandRef[] common = CommandCatalog.common();
  179. int width = 0;
  180. for (final CommandRef c : common)
  181. width = Math.max(width, c.getName().length());
  182. width += 2;
  183. for (final CommandRef c : common) {
  184. writer.print(' ');
  185. writer.print(c.getName());
  186. for (int i = c.getName().length(); i < width; i++)
  187. writer.print(' ');
  188. writer.print(CLIText.get().resourceBundle().getString(c.getUsage()));
  189. writer.println();
  190. }
  191. writer.println();
  192. }
  193. writer.flush();
  194. System.exit(1);
  195. }
  196. if (version) {
  197. String cmdId = Version.class.getSimpleName().toLowerCase();
  198. subcommand = CommandCatalog.get(cmdId).create();
  199. }
  200. final TextBuiltin cmd = subcommand;
  201. if (cmd.requiresRepository())
  202. cmd.init(openGitDir(gitdir), null);
  203. else
  204. cmd.init(null, gitdir);
  205. try {
  206. cmd.execute(arguments.toArray(new String[arguments.size()]));
  207. } finally {
  208. if (cmd.outw != null)
  209. cmd.outw.flush();
  210. if (cmd.errw != null)
  211. cmd.errw.flush();
  212. }
  213. }
  214. /**
  215. * Evaluate the {@code --git-dir} option and open the repository.
  216. *
  217. * @param aGitdir
  218. * the {@code --git-dir} option given on the command line. May be
  219. * null if it was not supplied.
  220. * @return the repository to operate on.
  221. * @throws IOException
  222. * the repository cannot be opened.
  223. */
  224. protected Repository openGitDir(String aGitdir) throws IOException {
  225. RepositoryBuilder rb = new RepositoryBuilder() //
  226. .setGitDir(aGitdir != null ? new File(aGitdir) : null) //
  227. .readEnvironment() //
  228. .findGitDir();
  229. if (rb.getGitDir() == null)
  230. throw new Die(CLIText.get().cantFindGitDirectory);
  231. return rb.build();
  232. }
  233. private static boolean installConsole() {
  234. try {
  235. install("org.eclipse.jgit.console.ConsoleAuthenticator"); //$NON-NLS-1$
  236. install("org.eclipse.jgit.console.ConsoleCredentialsProvider"); //$NON-NLS-1$
  237. return true;
  238. } catch (ClassNotFoundException e) {
  239. return false;
  240. } catch (NoClassDefFoundError e) {
  241. return false;
  242. } catch (UnsupportedClassVersionError e) {
  243. return false;
  244. } catch (IllegalArgumentException e) {
  245. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  246. } catch (SecurityException e) {
  247. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  248. } catch (IllegalAccessException e) {
  249. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  250. } catch (InvocationTargetException e) {
  251. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  252. } catch (NoSuchMethodException e) {
  253. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  254. }
  255. }
  256. private static void install(final String name)
  257. throws IllegalAccessException, InvocationTargetException,
  258. NoSuchMethodException, ClassNotFoundException {
  259. try {
  260. Class.forName(name).getMethod("install").invoke(null); //$NON-NLS-1$
  261. } catch (InvocationTargetException e) {
  262. if (e.getCause() instanceof RuntimeException)
  263. throw (RuntimeException) e.getCause();
  264. if (e.getCause() instanceof Error)
  265. throw (Error) e.getCause();
  266. throw e;
  267. }
  268. }
  269. /**
  270. * Configure the JRE's standard HTTP based on <code>http_proxy</code>.
  271. * <p>
  272. * The popular libcurl library honors the <code>http_proxy</code>
  273. * environment variable as a means of specifying an HTTP proxy for requests
  274. * made behind a firewall. This is not natively recognized by the JRE, so
  275. * this method can be used by command line utilities to configure the JRE
  276. * before the first request is sent.
  277. *
  278. * @throws MalformedURLException
  279. * the value in <code>http_proxy</code> is unsupportable.
  280. */
  281. private static void configureHttpProxy() throws MalformedURLException {
  282. final String s = System.getenv("http_proxy"); //$NON-NLS-1$
  283. if (s == null || s.equals("")) //$NON-NLS-1$
  284. return;
  285. final URL u = new URL((s.indexOf("://") == -1) ? "http://" + s : s); //$NON-NLS-1$ //$NON-NLS-2$
  286. if (!"http".equals(u.getProtocol())) //$NON-NLS-1$
  287. throw new MalformedURLException(MessageFormat.format(CLIText.get().invalidHttpProxyOnlyHttpSupported, s));
  288. final String proxyHost = u.getHost();
  289. final int proxyPort = u.getPort();
  290. System.setProperty("http.proxyHost", proxyHost); //$NON-NLS-1$
  291. if (proxyPort > 0)
  292. System.setProperty("http.proxyPort", String.valueOf(proxyPort)); //$NON-NLS-1$
  293. final String userpass = u.getUserInfo();
  294. if (userpass != null && userpass.contains(":")) { //$NON-NLS-1$
  295. final int c = userpass.indexOf(':');
  296. final String user = userpass.substring(0, c);
  297. final String pass = userpass.substring(c + 1);
  298. CachedAuthenticator
  299. .add(new CachedAuthenticator.CachedAuthentication(
  300. proxyHost, proxyPort, user, pass));
  301. }
  302. }
  303. }