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.

FS.java 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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 hookName
  618. * The name of 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 4.0
  627. */
  628. public ProcessResult runHookIfPresent(Repository repository,
  629. final String hookName,
  630. String[] args) throws JGitInternalException {
  631. return runHookIfPresent(repository, hookName, args, System.out, System.err,
  632. null);
  633. }
  634. /**
  635. * Checks whether the given hook is defined for the given repository, then
  636. * runs it with the given arguments.
  637. *
  638. * @param repository
  639. * The repository for which a hook should be run.
  640. * @param hookName
  641. * The name of the hook to be executed.
  642. * @param args
  643. * Arguments to pass to this hook. Cannot be <code>null</code>,
  644. * but can be an empty array.
  645. * @param outRedirect
  646. * A print stream on which to redirect the hook's stdout. Can be
  647. * <code>null</code>, in which case the hook's standard output
  648. * will be lost.
  649. * @param errRedirect
  650. * A print stream on which to redirect the hook's stderr. Can be
  651. * <code>null</code>, in which case the hook's standard error
  652. * will be lost.
  653. * @param stdinArgs
  654. * A string to pass on to the standard input of the hook. May be
  655. * <code>null</code>.
  656. * @return The ProcessResult describing this hook's execution.
  657. * @throws JGitInternalException
  658. * if we fail to run the hook somehow. Causes may include an
  659. * interrupted process or I/O errors.
  660. * @since 4.0
  661. */
  662. public ProcessResult runHookIfPresent(Repository repository,
  663. final String hookName,
  664. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  665. String stdinArgs) throws JGitInternalException {
  666. return new ProcessResult(Status.NOT_SUPPORTED);
  667. }
  668. /**
  669. * See
  670. * {@link #runHookIfPresent(Repository, String, String[], PrintStream, PrintStream, String)}
  671. * . Should only be called by FS supporting shell scripts execution.
  672. *
  673. * @param repository
  674. * The repository for which a hook should be run.
  675. * @param hookName
  676. * The name of the hook to be executed.
  677. * @param args
  678. * Arguments to pass to this hook. Cannot be <code>null</code>,
  679. * but can be an empty array.
  680. * @param outRedirect
  681. * A print stream on which to redirect the hook's stdout. Can be
  682. * <code>null</code>, in which case the hook's standard output
  683. * will be lost.
  684. * @param errRedirect
  685. * A print stream on which to redirect the hook's stderr. Can be
  686. * <code>null</code>, in which case the hook's standard error
  687. * will be lost.
  688. * @param stdinArgs
  689. * A string to pass on to the standard input of the hook. May be
  690. * <code>null</code>.
  691. * @return The ProcessResult describing this hook's execution.
  692. * @throws JGitInternalException
  693. * if we fail to run the hook somehow. Causes may include an
  694. * interrupted process or I/O errors.
  695. * @since 4.0
  696. */
  697. protected ProcessResult internalRunHookIfPresent(Repository repository,
  698. final String hookName, String[] args, PrintStream outRedirect,
  699. PrintStream errRedirect, String stdinArgs)
  700. throws JGitInternalException {
  701. final File hookFile = findHook(repository, hookName);
  702. if (hookFile == null)
  703. return new ProcessResult(Status.NOT_PRESENT);
  704. final String hookPath = hookFile.getAbsolutePath();
  705. final File runDirectory;
  706. if (repository.isBare())
  707. runDirectory = repository.getDirectory();
  708. else
  709. runDirectory = repository.getWorkTree();
  710. final String cmd = relativize(runDirectory.getAbsolutePath(),
  711. hookPath);
  712. ProcessBuilder hookProcess = runInShell(cmd, args);
  713. hookProcess.directory(runDirectory);
  714. try {
  715. return new ProcessResult(runProcess(hookProcess, outRedirect,
  716. errRedirect, stdinArgs), Status.OK);
  717. } catch (IOException e) {
  718. throw new JGitInternalException(MessageFormat.format(
  719. JGitText.get().exceptionCaughtDuringExecutionOfHook,
  720. hookName), e);
  721. } catch (InterruptedException e) {
  722. throw new JGitInternalException(MessageFormat.format(
  723. JGitText.get().exceptionHookExecutionInterrupted,
  724. hookName), e);
  725. }
  726. }
  727. /**
  728. * Tries to find a hook matching the given one in the given repository.
  729. *
  730. * @param repository
  731. * The repository within which to find a hook.
  732. * @param hookName
  733. * The name of the hook we're trying to find.
  734. * @return The {@link File} containing this particular hook if it exists in
  735. * the given repository, <code>null</code> otherwise.
  736. * @since 4.0
  737. */
  738. public File findHook(Repository repository, final String hookName) {
  739. final File hookFile = new File(new File(repository.getDirectory(),
  740. Constants.HOOKS), hookName);
  741. return hookFile.isFile() ? hookFile : null;
  742. }
  743. /**
  744. * Runs the given process until termination, clearing its stdout and stderr
  745. * streams on-the-fly.
  746. *
  747. * @param hookProcessBuilder
  748. * The process builder configured for this hook.
  749. * @param outRedirect
  750. * A print stream on which to redirect the hook's stdout. Can be
  751. * <code>null</code>, in which case the hook's standard output
  752. * will be lost.
  753. * @param errRedirect
  754. * A print stream on which to redirect the hook's stderr. Can be
  755. * <code>null</code>, in which case the hook's standard error
  756. * will be lost.
  757. * @param stdinArgs
  758. * A string to pass on to the standard input of the hook. Can be
  759. * <code>null</code>.
  760. * @return the exit value of this hook.
  761. * @throws IOException
  762. * if an I/O error occurs while executing this hook.
  763. * @throws InterruptedException
  764. * if the current thread is interrupted while waiting for the
  765. * process to end.
  766. * @since 3.7
  767. */
  768. protected int runProcess(ProcessBuilder hookProcessBuilder,
  769. OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
  770. throws IOException, InterruptedException {
  771. final ExecutorService executor = Executors.newFixedThreadPool(2);
  772. Process process = null;
  773. // We'll record the first I/O exception that occurs, but keep on trying
  774. // to dispose of our open streams and file handles
  775. IOException ioException = null;
  776. try {
  777. process = hookProcessBuilder.start();
  778. final Callable<Void> errorGobbler = new StreamGobbler(
  779. process.getErrorStream(), errRedirect);
  780. final Callable<Void> outputGobbler = new StreamGobbler(
  781. process.getInputStream(), outRedirect);
  782. executor.submit(errorGobbler);
  783. executor.submit(outputGobbler);
  784. if (stdinArgs != null) {
  785. final PrintWriter stdinWriter = new PrintWriter(
  786. process.getOutputStream());
  787. stdinWriter.print(stdinArgs);
  788. stdinWriter.flush();
  789. // We are done with this hook's input. Explicitly close its
  790. // stdin now to kick off any blocking read the hook might have.
  791. stdinWriter.close();
  792. }
  793. return process.waitFor();
  794. } catch (IOException e) {
  795. ioException = e;
  796. } finally {
  797. shutdownAndAwaitTermination(executor);
  798. if (process != null) {
  799. try {
  800. process.waitFor();
  801. } catch (InterruptedException e) {
  802. // Thrown by the outer try.
  803. // Swallow this one to carry on our cleanup, and clear the
  804. // interrupted flag (processes throw the exception without
  805. // clearing the flag).
  806. Thread.interrupted();
  807. }
  808. // A process doesn't clean its own resources even when destroyed
  809. // Explicitly try and close all three streams, preserving the
  810. // outer I/O exception if any.
  811. try {
  812. process.getErrorStream().close();
  813. } catch (IOException e) {
  814. ioException = ioException != null ? ioException : e;
  815. }
  816. try {
  817. process.getInputStream().close();
  818. } catch (IOException e) {
  819. ioException = ioException != null ? ioException : e;
  820. }
  821. try {
  822. process.getOutputStream().close();
  823. } catch (IOException e) {
  824. ioException = ioException != null ? ioException : e;
  825. }
  826. process.destroy();
  827. }
  828. }
  829. // We can only be here if the outer try threw an IOException.
  830. throw ioException;
  831. }
  832. /**
  833. * Shuts down an {@link ExecutorService} in two phases, first by calling
  834. * {@link ExecutorService#shutdown() shutdown} to reject incoming tasks, and
  835. * then calling {@link ExecutorService#shutdownNow() shutdownNow}, if
  836. * necessary, to cancel any lingering tasks. Returns true if the pool has
  837. * been properly shutdown, false otherwise.
  838. * <p>
  839. *
  840. * @param pool
  841. * the pool to shutdown
  842. * @return <code>true</code> if the pool has been properly shutdown,
  843. * <code>false</code> otherwise.
  844. */
  845. private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
  846. boolean hasShutdown = true;
  847. pool.shutdown(); // Disable new tasks from being submitted
  848. try {
  849. // Wait a while for existing tasks to terminate
  850. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  851. pool.shutdownNow(); // Cancel currently executing tasks
  852. // Wait a while for tasks to respond to being canceled
  853. if (!pool.awaitTermination(5, TimeUnit.SECONDS))
  854. hasShutdown = false;
  855. }
  856. } catch (InterruptedException ie) {
  857. // (Re-)Cancel if current thread also interrupted
  858. pool.shutdownNow();
  859. // Preserve interrupt status
  860. Thread.currentThread().interrupt();
  861. hasShutdown = false;
  862. }
  863. return hasShutdown;
  864. }
  865. /**
  866. * Initialize a ProcesssBuilder to run a command using the system shell.
  867. *
  868. * @param cmd
  869. * command to execute. This string should originate from the
  870. * end-user, and thus is platform specific.
  871. * @param args
  872. * arguments to pass to command. These should be protected from
  873. * shell evaluation.
  874. * @return a partially completed process builder. Caller should finish
  875. * populating directory, environment, and then start the process.
  876. */
  877. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  878. private static class Holder<V> {
  879. final V value;
  880. Holder(V value) {
  881. this.value = value;
  882. }
  883. }
  884. /**
  885. * File attributes we typically care for.
  886. *
  887. * @since 3.3
  888. */
  889. public static class Attributes {
  890. /**
  891. * @return true if this are the attributes of a directory
  892. */
  893. public boolean isDirectory() {
  894. return isDirectory;
  895. }
  896. /**
  897. * @return true if this are the attributes of an executable file
  898. */
  899. public boolean isExecutable() {
  900. return isExecutable;
  901. }
  902. /**
  903. * @return true if this are the attributes of a symbolic link
  904. */
  905. public boolean isSymbolicLink() {
  906. return isSymbolicLink;
  907. }
  908. /**
  909. * @return true if this are the attributes of a regular file
  910. */
  911. public boolean isRegularFile() {
  912. return isRegularFile;
  913. }
  914. /**
  915. * @return the time when the file was created
  916. */
  917. public long getCreationTime() {
  918. return creationTime;
  919. }
  920. /**
  921. * @return the time (milliseconds since 1970-01-01) when this object was
  922. * last modified
  923. */
  924. public long getLastModifiedTime() {
  925. return lastModifiedTime;
  926. }
  927. private boolean isDirectory;
  928. private boolean isSymbolicLink;
  929. private boolean isRegularFile;
  930. private long creationTime;
  931. private long lastModifiedTime;
  932. private boolean isExecutable;
  933. private File file;
  934. private boolean exists;
  935. /**
  936. * file length
  937. */
  938. protected long length = -1;
  939. FS fs;
  940. Attributes(FS fs, File file, boolean exists, boolean isDirectory,
  941. boolean isExecutable, boolean isSymbolicLink,
  942. boolean isRegularFile, long creationTime,
  943. long lastModifiedTime, long length) {
  944. this.fs = fs;
  945. this.file = file;
  946. this.exists = exists;
  947. this.isDirectory = isDirectory;
  948. this.isExecutable = isExecutable;
  949. this.isSymbolicLink = isSymbolicLink;
  950. this.isRegularFile = isRegularFile;
  951. this.creationTime = creationTime;
  952. this.lastModifiedTime = lastModifiedTime;
  953. this.length = length;
  954. }
  955. /**
  956. * Constructor when there are issues with reading
  957. *
  958. * @param fs
  959. * @param path
  960. */
  961. public Attributes(File path, FS fs) {
  962. this.file = path;
  963. this.fs = fs;
  964. }
  965. /**
  966. * @return length of this file object
  967. */
  968. public long getLength() {
  969. if (length == -1)
  970. return length = file.length();
  971. return length;
  972. }
  973. /**
  974. * @return the filename
  975. */
  976. public String getName() {
  977. return file.getName();
  978. }
  979. /**
  980. * @return the file the attributes apply to
  981. */
  982. public File getFile() {
  983. return file;
  984. }
  985. boolean exists() {
  986. return exists;
  987. }
  988. }
  989. /**
  990. * @param path
  991. * @return the file attributes we care for
  992. * @since 3.3
  993. */
  994. public Attributes getAttributes(File path) {
  995. boolean isDirectory = isDirectory(path);
  996. boolean isFile = !isDirectory && path.isFile();
  997. assert path.exists() == isDirectory || isFile;
  998. boolean exists = isDirectory || isFile;
  999. boolean canExecute = exists && !isDirectory && canExecute(path);
  1000. boolean isSymlink = false;
  1001. long lastModified = exists ? path.lastModified() : 0L;
  1002. long createTime = 0L;
  1003. return new Attributes(this, path, exists, isDirectory, canExecute,
  1004. isSymlink, isFile, createTime, lastModified, -1);
  1005. }
  1006. /**
  1007. * Normalize the unicode path to composed form.
  1008. *
  1009. * @param file
  1010. * @return NFC-format File
  1011. * @since 3.3
  1012. */
  1013. public File normalize(File file) {
  1014. return file;
  1015. }
  1016. /**
  1017. * Normalize the unicode path to composed form.
  1018. *
  1019. * @param name
  1020. * @return NFC-format string
  1021. * @since 3.3
  1022. */
  1023. public String normalize(String name) {
  1024. return name;
  1025. }
  1026. /**
  1027. * This runnable will consume an input stream's content into an output
  1028. * stream as soon as it gets available.
  1029. * <p>
  1030. * Typically used to empty processes' standard output and error, preventing
  1031. * them to choke.
  1032. * </p>
  1033. * <p>
  1034. * <b>Note</b> that a {@link StreamGobbler} will never close either of its
  1035. * streams.
  1036. * </p>
  1037. */
  1038. private static class StreamGobbler implements Callable<Void> {
  1039. private final BufferedReader reader;
  1040. private final BufferedWriter writer;
  1041. public StreamGobbler(InputStream stream, OutputStream output) {
  1042. this.reader = new BufferedReader(new InputStreamReader(stream));
  1043. if (output == null)
  1044. this.writer = null;
  1045. else
  1046. this.writer = new BufferedWriter(new OutputStreamWriter(output));
  1047. }
  1048. public Void call() throws IOException {
  1049. boolean writeFailure = false;
  1050. String line = null;
  1051. while ((line = reader.readLine()) != null) {
  1052. // Do not try to write again after a failure, but keep reading
  1053. // as long as possible to prevent the input stream from choking.
  1054. if (!writeFailure && writer != null) {
  1055. try {
  1056. writer.write(line);
  1057. writer.newLine();
  1058. writer.flush();
  1059. } catch (IOException e) {
  1060. writeFailure = true;
  1061. }
  1062. }
  1063. }
  1064. return null;
  1065. }
  1066. }
  1067. }