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

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