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

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