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

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