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

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