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.

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