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.

TextBuiltin.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Copyright (C) 2007, 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 static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_LOG_OUTPUT_ENCODING;
  47. import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_SECTION_I18N;
  48. import static org.eclipse.jgit.lib.Constants.R_HEADS;
  49. import static org.eclipse.jgit.lib.Constants.R_REMOTES;
  50. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  51. import java.io.BufferedWriter;
  52. import java.io.FileDescriptor;
  53. import java.io.FileInputStream;
  54. import java.io.FileOutputStream;
  55. import java.io.IOException;
  56. import java.io.InputStream;
  57. import java.io.OutputStream;
  58. import java.io.OutputStreamWriter;
  59. import java.nio.charset.Charset;
  60. import java.text.MessageFormat;
  61. import java.util.ResourceBundle;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.pgm.internal.CLIText;
  65. import org.eclipse.jgit.pgm.internal.SshDriver;
  66. import org.eclipse.jgit.pgm.opt.CmdLineParser;
  67. import org.eclipse.jgit.revwalk.RevWalk;
  68. import org.eclipse.jgit.transport.SshSessionFactory;
  69. import org.eclipse.jgit.transport.sshd.DefaultProxyDataFactory;
  70. import org.eclipse.jgit.transport.sshd.JGitKeyCache;
  71. import org.eclipse.jgit.transport.sshd.SshdSessionFactory;
  72. import org.eclipse.jgit.util.io.ThrowingPrintWriter;
  73. import org.kohsuke.args4j.CmdLineException;
  74. import org.kohsuke.args4j.Option;
  75. /**
  76. * Abstract command which can be invoked from the command line.
  77. * <p>
  78. * Commands are configured with a single "current" repository and then the
  79. * {@link #execute(String[])} method is invoked with the arguments that appear
  80. * on the command line after the command name.
  81. * <p>
  82. * Command constructors should perform as little work as possible as they may be
  83. * invoked very early during process loading, and the command may not execute
  84. * even though it was constructed.
  85. */
  86. public abstract class TextBuiltin {
  87. private String commandName;
  88. @Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" })
  89. private boolean help;
  90. @Option(name = "--ssh", usage = "usage_sshDriver")
  91. private SshDriver sshDriver = SshDriver.JSCH;
  92. /**
  93. * Input stream, typically this is standard input.
  94. *
  95. * @since 3.4
  96. */
  97. protected InputStream ins;
  98. /**
  99. * Writer to output to, typically this is standard output.
  100. *
  101. * @since 2.2
  102. */
  103. protected ThrowingPrintWriter outw;
  104. /**
  105. * Stream to output to, typically this is standard output.
  106. *
  107. * @since 2.2
  108. */
  109. protected OutputStream outs;
  110. /**
  111. * Error writer, typically this is standard error.
  112. *
  113. * @since 3.4
  114. */
  115. protected ThrowingPrintWriter errw;
  116. /**
  117. * Error output stream, typically this is standard error.
  118. *
  119. * @since 3.4
  120. */
  121. protected OutputStream errs;
  122. /** Git repository the command was invoked within. */
  123. protected Repository db;
  124. /** Directory supplied via --git-dir command line option. */
  125. protected String gitdir;
  126. /** RevWalk used during command line parsing, if it was required. */
  127. protected RevWalk argWalk;
  128. final void setCommandName(String name) {
  129. commandName = name;
  130. }
  131. /**
  132. * If this command requires a repository.
  133. *
  134. * @return true if {@link #db}/{@link #getRepository()} is required
  135. */
  136. protected boolean requiresRepository() {
  137. return true;
  138. }
  139. /**
  140. * Initializes the command to work with a repository, including setting the
  141. * output and error streams.
  142. *
  143. * @param repository
  144. * the opened repository that the command should work on.
  145. * @param gitDir
  146. * value of the {@code --git-dir} command line option, if
  147. * {@code repository} is null.
  148. * @param input
  149. * input stream from which input will be read
  150. * @param output
  151. * output stream to which output will be written
  152. * @param error
  153. * error stream to which errors will be written
  154. * @since 4.9
  155. */
  156. public void initRaw(final Repository repository, final String gitDir,
  157. InputStream input, OutputStream output, OutputStream error) {
  158. this.ins = input;
  159. this.outs = output;
  160. this.errs = error;
  161. init(repository, gitDir);
  162. }
  163. /**
  164. * Get the log output encoding specified in the repository's
  165. * {@code i18n.logOutputEncoding} configuration.
  166. *
  167. * @param repository
  168. * the repository.
  169. * @return Charset corresponding to {@code i18n.logOutputEncoding}, or
  170. * {@code UTF_8}.
  171. */
  172. private Charset getLogOutputEncodingCharset(Repository repository) {
  173. if (repository != null) {
  174. String logOutputEncoding = repository.getConfig().getString(
  175. CONFIG_SECTION_I18N, null, CONFIG_KEY_LOG_OUTPUT_ENCODING);
  176. if (logOutputEncoding != null) {
  177. try {
  178. return Charset.forName(logOutputEncoding);
  179. } catch (IllegalArgumentException e) {
  180. throw die(CLIText.get().cannotCreateOutputStream, e);
  181. }
  182. }
  183. }
  184. return UTF_8;
  185. }
  186. /**
  187. * Initialize the command to work with a repository.
  188. *
  189. * @param repository
  190. * the opened repository that the command should work on.
  191. * @param gitDir
  192. * value of the {@code --git-dir} command line option, if
  193. * {@code repository} is null.
  194. */
  195. protected void init(Repository repository, String gitDir) {
  196. Charset charset = getLogOutputEncodingCharset(repository);
  197. if (ins == null)
  198. ins = new FileInputStream(FileDescriptor.in);
  199. if (outs == null)
  200. outs = new FileOutputStream(FileDescriptor.out);
  201. if (errs == null)
  202. errs = new FileOutputStream(FileDescriptor.err);
  203. outw = new ThrowingPrintWriter(new BufferedWriter(
  204. new OutputStreamWriter(outs, charset)));
  205. errw = new ThrowingPrintWriter(new BufferedWriter(
  206. new OutputStreamWriter(errs, charset)));
  207. if (repository != null && repository.getDirectory() != null) {
  208. db = repository;
  209. gitdir = repository.getDirectory().getAbsolutePath();
  210. } else {
  211. db = repository;
  212. gitdir = gitDir;
  213. }
  214. }
  215. /**
  216. * Parse arguments and run this command.
  217. *
  218. * @param args
  219. * command line arguments passed after the command name.
  220. * @throws java.lang.Exception
  221. * an error occurred while processing the command. The main
  222. * framework will catch the exception and print a message on
  223. * standard error.
  224. */
  225. public final void execute(String[] args) throws Exception {
  226. parseArguments(args);
  227. switch (sshDriver) {
  228. case APACHE: {
  229. SshdSessionFactory factory = new SshdSessionFactory(
  230. new JGitKeyCache(), new DefaultProxyDataFactory());
  231. Runtime.getRuntime()
  232. .addShutdownHook(new Thread(() -> factory.close()));
  233. SshSessionFactory.setInstance(factory);
  234. break;
  235. }
  236. case JSCH:
  237. default:
  238. SshSessionFactory.setInstance(null);
  239. break;
  240. }
  241. run();
  242. }
  243. /**
  244. * Parses the command line arguments prior to running.
  245. * <p>
  246. * This method should only be invoked by {@link #execute(String[])}, prior
  247. * to calling {@link #run()}. The default implementation parses all
  248. * arguments into this object's instance fields.
  249. *
  250. * @param args
  251. * the arguments supplied on the command line, if any.
  252. * @throws java.io.IOException
  253. */
  254. protected void parseArguments(String[] args) throws IOException {
  255. final CmdLineParser clp = new CmdLineParser(this);
  256. help = containsHelp(args);
  257. try {
  258. clp.parseArgument(args);
  259. } catch (CmdLineException err) {
  260. this.errw.println(CLIText.fatalError(err.getMessage()));
  261. if (help) {
  262. printUsage("", clp); //$NON-NLS-1$
  263. }
  264. throw die(true, err);
  265. }
  266. if (help) {
  267. printUsage("", clp); //$NON-NLS-1$
  268. throw new TerminatedByHelpException();
  269. }
  270. argWalk = clp.getRevWalkGently();
  271. }
  272. /**
  273. * Print the usage line
  274. *
  275. * @param clp
  276. * a {@link org.eclipse.jgit.pgm.opt.CmdLineParser} object.
  277. * @throws java.io.IOException
  278. */
  279. public void printUsageAndExit(CmdLineParser clp) throws IOException {
  280. printUsageAndExit("", clp); //$NON-NLS-1$
  281. }
  282. /**
  283. * Print an error message and the usage line
  284. *
  285. * @param message
  286. * a {@link java.lang.String} object.
  287. * @param clp
  288. * a {@link org.eclipse.jgit.pgm.opt.CmdLineParser} object.
  289. * @throws java.io.IOException
  290. */
  291. public void printUsageAndExit(String message, CmdLineParser clp) throws IOException {
  292. printUsage(message, clp);
  293. throw die(true);
  294. }
  295. /**
  296. * Print usage help text.
  297. *
  298. * @param message
  299. * non null
  300. * @param clp
  301. * parser used to print options
  302. * @throws java.io.IOException
  303. * @since 4.2
  304. */
  305. protected void printUsage(String message, CmdLineParser clp)
  306. throws IOException {
  307. errw.println(message);
  308. errw.print("jgit "); //$NON-NLS-1$
  309. errw.print(commandName);
  310. clp.printSingleLineUsage(errw, getResourceBundle());
  311. errw.println();
  312. errw.println();
  313. clp.printUsage(errw, getResourceBundle());
  314. errw.println();
  315. errw.flush();
  316. }
  317. /**
  318. * Get error writer
  319. *
  320. * @return error writer, typically this is standard error.
  321. * @since 4.2
  322. */
  323. public ThrowingPrintWriter getErrorWriter() {
  324. return errw;
  325. }
  326. /**
  327. * Get output writer
  328. *
  329. * @return output writer, typically this is standard output.
  330. * @since 4.9
  331. */
  332. public ThrowingPrintWriter getOutputWriter() {
  333. return outw;
  334. }
  335. /**
  336. * Get resource bundle with localized texts
  337. *
  338. * @return the resource bundle that will be passed to args4j for purpose of
  339. * string localization
  340. */
  341. protected ResourceBundle getResourceBundle() {
  342. return CLIText.get().resourceBundle();
  343. }
  344. /**
  345. * Perform the actions of this command.
  346. * <p>
  347. * This method should only be invoked by {@link #execute(String[])}.
  348. *
  349. * @throws java.lang.Exception
  350. * an error occurred while processing the command. The main
  351. * framework will catch the exception and print a message on
  352. * standard error.
  353. */
  354. protected abstract void run() throws Exception;
  355. /**
  356. * Get the repository
  357. *
  358. * @return the repository this command accesses.
  359. */
  360. public Repository getRepository() {
  361. return db;
  362. }
  363. ObjectId resolve(String s) throws IOException {
  364. final ObjectId r = db.resolve(s);
  365. if (r == null)
  366. throw die(MessageFormat.format(CLIText.get().notARevision, s));
  367. return r;
  368. }
  369. /**
  370. * Exit the command with an error message
  371. *
  372. * @param why
  373. * textual explanation
  374. * @return a runtime exception the caller is expected to throw
  375. */
  376. protected static Die die(String why) {
  377. return new Die(why);
  378. }
  379. /**
  380. * Exit the command with an error message and an exception
  381. *
  382. * @param why
  383. * textual explanation
  384. * @param cause
  385. * why the command has failed.
  386. * @return a runtime exception the caller is expected to throw
  387. */
  388. protected static Die die(String why, Throwable cause) {
  389. return new Die(why, cause);
  390. }
  391. /**
  392. * Exit the command
  393. *
  394. * @param aborted
  395. * boolean indicating that the execution has been aborted before
  396. * running
  397. * @return a runtime exception the caller is expected to throw
  398. * @since 3.4
  399. */
  400. protected static Die die(boolean aborted) {
  401. return new Die(aborted);
  402. }
  403. /**
  404. * Exit the command
  405. *
  406. * @param aborted
  407. * boolean indicating that the execution has been aborted before
  408. * running
  409. * @param cause
  410. * why the command has failed.
  411. * @return a runtime exception the caller is expected to throw
  412. * @since 4.2
  413. */
  414. protected static Die die(boolean aborted, Throwable cause) {
  415. return new Die(aborted, cause);
  416. }
  417. String abbreviateRef(String dst, boolean abbreviateRemote) {
  418. if (dst.startsWith(R_HEADS))
  419. dst = dst.substring(R_HEADS.length());
  420. else if (dst.startsWith(R_TAGS))
  421. dst = dst.substring(R_TAGS.length());
  422. else if (abbreviateRemote && dst.startsWith(R_REMOTES))
  423. dst = dst.substring(R_REMOTES.length());
  424. return dst;
  425. }
  426. /**
  427. * Check if the arguments contain a help option
  428. *
  429. * @param args
  430. * non null
  431. * @return true if the given array contains help option
  432. * @since 4.2
  433. */
  434. public static boolean containsHelp(String[] args) {
  435. for (String str : args) {
  436. if (str.equals("-h") || str.equals("--help")) { //$NON-NLS-1$ //$NON-NLS-2$
  437. return true;
  438. }
  439. }
  440. return false;
  441. }
  442. /**
  443. * Exception thrown by {@link TextBuiltin} if it proceeds 'help' option
  444. *
  445. * @since 4.2
  446. */
  447. public static class TerminatedByHelpException extends Die {
  448. private static final long serialVersionUID = 1L;
  449. /**
  450. * Default constructor
  451. */
  452. public TerminatedByHelpException() {
  453. super(true);
  454. }
  455. }
  456. }