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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 java.util.Locale;
  55. import org.eclipse.jgit.awtui.AwtAuthenticator;
  56. import org.eclipse.jgit.awtui.AwtCredentialsProvider;
  57. import org.eclipse.jgit.errors.TransportException;
  58. import org.eclipse.jgit.lfs.CleanFilter;
  59. import org.eclipse.jgit.lfs.SmudgeFilter;
  60. import org.eclipse.jgit.lib.Repository;
  61. import org.eclipse.jgit.lib.RepositoryBuilder;
  62. import org.eclipse.jgit.pgm.internal.CLIText;
  63. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  64. import org.eclipse.jgit.pgm.opt.SubcommandHandler;
  65. import org.eclipse.jgit.transport.HttpTransport;
  66. import org.eclipse.jgit.transport.http.apache.HttpClientConnectionFactory;
  67. import org.eclipse.jgit.util.CachedAuthenticator;
  68. import org.kohsuke.args4j.Argument;
  69. import org.kohsuke.args4j.CmdLineException;
  70. import org.kohsuke.args4j.ExampleMode;
  71. import org.kohsuke.args4j.Option;
  72. /** Command line entry point. */
  73. public class Main {
  74. @Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" })
  75. private boolean help;
  76. @Option(name = "--version", usage = "usage_displayVersion")
  77. private boolean version;
  78. @Option(name = "--show-stack-trace", usage = "usage_displayThejavaStackTraceOnExceptions")
  79. private boolean showStackTrace;
  80. @Option(name = "--git-dir", metaVar = "metaVar_gitDir", usage = "usage_setTheGitRepositoryToOperateOn")
  81. private String gitdir;
  82. @Argument(index = 0, metaVar = "metaVar_command", required = true, handler = SubcommandHandler.class)
  83. private TextBuiltin subcommand;
  84. @Argument(index = 1, metaVar = "metaVar_arg")
  85. private List<String> arguments = new ArrayList<>();
  86. PrintWriter writer;
  87. /**
  88. *
  89. */
  90. public Main() {
  91. HttpTransport.setConnectionFactory(new HttpClientConnectionFactory());
  92. CleanFilter.register();
  93. SmudgeFilter.register();
  94. }
  95. /**
  96. * Execute the command line.
  97. *
  98. * @param argv
  99. * arguments.
  100. * @throws Exception
  101. */
  102. public static void main(final String[] argv) throws Exception {
  103. new Main().run(argv);
  104. }
  105. /**
  106. * Parse the command line and execute the requested action.
  107. *
  108. * Subclasses should allocate themselves and then invoke this method:
  109. *
  110. * <pre>
  111. * class ExtMain {
  112. * public static void main(String[] argv) {
  113. * new ExtMain().run(argv);
  114. * }
  115. * }
  116. * </pre>
  117. *
  118. * @param argv
  119. * arguments.
  120. * @throws Exception
  121. */
  122. protected void run(final String[] argv) throws Exception {
  123. writer = createErrorWriter();
  124. try {
  125. if (!installConsole()) {
  126. AwtAuthenticator.install();
  127. AwtCredentialsProvider.install();
  128. }
  129. configureHttpProxy();
  130. execute(argv);
  131. } catch (Die err) {
  132. if (err.isAborted()) {
  133. exit(1, err);
  134. }
  135. writer.println(CLIText.fatalError(err.getMessage()));
  136. if (showStackTrace) {
  137. err.printStackTrace(writer);
  138. }
  139. exit(128, err);
  140. } catch (Exception err) {
  141. // Try to detect errno == EPIPE and exit normally if that happens
  142. // There may be issues with operating system versions and locale,
  143. // but we can probably assume that these messages will not be thrown
  144. // under other circumstances.
  145. if (err.getClass() == IOException.class) {
  146. // Linux, OS X
  147. if (err.getMessage().equals("Broken pipe")) { //$NON-NLS-1$
  148. exit(0, err);
  149. }
  150. // Windows
  151. if (err.getMessage().equals("The pipe is being closed")) { //$NON-NLS-1$
  152. exit(0, err);
  153. }
  154. }
  155. if (!showStackTrace && err.getCause() != null
  156. && err instanceof TransportException) {
  157. writer.println(CLIText.fatalError(err.getCause().getMessage()));
  158. }
  159. if (err.getClass().getName().startsWith("org.eclipse.jgit.errors.")) { //$NON-NLS-1$
  160. writer.println(CLIText.fatalError(err.getMessage()));
  161. if (showStackTrace) {
  162. err.printStackTrace();
  163. }
  164. exit(128, err);
  165. }
  166. err.printStackTrace();
  167. exit(1, err);
  168. }
  169. if (System.out.checkError()) {
  170. writer.println(CLIText.get().unknownIoErrorStdout);
  171. exit(1, null);
  172. }
  173. if (writer.checkError()) {
  174. // No idea how to present an error here, most likely disk full or
  175. // broken pipe
  176. exit(1, null);
  177. }
  178. }
  179. PrintWriter createErrorWriter() {
  180. return new PrintWriter(System.err);
  181. }
  182. private void execute(final String[] argv) throws Exception {
  183. final CmdLineParser clp = new SubcommandLineParser(this);
  184. try {
  185. clp.parseArgument(argv);
  186. } catch (CmdLineException err) {
  187. if (argv.length > 0 && !help && !version) {
  188. writer.println(CLIText.fatalError(err.getMessage()));
  189. writer.flush();
  190. exit(1, err);
  191. }
  192. }
  193. if (argv.length == 0 || help) {
  194. final String ex = clp.printExample(ExampleMode.ALL, CLIText.get().resourceBundle());
  195. writer.println("jgit" + ex + " command [ARG ...]"); //$NON-NLS-1$ //$NON-NLS-2$
  196. if (help) {
  197. writer.println();
  198. clp.printUsage(writer, CLIText.get().resourceBundle());
  199. writer.println();
  200. } else if (subcommand == null) {
  201. writer.println();
  202. writer.println(CLIText.get().mostCommonlyUsedCommandsAre);
  203. final CommandRef[] common = CommandCatalog.common();
  204. int width = 0;
  205. for (final CommandRef c : common) {
  206. width = Math.max(width, c.getName().length());
  207. }
  208. width += 2;
  209. for (final CommandRef c : common) {
  210. writer.print(' ');
  211. writer.print(c.getName());
  212. for (int i = c.getName().length(); i < width; i++) {
  213. writer.print(' ');
  214. }
  215. writer.print(CLIText.get().resourceBundle().getString(c.getUsage()));
  216. writer.println();
  217. }
  218. writer.println();
  219. }
  220. writer.flush();
  221. exit(1, null);
  222. }
  223. if (version) {
  224. String cmdId = Version.class.getSimpleName()
  225. .toLowerCase(Locale.ROOT);
  226. subcommand = CommandCatalog.get(cmdId).create();
  227. }
  228. final TextBuiltin cmd = subcommand;
  229. init(cmd);
  230. try {
  231. cmd.execute(arguments.toArray(new String[arguments.size()]));
  232. } finally {
  233. if (cmd.outw != null) {
  234. cmd.outw.flush();
  235. }
  236. if (cmd.errw != null) {
  237. cmd.errw.flush();
  238. }
  239. }
  240. }
  241. void init(final TextBuiltin cmd) throws IOException {
  242. if (cmd.requiresRepository()) {
  243. cmd.init(openGitDir(gitdir), null);
  244. } else {
  245. cmd.init(null, gitdir);
  246. }
  247. }
  248. /**
  249. * @param status
  250. * @param t
  251. * can be {@code null}
  252. * @throws Exception
  253. */
  254. void exit(int status, Exception t) throws Exception {
  255. writer.flush();
  256. System.exit(status);
  257. }
  258. /**
  259. * Evaluate the {@code --git-dir} option and open the repository.
  260. *
  261. * @param aGitdir
  262. * the {@code --git-dir} option given on the command line. May be
  263. * null if it was not supplied.
  264. * @return the repository to operate on.
  265. * @throws IOException
  266. * the repository cannot be opened.
  267. */
  268. protected Repository openGitDir(String aGitdir) throws IOException {
  269. RepositoryBuilder rb = new RepositoryBuilder() //
  270. .setGitDir(aGitdir != null ? new File(aGitdir) : null) //
  271. .readEnvironment() //
  272. .findGitDir();
  273. if (rb.getGitDir() == null)
  274. throw new Die(CLIText.get().cantFindGitDirectory);
  275. return rb.build();
  276. }
  277. private static boolean installConsole() {
  278. try {
  279. install("org.eclipse.jgit.console.ConsoleAuthenticator"); //$NON-NLS-1$
  280. install("org.eclipse.jgit.console.ConsoleCredentialsProvider"); //$NON-NLS-1$
  281. return true;
  282. } catch (ClassNotFoundException e) {
  283. return false;
  284. } catch (NoClassDefFoundError e) {
  285. return false;
  286. } catch (UnsupportedClassVersionError e) {
  287. return false;
  288. } catch (IllegalArgumentException e) {
  289. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  290. } catch (SecurityException e) {
  291. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  292. } catch (IllegalAccessException e) {
  293. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  294. } catch (InvocationTargetException e) {
  295. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  296. } catch (NoSuchMethodException e) {
  297. throw new RuntimeException(CLIText.get().cannotSetupConsole, e);
  298. }
  299. }
  300. private static void install(final String name)
  301. throws IllegalAccessException, InvocationTargetException,
  302. NoSuchMethodException, ClassNotFoundException {
  303. try {
  304. Class.forName(name).getMethod("install").invoke(null); //$NON-NLS-1$
  305. } catch (InvocationTargetException e) {
  306. if (e.getCause() instanceof RuntimeException)
  307. throw (RuntimeException) e.getCause();
  308. if (e.getCause() instanceof Error)
  309. throw (Error) e.getCause();
  310. throw e;
  311. }
  312. }
  313. /**
  314. * Configure the JRE's standard HTTP based on <code>http_proxy</code>.
  315. * <p>
  316. * The popular libcurl library honors the <code>http_proxy</code>,
  317. * <code>https_proxy</code> environment variables as a means of specifying
  318. * an HTTP/S proxy for requests made behind a firewall. This is not natively
  319. * recognized by the JRE, so this method can be used by command line
  320. * utilities to configure the JRE before the first request is sent. The
  321. * information found in the environment variables is copied to the
  322. * associated system properties. This is not done when the system properties
  323. * are already set. The default way of telling java programs about proxies
  324. * (the system properties) takes precedence over environment variables.
  325. *
  326. * @throws MalformedURLException
  327. * the value in <code>http_proxy</code> or
  328. * <code>https_proxy</code> is unsupportable.
  329. */
  330. static void configureHttpProxy() throws MalformedURLException {
  331. for (String protocol : new String[] { "http", "https" }) { //$NON-NLS-1$ //$NON-NLS-2$
  332. if (System.getProperty(protocol + ".proxyHost") != null) { //$NON-NLS-1$
  333. continue;
  334. }
  335. String s = System.getenv(protocol + "_proxy"); //$NON-NLS-1$
  336. if (s == null && protocol.equals("https")) { //$NON-NLS-1$
  337. s = System.getenv("HTTPS_PROXY"); //$NON-NLS-1$
  338. }
  339. if (s == null || s.equals("")) { //$NON-NLS-1$
  340. continue;
  341. }
  342. final URL u = new URL(
  343. (s.indexOf("://") == -1) ? protocol + "://" + s : s); //$NON-NLS-1$ //$NON-NLS-2$
  344. if (!u.getProtocol().startsWith("http")) //$NON-NLS-1$
  345. throw new MalformedURLException(MessageFormat.format(
  346. CLIText.get().invalidHttpProxyOnlyHttpSupported, s));
  347. final String proxyHost = u.getHost();
  348. final int proxyPort = u.getPort();
  349. System.setProperty(protocol + ".proxyHost", proxyHost); //$NON-NLS-1$
  350. if (proxyPort > 0)
  351. System.setProperty(protocol + ".proxyPort", //$NON-NLS-1$
  352. String.valueOf(proxyPort));
  353. final String userpass = u.getUserInfo();
  354. if (userpass != null && userpass.contains(":")) { //$NON-NLS-1$
  355. final int c = userpass.indexOf(':');
  356. final String user = userpass.substring(0, c);
  357. final String pass = userpass.substring(c + 1);
  358. CachedAuthenticator.add(
  359. new CachedAuthenticator.CachedAuthentication(proxyHost,
  360. proxyPort, user, pass));
  361. }
  362. }
  363. }
  364. /**
  365. * Parser for subcommands which doesn't stop parsing on help options and so
  366. * proceeds all specified options
  367. */
  368. static class SubcommandLineParser extends CmdLineParser {
  369. public SubcommandLineParser(Object bean) {
  370. super(bean);
  371. }
  372. @Override
  373. protected boolean containsHelp(String... args) {
  374. return false;
  375. }
  376. }
  377. }