Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

FS.java 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.util;
  44. import java.io.BufferedReader;
  45. import java.io.BufferedWriter;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.io.InputStreamReader;
  50. import java.io.OutputStream;
  51. import java.io.OutputStreamWriter;
  52. import java.io.PrintStream;
  53. import java.io.PrintWriter;
  54. import java.security.AccessController;
  55. import java.security.PrivilegedAction;
  56. import java.text.MessageFormat;
  57. import java.util.Arrays;
  58. import java.util.concurrent.Callable;
  59. import java.util.concurrent.ExecutorService;
  60. import java.util.concurrent.Executors;
  61. import java.util.concurrent.TimeUnit;
  62. import java.util.concurrent.atomic.AtomicBoolean;
  63. import org.eclipse.jgit.api.errors.JGitInternalException;
  64. import org.eclipse.jgit.errors.SymlinksNotSupportedException;
  65. import org.eclipse.jgit.internal.JGitText;
  66. import org.eclipse.jgit.lib.Constants;
  67. import org.eclipse.jgit.lib.Repository;
  68. import org.eclipse.jgit.util.ProcessResult.Status;
  69. import org.slf4j.Logger;
  70. import org.slf4j.LoggerFactory;
  71. /** Abstraction to support various file system operations not in Java. */
  72. public abstract class FS {
  73. /**
  74. * This class creates FS instances. It will be overridden by a Java7 variant
  75. * if such can be detected in {@link #detect(Boolean)}.
  76. *
  77. * @since 3.0
  78. */
  79. public static class FSFactory {
  80. /**
  81. * Constructor
  82. */
  83. protected FSFactory() {
  84. // empty
  85. }
  86. /**
  87. * Detect the file system
  88. *
  89. * @param cygwinUsed
  90. * @return FS instance
  91. */
  92. public FS detect(Boolean cygwinUsed) {
  93. if (SystemReader.getInstance().isWindows()) {
  94. if (cygwinUsed == null)
  95. cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
  96. if (cygwinUsed.booleanValue())
  97. return new FS_Win32_Cygwin();
  98. else
  99. return new FS_Win32();
  100. } else if (FS_POSIX_Java6.hasExecute())
  101. return new FS_POSIX_Java6();
  102. else
  103. return new FS_POSIX_Java5();
  104. }
  105. }
  106. private final static Logger LOG = LoggerFactory.getLogger(FS.class);
  107. /** The auto-detected implementation selected for this operating system and JRE. */
  108. public static final FS DETECTED = detect();
  109. private static FSFactory factory;
  110. /**
  111. * Auto-detect the appropriate file system abstraction.
  112. *
  113. * @return detected file system abstraction
  114. */
  115. public static FS detect() {
  116. return detect(null);
  117. }
  118. /**
  119. * Auto-detect the appropriate file system abstraction, taking into account
  120. * the presence of a Cygwin installation on the system. Using jgit in
  121. * combination with Cygwin requires a more elaborate (and possibly slower)
  122. * resolution of file system paths.
  123. *
  124. * @param cygwinUsed
  125. * <ul>
  126. * <li><code>Boolean.TRUE</code> to assume that Cygwin is used in
  127. * combination with jgit</li>
  128. * <li><code>Boolean.FALSE</code> to assume that Cygwin is
  129. * <b>not</b> used with jgit</li>
  130. * <li><code>null</code> to auto-detect whether a Cygwin
  131. * installation is present on the system and in this case assume
  132. * that Cygwin is used</li>
  133. * </ul>
  134. *
  135. * Note: this parameter is only relevant on Windows.
  136. *
  137. * @return detected file system abstraction
  138. */
  139. public static FS detect(Boolean cygwinUsed) {
  140. if (factory == null) {
  141. try {
  142. Class<?> activatorClass = Class
  143. .forName("org.eclipse.jgit.util.Java7FSFactory"); //$NON-NLS-1$
  144. // found Java7
  145. factory = (FSFactory) activatorClass.newInstance();
  146. } catch (ClassNotFoundException e) {
  147. // Java7 module not found
  148. // Silently ignore failure to find Java7 FS factory
  149. factory = new FS.FSFactory();
  150. } catch (UnsupportedClassVersionError e) {
  151. factory = new FS.FSFactory();
  152. } catch (InstantiationException e) {
  153. factory = new FS.FSFactory();
  154. } catch (IllegalAccessException e) {
  155. factory = new FS.FSFactory();
  156. }
  157. }
  158. return factory.detect(cygwinUsed);
  159. }
  160. private volatile Holder<File> userHome;
  161. private volatile Holder<File> gitPrefix;
  162. /**
  163. * Constructs a file system abstraction.
  164. */
  165. protected FS() {
  166. // Do nothing by default.
  167. }
  168. /**
  169. * Initialize this FS using another's current settings.
  170. *
  171. * @param src
  172. * the source FS to copy from.
  173. */
  174. protected FS(FS src) {
  175. userHome = src.userHome;
  176. gitPrefix = src.gitPrefix;
  177. }
  178. /** @return a new instance of the same type of FS. */
  179. public abstract FS newInstance();
  180. /**
  181. * Does this operating system and JRE support the execute flag on files?
  182. *
  183. * @return true if this implementation can provide reasonably accurate
  184. * executable bit information; false otherwise.
  185. */
  186. public abstract boolean supportsExecute();
  187. /**
  188. * Does this operating system and JRE supports symbolic links. The
  189. * capability to handle symbolic links is detected at runtime.
  190. *
  191. * @return true if symbolic links may be used
  192. * @since 3.0
  193. */
  194. public boolean supportsSymlinks() {
  195. return false;
  196. }
  197. /**
  198. * Is this file system case sensitive
  199. *
  200. * @return true if this implementation is case sensitive
  201. */
  202. public abstract boolean isCaseSensitive();
  203. /**
  204. * Determine if the file is executable (or not).
  205. * <p>
  206. * Not all platforms and JREs support executable flags on files. If the
  207. * feature is unsupported this method will always return false.
  208. * <p>
  209. * <em>If the platform supports symbolic links and <code>f</code> is a symbolic link
  210. * this method returns false, rather than the state of the executable flags
  211. * on the target file.</em>
  212. *
  213. * @param f
  214. * abstract path to test.
  215. * @return true if the file is believed to be executable by the user.
  216. */
  217. public abstract boolean canExecute(File f);
  218. /**
  219. * Set a file to be executable by the user.
  220. * <p>
  221. * Not all platforms and JREs support executable flags on files. If the
  222. * feature is unsupported this method will always return false and no
  223. * changes will be made to the file specified.
  224. *
  225. * @param f
  226. * path to modify the executable status of.
  227. * @param canExec
  228. * true to enable execution; false to disable it.
  229. * @return true if the change succeeded; false otherwise.
  230. */
  231. public abstract boolean setExecute(File f, boolean canExec);
  232. /**
  233. * Get the last modified time of a file system object. If the OS/JRE support
  234. * symbolic links, the modification time of the link is returned, rather
  235. * than that of the link target.
  236. *
  237. * @param f
  238. * @return last modified time of f
  239. * @throws IOException
  240. * @since 3.0
  241. */
  242. public long lastModified(File f) throws IOException {
  243. return f.lastModified();
  244. }
  245. /**
  246. * Set the last modified time of a file system object. If the OS/JRE support
  247. * symbolic links, the link is modified, not the target,
  248. *
  249. * @param f
  250. * @param time
  251. * @throws IOException
  252. * @since 3.0
  253. */
  254. public void setLastModified(File f, long time) throws IOException {
  255. f.setLastModified(time);
  256. }
  257. /**
  258. * Get the length of a file or link, If the OS/JRE supports symbolic links
  259. * it's the length of the link, else the length of the target.
  260. *
  261. * @param path
  262. * @return length of a file
  263. * @throws IOException
  264. * @since 3.0
  265. */
  266. public long length(File path) throws IOException {
  267. return path.length();
  268. }
  269. /**
  270. * Delete a file. Throws an exception if delete fails.
  271. *
  272. * @param f
  273. * @throws IOException
  274. * this may be a Java7 subclass with detailed information
  275. * @since 3.3
  276. */
  277. public void delete(File f) throws IOException {
  278. if (!f.delete())
  279. throw new IOException(MessageFormat.format(
  280. JGitText.get().deleteFileFailed, f.getAbsolutePath()));
  281. }
  282. /**
  283. * Resolve this file to its actual path name that the JRE can use.
  284. * <p>
  285. * This method can be relatively expensive. Computing a translation may
  286. * require forking an external process per path name translated. Callers
  287. * should try to minimize the number of translations necessary by caching
  288. * the results.
  289. * <p>
  290. * Not all platforms and JREs require path name translation. Currently only
  291. * Cygwin on Win32 require translation for Cygwin based paths.
  292. *
  293. * @param dir
  294. * directory relative to which the path name is.
  295. * @param name
  296. * path name to translate.
  297. * @return the translated path. <code>new File(dir,name)</code> if this
  298. * platform does not require path name translation.
  299. */
  300. public File resolve(final File dir, final String name) {
  301. final File abspn = new File(name);
  302. if (abspn.isAbsolute())
  303. return abspn;
  304. return new File(dir, name);
  305. }
  306. /**
  307. * Determine the user's home directory (location where preferences are).
  308. * <p>
  309. * This method can be expensive on the first invocation if path name
  310. * translation is required. Subsequent invocations return a cached result.
  311. * <p>
  312. * Not all platforms and JREs require path name translation. Currently only
  313. * Cygwin on Win32 requires translation of the Cygwin HOME directory.
  314. *
  315. * @return the user's home directory; null if the user does not have one.
  316. */
  317. public File userHome() {
  318. Holder<File> p = userHome;
  319. if (p == null) {
  320. p = new Holder<File>(userHomeImpl());
  321. userHome = p;
  322. }
  323. return p.value;
  324. }
  325. /**
  326. * Set the user's home directory location.
  327. *
  328. * @param path
  329. * the location of the user's preferences; null if there is no
  330. * home directory for the current user.
  331. * @return {@code this}.
  332. */
  333. public FS setUserHome(File path) {
  334. userHome = new Holder<File>(path);
  335. return this;
  336. }
  337. /**
  338. * Does this file system have problems with atomic renames?
  339. *
  340. * @return true if the caller should retry a failed rename of a lock file.
  341. */
  342. public abstract boolean retryFailedLockFileCommit();
  343. /**
  344. * Determine the user's home directory (location where preferences are).
  345. *
  346. * @return the user's home directory; null if the user does not have one.
  347. */
  348. protected File userHomeImpl() {
  349. final String home = AccessController
  350. .doPrivileged(new PrivilegedAction<String>() {
  351. public String run() {
  352. return System.getProperty("user.home"); //$NON-NLS-1$
  353. }
  354. });
  355. if (home == null || home.length() == 0)
  356. return null;
  357. return new File(home).getAbsoluteFile();
  358. }
  359. /**
  360. * Searches the given path to see if it contains one of the given files.
  361. * Returns the first it finds. Returns null if not found or if path is null.
  362. *
  363. * @param path
  364. * List of paths to search separated by File.pathSeparator
  365. * @param lookFor
  366. * Files to search for in the given path
  367. * @return the first match found, or null
  368. * @since 3.0
  369. **/
  370. protected static File searchPath(final String path, final String... lookFor) {
  371. if (path == null)
  372. return null;
  373. for (final String p : path.split(File.pathSeparator)) {
  374. for (String command : lookFor) {
  375. final File e = new File(p, command);
  376. if (e.isFile())
  377. return e.getAbsoluteFile();
  378. }
  379. }
  380. return null;
  381. }
  382. /**
  383. * Execute a command and return a single line of output as a String
  384. *
  385. * @param dir
  386. * Working directory for the command
  387. * @param command
  388. * as component array
  389. * @param encoding
  390. * @return the one-line output of the command
  391. */
  392. protected static String readPipe(File dir, String[] command, String encoding) {
  393. final boolean debug = LOG.isDebugEnabled();
  394. try {
  395. if (debug) {
  396. LOG.debug("readpipe " + Arrays.asList(command) + "," //$NON-NLS-1$ //$NON-NLS-2$
  397. + dir);
  398. }
  399. final Process p = Runtime.getRuntime().exec(command, null, dir);
  400. final BufferedReader lineRead = new BufferedReader(
  401. new InputStreamReader(p.getInputStream(), encoding));
  402. p.getOutputStream().close();
  403. final AtomicBoolean gooblerFail = new AtomicBoolean(false);
  404. Thread gobbler = new Thread() {
  405. public void run() {
  406. InputStream is = p.getErrorStream();
  407. try {
  408. int ch;
  409. if (debug)
  410. while ((ch = is.read()) != -1)
  411. System.err.print((char) ch);
  412. else
  413. while (is.read() != -1) {
  414. // ignore
  415. }
  416. } catch (IOException e) {
  417. // Just print on stderr for debugging
  418. if (debug)
  419. e.printStackTrace(System.err);
  420. gooblerFail.set(true);
  421. }
  422. try {
  423. is.close();
  424. } catch (IOException e) {
  425. // Just print on stderr for debugging
  426. if (debug) {
  427. LOG.debug("Caught exception in gobbler thread", e); //$NON-NLS-1$
  428. }
  429. gooblerFail.set(true);
  430. }
  431. }
  432. };
  433. gobbler.start();
  434. String r = null;
  435. try {
  436. r = lineRead.readLine();
  437. if (debug) {
  438. LOG.debug("readpipe may return '" + r + "'"); //$NON-NLS-1$ //$NON-NLS-2$
  439. LOG.debug("(ignoring remaing output:"); //$NON-NLS-1$
  440. }
  441. String l;
  442. while ((l = lineRead.readLine()) != null) {
  443. if (debug) {
  444. LOG.debug(l);
  445. }
  446. }
  447. } finally {
  448. p.getErrorStream().close();
  449. lineRead.close();
  450. }
  451. for (;;) {
  452. try {
  453. int rc = p.waitFor();
  454. gobbler.join();
  455. if (rc == 0 && r != null && r.length() > 0
  456. && !gooblerFail.get())
  457. return r;
  458. if (debug) {
  459. LOG.debug("readpipe rc=" + rc); //$NON-NLS-1$
  460. }
  461. break;
  462. } catch (InterruptedException ie) {
  463. // Stop bothering me, I have a zombie to reap.
  464. }
  465. }
  466. } catch (IOException e) {
  467. LOG.error("Caught exception in FS.readPipe()", e); //$NON-NLS-1$
  468. }
  469. if (debug) {
  470. LOG.debug("readpipe returns null"); //$NON-NLS-1$
  471. }
  472. return null;
  473. }
  474. /** @return the $prefix directory C Git would use. */
  475. public File gitPrefix() {
  476. Holder<File> p = gitPrefix;
  477. if (p == null) {
  478. String overrideGitPrefix = SystemReader.getInstance().getProperty(
  479. "jgit.gitprefix"); //$NON-NLS-1$
  480. if (overrideGitPrefix != null)
  481. p = new Holder<File>(new File(overrideGitPrefix));
  482. else
  483. p = new Holder<File>(discoverGitPrefix());
  484. gitPrefix = p;
  485. }
  486. return p.value;
  487. }
  488. /** @return the $prefix directory C Git would use. */
  489. protected abstract File discoverGitPrefix();
  490. /**
  491. * Set the $prefix directory C Git uses.
  492. *
  493. * @param path
  494. * the directory. Null if C Git is not installed.
  495. * @return {@code this}
  496. */
  497. public FS setGitPrefix(File path) {
  498. gitPrefix = new Holder<File>(path);
  499. return this;
  500. }
  501. /**
  502. * Check if a file is a symbolic link and read it
  503. *
  504. * @param path
  505. * @return target of link or null
  506. * @throws IOException
  507. * @since 3.0
  508. */
  509. public String readSymLink(File path) throws IOException {
  510. throw new SymlinksNotSupportedException(
  511. JGitText.get().errorSymlinksNotSupported);
  512. }
  513. /**
  514. * @param path
  515. * @return true if the path is a symbolic link (and we support these)
  516. * @throws IOException
  517. * @since 3.0
  518. */
  519. public boolean isSymLink(File path) throws IOException {
  520. return false;
  521. }
  522. /**
  523. * Tests if the path exists, in case of a symbolic link, true even if the
  524. * target does not exist
  525. *
  526. * @param path
  527. * @return true if path exists
  528. * @since 3.0
  529. */
  530. public boolean exists(File path) {
  531. return path.exists();
  532. }
  533. /**
  534. * Check if path is a directory. If the OS/JRE supports symbolic links and
  535. * path is a symbolic link to a directory, this method returns false.
  536. *
  537. * @param path
  538. * @return true if file is a directory,
  539. * @since 3.0
  540. */
  541. public boolean isDirectory(File path) {
  542. return path.isDirectory();
  543. }
  544. /**
  545. * Examine if path represents a regular file. If the OS/JRE supports
  546. * symbolic links the test returns false if path represents a symbolic link.
  547. *
  548. * @param path
  549. * @return true if path represents a regular file
  550. * @since 3.0
  551. */
  552. public boolean isFile(File path) {
  553. return path.isFile();
  554. }
  555. /**
  556. * @param path
  557. * @return true if path is hidden, either starts with . on unix or has the
  558. * hidden attribute in windows
  559. * @throws IOException
  560. * @since 3.0
  561. */
  562. public boolean isHidden(File path) throws IOException {
  563. return path.isHidden();
  564. }
  565. /**
  566. * Set the hidden attribute for file whose name starts with a period.
  567. *
  568. * @param path
  569. * @param hidden
  570. * @throws IOException
  571. * @since 3.0
  572. */
  573. public void setHidden(File path, boolean hidden) throws IOException {
  574. if (!path.getName().startsWith(".")) //$NON-NLS-1$
  575. throw new IllegalArgumentException(
  576. "Hiding only allowed for names that start with a period");
  577. }
  578. /**
  579. * Create a symbolic link
  580. *
  581. * @param path
  582. * @param target
  583. * @throws IOException
  584. * @since 3.0
  585. */
  586. public void createSymLink(File path, String target) throws IOException {
  587. throw new SymlinksNotSupportedException(
  588. JGitText.get().errorSymlinksNotSupported);
  589. }
  590. /**
  591. * See {@link FileUtils#relativize(String, String)}.
  592. *
  593. * @param base
  594. * The path against which <code>other</code> should be
  595. * relativized.
  596. * @param other
  597. * The path that will be made relative to <code>base</code>.
  598. * @return A relative path that, when resolved against <code>base</code>,
  599. * will yield the original <code>other</code>.
  600. * @see FileUtils#relativize(String, String)
  601. * @since 3.7
  602. */
  603. public String relativize(String base, String other) {
  604. return FileUtils.relativize(base, other);
  605. }
  606. /**
  607. * Checks whether the given hook is defined for the given repository, then
  608. * runs it with the given arguments.
  609. * <p>
  610. * The hook's standard output and error streams will be redirected to
  611. * <code>System.out</code> and <code>System.err</code> respectively. The
  612. * hook will have no stdin.
  613. * </p>
  614. *
  615. * @param repository
  616. * The repository for which a hook should be run.
  617. * @param hook
  618. * The hook to be executed.
  619. * @param args
  620. * Arguments to pass to this hook. Cannot be <code>null</code>,
  621. * but can be an empty array.
  622. * @return The ProcessResult describing this hook's execution.
  623. * @throws JGitInternalException
  624. * if we fail to run the hook somehow. Causes may include an
  625. * interrupted process or I/O errors.
  626. * @since 3.7
  627. */
  628. public ProcessResult runIfPresent(Repository repository, final Hook hook,
  629. String[] args) throws JGitInternalException {
  630. return runIfPresent(repository, hook, args, System.out, System.err,
  631. null);
  632. }
  633. /**
  634. * Checks whether the given hook is defined for the given repository, then
  635. * runs it with the given arguments.
  636. *
  637. * @param repository
  638. * The repository for which a hook should be run.
  639. * @param hook
  640. * The hook to be executed.
  641. * @param args
  642. * Arguments to pass to this hook. Cannot be <code>null</code>,
  643. * but can be an empty array.
  644. * @param outRedirect
  645. * A print stream on which to redirect the hook's stdout. Can be
  646. * <code>null</code>, in which case the hook's standard output
  647. * will be lost.
  648. * @param errRedirect
  649. * A print stream on which to redirect the hook's stderr. Can be
  650. * <code>null</code>, in which case the hook's standard error
  651. * will be lost.
  652. * @param stdinArgs
  653. * A string to pass on to the standard input of the hook. May be
  654. * <code>null</code>.
  655. * @return The ProcessResult describing this hook's execution.
  656. * @throws JGitInternalException
  657. * if we fail to run the hook somehow. Causes may include an
  658. * interrupted process or I/O errors.
  659. * @since 3.7
  660. */
  661. public ProcessResult runIfPresent(Repository repository, final Hook hook,
  662. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  663. String stdinArgs) throws JGitInternalException {
  664. return new ProcessResult(Status.NOT_SUPPORTED);
  665. }
  666. /**
  667. * See
  668. * {@link #runIfPresent(Repository, Hook, String[], PrintStream, PrintStream, String)}
  669. * . Should only be called by FS supporting shell scripts execution.
  670. *
  671. * @param repository
  672. * The repository for which a hook should be run.
  673. * @param hook
  674. * The hook to be executed.
  675. * @param args
  676. * Arguments to pass to this hook. Cannot be <code>null</code>,
  677. * but can be an empty array.
  678. * @param outRedirect
  679. * A print stream on which to redirect the hook's stdout. Can be
  680. * <code>null</code>, in which case the hook's standard output
  681. * will be lost.
  682. * @param errRedirect
  683. * A print stream on which to redirect the hook's stderr. Can be
  684. * <code>null</code>, in which case the hook's standard error
  685. * will be lost.
  686. * @param stdinArgs
  687. * A string to pass on to the standard input of the hook. May be
  688. * <code>null</code>.
  689. * @return The ProcessResult describing this hook's execution.
  690. * @throws JGitInternalException
  691. * if we fail to run the hook somehow. Causes may include an
  692. * interrupted process or I/O errors.
  693. * @since 3.7
  694. */
  695. protected ProcessResult internalRunIfPresent(Repository repository,
  696. final Hook hook, String[] args, PrintStream outRedirect,
  697. PrintStream errRedirect, String stdinArgs)
  698. throws JGitInternalException {
  699. final File hookFile = findHook(repository, hook);
  700. if (hookFile == null)
  701. return new ProcessResult(Status.NOT_PRESENT);
  702. final String hookPath = hookFile.getAbsolutePath();
  703. final File runDirectory;
  704. if (repository.isBare())
  705. runDirectory = repository.getDirectory();
  706. else
  707. runDirectory = repository.getWorkTree();
  708. final String cmd = relativize(runDirectory.getAbsolutePath(),
  709. hookPath);
  710. ProcessBuilder hookProcess = runInShell(cmd, args);
  711. hookProcess.directory(runDirectory);
  712. try {
  713. return new ProcessResult(runProcess(hookProcess, outRedirect,
  714. errRedirect, stdinArgs), Status.OK);
  715. } catch (IOException e) {
  716. throw new JGitInternalException(MessageFormat.format(
  717. JGitText.get().exceptionCaughtDuringExecutionOfHook,
  718. hook.getName()), e);
  719. } catch (InterruptedException e) {
  720. throw new JGitInternalException(MessageFormat.format(
  721. JGitText.get().exceptionHookExecutionInterrupted,
  722. hook.getName()), e);
  723. }
  724. }
  725. /**
  726. * Tries to find a hook matching the given one in the given repository.
  727. *
  728. * @param repository
  729. * The repository within which to find a hook.
  730. * @param hook
  731. * The hook we're trying to find.
  732. * @return The {@link File} containing this particular hook if it exists in
  733. * the given repository, <code>null</code> otherwise.
  734. * @since 3.7
  735. */
  736. public File findHook(Repository repository, final Hook hook) {
  737. final File hookFile = new File(new File(repository.getDirectory(),
  738. Constants.HOOKS), hook.getName());
  739. return hookFile.isFile() ? hookFile : null;
  740. }
  741. /**
  742. * Runs the given process until termination, clearing its stdout and stderr
  743. * streams on-the-fly.
  744. *
  745. * @param hookProcessBuilder
  746. * The process builder configured for this hook.
  747. * @param outRedirect
  748. * A print stream on which to redirect the hook's stdout. Can be
  749. * <code>null</code>, in which case the hook's standard output
  750. * will be lost.
  751. * @param errRedirect
  752. * A print stream on which to redirect the hook's stderr. Can be
  753. * <code>null</code>, in which case the hook's standard error
  754. * will be lost.
  755. * @param stdinArgs
  756. * A string to pass on to the standard input of the hook. Can be
  757. * <code>null</code>.
  758. * @return the exit value of this hook.
  759. * @throws IOException
  760. * if an I/O error occurs while executing this hook.
  761. * @throws InterruptedException
  762. * if the current thread is interrupted while waiting for the
  763. * process to end.
  764. * @since 3.7
  765. */
  766. protected int runProcess(ProcessBuilder hookProcessBuilder,
  767. OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
  768. throws IOException, InterruptedException {
  769. final ExecutorService executor = Executors.newFixedThreadPool(2);
  770. Process process = null;
  771. // We'll record the first I/O exception that occurs, but keep on trying
  772. // to dispose of our open streams and file handles
  773. IOException ioException = null;
  774. try {
  775. process = hookProcessBuilder.start();
  776. final Callable<Void> errorGobbler = new StreamGobbler(
  777. process.getErrorStream(), errRedirect);
  778. final Callable<Void> outputGobbler = new StreamGobbler(
  779. process.getInputStream(), outRedirect);
  780. executor.submit(errorGobbler);
  781. executor.submit(outputGobbler);
  782. if (stdinArgs != null) {
  783. final PrintWriter stdinWriter = new PrintWriter(
  784. process.getOutputStream());
  785. stdinWriter.print(stdinArgs);
  786. stdinWriter.flush();
  787. // We are done with this hook's input. Explicitly close its
  788. // stdin now to kick off any blocking read the hook might have.
  789. stdinWriter.close();
  790. }
  791. return process.waitFor();
  792. } catch (IOException e) {
  793. ioException = e;
  794. } finally {
  795. shutdownAndAwaitTermination(executor);
  796. if (process != null) {
  797. try {
  798. process.waitFor();
  799. } catch (InterruptedException e) {
  800. // Thrown by the outer try.
  801. // Swallow this one to carry on our cleanup, and clear the
  802. // interrupted flag (processes throw the exception without
  803. // clearing the flag).
  804. Thread.interrupted();
  805. }
  806. // A process doesn't clean its own resources even when destroyed
  807. // Explicitly try and close all three streams, preserving the
  808. // outer I/O exception if any.
  809. try {
  810. process.getErrorStream().close();
  811. } catch (IOException e) {
  812. ioException = ioException != null ? ioException : e;
  813. }
  814. try {
  815. process.getInputStream().close();
  816. } catch (IOException e) {
  817. ioException = ioException != null ? ioException : e;
  818. }
  819. try {
  820. process.getOutputStream().close();
  821. } catch (IOException e) {
  822. ioException = ioException != null ? ioException : e;
  823. }
  824. process.destroy();
  825. }
  826. }
  827. // We can only be here if the outer try threw an IOException.
  828. throw ioException;
  829. }
  830. /**
  831. * Shuts down an {@link ExecutorService} in two phases, first by calling
  832. * {@link ExecutorService#shutdown() shutdown} to reject incoming tasks, and
  833. * then calling {@link ExecutorService#shutdownNow() shutdownNow}, if
  834. * necessary, to cancel any lingering tasks. Returns true if the pool has
  835. * been properly shutdown, false otherwise.
  836. * <p>
  837. *
  838. * @param pool
  839. * the pool to shutdown
  840. * @return <code>true</code> if the pool has been properly shutdown,
  841. * <code>false</code> otherwise.
  842. */
  843. private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
  844. boolean hasShutdown = true;
  845. pool.shutdown(); // Disable new tasks from being submitted
  846. try {
  847. // Wait a while for existing tasks to terminate
  848. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  849. pool.shutdownNow(); // Cancel currently executing tasks
  850. // Wait a while for tasks to respond to being canceled
  851. if (!pool.awaitTermination(5, TimeUnit.SECONDS))
  852. hasShutdown = false;
  853. }
  854. } catch (InterruptedException ie) {
  855. // (Re-)Cancel if current thread also interrupted
  856. pool.shutdownNow();
  857. // Preserve interrupt status
  858. Thread.currentThread().interrupt();
  859. hasShutdown = false;
  860. }
  861. return hasShutdown;
  862. }
  863. /**
  864. * Initialize a ProcesssBuilder to run a command using the system shell.
  865. *
  866. * @param cmd
  867. * command to execute. This string should originate from the
  868. * end-user, and thus is platform specific.
  869. * @param args
  870. * arguments to pass to command. These should be protected from
  871. * shell evaluation.
  872. * @return a partially completed process builder. Caller should finish
  873. * populating directory, environment, and then start the process.
  874. */
  875. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  876. private static class Holder<V> {
  877. final V value;
  878. Holder(V value) {
  879. this.value = value;
  880. }
  881. }
  882. /**
  883. * File attributes we typically care for.
  884. *
  885. * @since 3.3
  886. */
  887. public static class Attributes {
  888. /**
  889. * @return true if this are the attributes of a directory
  890. */
  891. public boolean isDirectory() {
  892. return isDirectory;
  893. }
  894. /**
  895. * @return true if this are the attributes of an executable file
  896. */
  897. public boolean isExecutable() {
  898. return isExecutable;
  899. }
  900. /**
  901. * @return true if this are the attributes of a symbolic link
  902. */
  903. public boolean isSymbolicLink() {
  904. return isSymbolicLink;
  905. }
  906. /**
  907. * @return true if this are the attributes of a regular file
  908. */
  909. public boolean isRegularFile() {
  910. return isRegularFile;
  911. }
  912. /**
  913. * @return the time when the file was created
  914. */
  915. public long getCreationTime() {
  916. return creationTime;
  917. }
  918. /**
  919. * @return the time (milliseconds since 1970-01-01) when this object was
  920. * last modified
  921. */
  922. public long getLastModifiedTime() {
  923. return lastModifiedTime;
  924. }
  925. private boolean isDirectory;
  926. private boolean isSymbolicLink;
  927. private boolean isRegularFile;
  928. private long creationTime;
  929. private long lastModifiedTime;
  930. private boolean isExecutable;
  931. private File file;
  932. private boolean exists;
  933. /**
  934. * file length
  935. */
  936. protected long length = -1;
  937. FS fs;
  938. Attributes(FS fs, File file, boolean exists, boolean isDirectory,
  939. boolean isExecutable, boolean isSymbolicLink,
  940. boolean isRegularFile, long creationTime,
  941. long lastModifiedTime, long length) {
  942. this.fs = fs;
  943. this.file = file;
  944. this.exists = exists;
  945. this.isDirectory = isDirectory;
  946. this.isExecutable = isExecutable;
  947. this.isSymbolicLink = isSymbolicLink;
  948. this.isRegularFile = isRegularFile;
  949. this.creationTime = creationTime;
  950. this.lastModifiedTime = lastModifiedTime;
  951. this.length = length;
  952. }
  953. /**
  954. * Constructor when there are issues with reading
  955. *
  956. * @param fs
  957. * @param path
  958. */
  959. public Attributes(File path, FS fs) {
  960. this.file = path;
  961. this.fs = fs;
  962. }
  963. /**
  964. * @return length of this file object
  965. */
  966. public long getLength() {
  967. if (length == -1)
  968. return length = file.length();
  969. return length;
  970. }
  971. /**
  972. * @return the filename
  973. */
  974. public String getName() {
  975. return file.getName();
  976. }
  977. /**
  978. * @return the file the attributes apply to
  979. */
  980. public File getFile() {
  981. return file;
  982. }
  983. boolean exists() {
  984. return exists;
  985. }
  986. }
  987. /**
  988. * @param path
  989. * @return the file attributes we care for
  990. * @since 3.3
  991. */
  992. public Attributes getAttributes(File path) {
  993. boolean isDirectory = isDirectory(path);
  994. boolean isFile = !isDirectory && path.isFile();
  995. assert path.exists() == isDirectory || isFile;
  996. boolean exists = isDirectory || isFile;
  997. boolean canExecute = exists && !isDirectory && canExecute(path);
  998. boolean isSymlink = false;
  999. long lastModified = exists ? path.lastModified() : 0L;
  1000. long createTime = 0L;
  1001. return new Attributes(this, path, exists, isDirectory, canExecute,
  1002. isSymlink, isFile, createTime, lastModified, -1);
  1003. }
  1004. /**
  1005. * Normalize the unicode path to composed form.
  1006. *
  1007. * @param file
  1008. * @return NFC-format File
  1009. * @since 3.3
  1010. */
  1011. public File normalize(File file) {
  1012. return file;
  1013. }
  1014. /**
  1015. * Normalize the unicode path to composed form.
  1016. *
  1017. * @param name
  1018. * @return NFC-format string
  1019. * @since 3.3
  1020. */
  1021. public String normalize(String name) {
  1022. return name;
  1023. }
  1024. /**
  1025. * This runnable will consume an input stream's content into an output
  1026. * stream as soon as it gets available.
  1027. * <p>
  1028. * Typically used to empty processes' standard output and error, preventing
  1029. * them to choke.
  1030. * </p>
  1031. * <p>
  1032. * <b>Note</b> that a {@link StreamGobbler} will never close either of its
  1033. * streams.
  1034. * </p>
  1035. */
  1036. private static class StreamGobbler implements Callable<Void> {
  1037. private final BufferedReader reader;
  1038. private final BufferedWriter writer;
  1039. public StreamGobbler(InputStream stream, OutputStream output) {
  1040. this.reader = new BufferedReader(new InputStreamReader(stream));
  1041. if (output == null)
  1042. this.writer = null;
  1043. else
  1044. this.writer = new BufferedWriter(new OutputStreamWriter(output));
  1045. }
  1046. public Void call() throws IOException {
  1047. boolean writeFailure = false;
  1048. String line = null;
  1049. while ((line = reader.readLine()) != null) {
  1050. // Do not try to write again after a failure, but keep reading
  1051. // as long as possible to prevent the input stream from choking.
  1052. if (!writeFailure && writer != null) {
  1053. try {
  1054. writer.write(line);
  1055. writer.newLine();
  1056. writer.flush();
  1057. } catch (IOException e) {
  1058. writeFailure = true;
  1059. }
  1060. }
  1061. }
  1062. return null;
  1063. }
  1064. }
  1065. }