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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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.PrintWriter;
  47. import java.lang.reflect.InvocationTargetException;
  48. import java.net.MalformedURLException;
  49. import java.net.URL;
  50. import java.text.MessageFormat;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.HashSet;
  54. import java.util.List;
  55. import java.util.Set;
  56. import org.eclipse.jgit.awtui.AwtAuthenticator;
  57. import org.eclipse.jgit.awtui.AwtSshSessionFactory;
  58. import org.eclipse.jgit.errors.TransportException;
  59. import org.eclipse.jgit.lib.Constants;
  60. import org.eclipse.jgit.lib.Repository;
  61. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  62. import org.eclipse.jgit.pgm.opt.SubcommandHandler;
  63. import org.eclipse.jgit.util.CachedAuthenticator;
  64. import org.eclipse.jgit.util.SystemReader;
  65. import org.kohsuke.args4j.Argument;
  66. import org.kohsuke.args4j.CmdLineException;
  67. import org.kohsuke.args4j.ExampleMode;
  68. import org.kohsuke.args4j.Option;
  69. /** Command line entry point. */
  70. public class Main {
  71. @Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" })
  72. private boolean help;
  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 File 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. final Main me = new Main();
  89. try {
  90. if (!installConsole()) {
  91. AwtAuthenticator.install();
  92. AwtSshSessionFactory.install();
  93. }
  94. configureHttpProxy();
  95. me.execute(argv);
  96. } catch (Die err) {
  97. System.err.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
  98. if (me.showStackTrace)
  99. err.printStackTrace();
  100. System.exit(128);
  101. } catch (Exception err) {
  102. if (!me.showStackTrace && err.getCause() != null
  103. && err instanceof TransportException)
  104. System.err.println(MessageFormat.format(CLIText.get().fatalError, err.getCause().getMessage()));
  105. if (err.getClass().getName().startsWith("org.eclipse.jgit.errors.")) {
  106. System.err.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
  107. if (me.showStackTrace)
  108. err.printStackTrace();
  109. System.exit(128);
  110. }
  111. err.printStackTrace();
  112. System.exit(1);
  113. }
  114. }
  115. private void execute(final String[] argv) throws Exception {
  116. final CmdLineParser clp = new CmdLineParser(this);
  117. PrintWriter writer = new PrintWriter(System.err);
  118. try {
  119. clp.parseArgument(argv);
  120. } catch (CmdLineException err) {
  121. if (argv.length > 0 && !help) {
  122. writer.println(MessageFormat.format(CLIText.get().fatalError, err.getMessage()));
  123. writer.flush();
  124. System.exit(1);
  125. }
  126. }
  127. if (argv.length == 0 || help) {
  128. final String ex = clp.printExample(ExampleMode.ALL, CLIText.get().resourceBundle());
  129. writer.println("jgit" + ex + " command [ARG ...]");
  130. if (help) {
  131. writer.println();
  132. clp.printUsage(writer, CLIText.get().resourceBundle());
  133. writer.println();
  134. } else if (subcommand == null) {
  135. writer.println();
  136. writer.println(CLIText.get().mostCommonlyUsedCommandsAre);
  137. final CommandRef[] common = CommandCatalog.common();
  138. int width = 0;
  139. for (final CommandRef c : common)
  140. width = Math.max(width, c.getName().length());
  141. width += 2;
  142. for (final CommandRef c : common) {
  143. writer.print(' ');
  144. writer.print(c.getName());
  145. for (int i = c.getName().length(); i < width; i++)
  146. writer.print(' ');
  147. writer.print(CLIText.get().resourceBundle().getString(c.getUsage()));
  148. writer.println();
  149. }
  150. writer.println();
  151. }
  152. writer.flush();
  153. System.exit(1);
  154. }
  155. final TextBuiltin cmd = subcommand;
  156. if (cmd.requiresRepository()) {
  157. if (gitdir == null) {
  158. String gitDirEnv = SystemReader.getInstance().getenv(Constants.GIT_DIR_KEY);
  159. if (gitDirEnv != null)
  160. gitdir = new File(gitDirEnv);
  161. }
  162. if (gitdir == null)
  163. gitdir = findGitDir();
  164. File gitworktree;
  165. String gitWorkTreeEnv = SystemReader.getInstance().getenv(Constants.GIT_WORK_TREE_KEY);
  166. if (gitWorkTreeEnv != null)
  167. gitworktree = new File(gitWorkTreeEnv);
  168. else
  169. gitworktree = null;
  170. File indexfile;
  171. String indexFileEnv = SystemReader.getInstance().getenv(Constants.GIT_INDEX_KEY);
  172. if (indexFileEnv != null)
  173. indexfile = new File(indexFileEnv);
  174. else
  175. indexfile = null;
  176. File objectdir;
  177. String objectDirEnv = SystemReader.getInstance().getenv(Constants.GIT_OBJECT_DIRECTORY_KEY);
  178. if (objectDirEnv != null)
  179. objectdir = new File(objectDirEnv);
  180. else
  181. objectdir = null;
  182. File[] altobjectdirs;
  183. String altObjectDirEnv = SystemReader.getInstance().getenv(Constants.GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY);
  184. if (altObjectDirEnv != null) {
  185. String[] parserdAltObjectDirEnv = altObjectDirEnv.split(File.pathSeparator);
  186. altobjectdirs = new File[parserdAltObjectDirEnv.length];
  187. for (int i = 0; i < parserdAltObjectDirEnv.length; i++)
  188. altobjectdirs[i] = new File(parserdAltObjectDirEnv[i]);
  189. } else
  190. altobjectdirs = null;
  191. if (gitdir == null || !gitdir.isDirectory()) {
  192. writer.println(CLIText.get().cantFindGitDirectory);
  193. writer.flush();
  194. System.exit(1);
  195. }
  196. cmd.init(new Repository(gitdir, gitworktree, objectdir, altobjectdirs, indexfile), gitdir);
  197. } else {
  198. cmd.init(null, gitdir);
  199. }
  200. try {
  201. cmd.execute(arguments.toArray(new String[arguments.size()]));
  202. } finally {
  203. if (cmd.out != null)
  204. cmd.out.flush();
  205. }
  206. }
  207. private static File findGitDir() {
  208. Set<String> ceilingDirectories = new HashSet<String>();
  209. String ceilingDirectoriesVar = SystemReader.getInstance().getenv(
  210. Constants.GIT_CEILING_DIRECTORIES_KEY);
  211. if (ceilingDirectoriesVar != null) {
  212. ceilingDirectories.addAll(Arrays.asList(ceilingDirectoriesVar
  213. .split(File.pathSeparator)));
  214. }
  215. File current = new File("").getAbsoluteFile();
  216. while (current != null) {
  217. final File gitDir = new File(current, Constants.DOT_GIT);
  218. if (gitDir.isDirectory())
  219. return gitDir;
  220. current = current.getParentFile();
  221. if (current != null
  222. && ceilingDirectories.contains(current.getPath()))
  223. break;
  224. }
  225. return null;
  226. }
  227. private static boolean installConsole() {
  228. try {
  229. install("org.eclipse.jgit.console.ConsoleAuthenticator");
  230. install("org.eclipse.jgit.console.ConsoleSshSessionFactory");
  231. return true;
  232. } catch (ClassNotFoundException e) {
  233. return false;
  234. } catch (NoClassDefFoundError e) {
  235. return false;
  236. } catch (UnsupportedClassVersionError e) {
  237. return false;
  238. } catch (IllegalArgumentException e) {
  239. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  240. } catch (SecurityException e) {
  241. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  242. } catch (IllegalAccessException e) {
  243. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  244. } catch (InvocationTargetException e) {
  245. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  246. } catch (NoSuchMethodException e) {
  247. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  248. }
  249. }
  250. private static void install(final String name)
  251. throws IllegalAccessException, InvocationTargetException,
  252. NoSuchMethodException, ClassNotFoundException {
  253. try {
  254. Class.forName(name).getMethod("install").invoke(null);
  255. } catch (InvocationTargetException e) {
  256. if (e.getCause() instanceof RuntimeException)
  257. throw (RuntimeException) e.getCause();
  258. if (e.getCause() instanceof Error)
  259. throw (Error) e.getCause();
  260. throw e;
  261. }
  262. }
  263. /**
  264. * Configure the JRE's standard HTTP based on <code>http_proxy</code>.
  265. * <p>
  266. * The popular libcurl library honors the <code>http_proxy</code>
  267. * environment variable as a means of specifying an HTTP proxy for requests
  268. * made behind a firewall. This is not natively recognized by the JRE, so
  269. * this method can be used by command line utilities to configure the JRE
  270. * before the first request is sent.
  271. *
  272. * @throws MalformedURLException
  273. * the value in <code>http_proxy</code> is unsupportable.
  274. */
  275. private static void configureHttpProxy() throws MalformedURLException {
  276. final String s = System.getenv("http_proxy");
  277. if (s == null || s.equals(""))
  278. return;
  279. final URL u = new URL((s.indexOf("://") == -1) ? "http://" + s : s);
  280. if (!"http".equals(u.getProtocol()))
  281. throw new MalformedURLException(MessageFormat.format(CLIText.get().invalidHttpProxyOnlyHttpSupported, s));
  282. final String proxyHost = u.getHost();
  283. final int proxyPort = u.getPort();
  284. System.setProperty("http.proxyHost", proxyHost);
  285. if (proxyPort > 0)
  286. System.setProperty("http.proxyPort", String.valueOf(proxyPort));
  287. final String userpass = u.getUserInfo();
  288. if (userpass != null && userpass.contains(":")) {
  289. final int c = userpass.indexOf(':');
  290. final String user = userpass.substring(0, c);
  291. final String pass = userpass.substring(c + 1);
  292. CachedAuthenticator
  293. .add(new CachedAuthenticator.CachedAuthentication(
  294. proxyHost, proxyPort, user, pass));
  295. }
  296. }
  297. }