Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

FS.java 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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. * @return the one-line output of the command
  375. */
  376. protected static String readPipe(File dir, String[] command, String encoding) {
  377. final boolean debug = LOG.isDebugEnabled();
  378. try {
  379. if (debug) {
  380. LOG.debug("readpipe " + Arrays.asList(command) + "," //$NON-NLS-1$ //$NON-NLS-2$
  381. + dir);
  382. }
  383. final Process p = Runtime.getRuntime().exec(command, null, dir);
  384. final BufferedReader lineRead = new BufferedReader(
  385. new InputStreamReader(p.getInputStream(), encoding));
  386. p.getOutputStream().close();
  387. final AtomicBoolean gooblerFail = new AtomicBoolean(false);
  388. Thread gobbler = new Thread() {
  389. public void run() {
  390. InputStream is = p.getErrorStream();
  391. try {
  392. int ch;
  393. if (debug)
  394. while ((ch = is.read()) != -1)
  395. System.err.print((char) ch);
  396. else
  397. while (is.read() != -1) {
  398. // ignore
  399. }
  400. } catch (IOException e) {
  401. // Just print on stderr for debugging
  402. if (debug)
  403. e.printStackTrace(System.err);
  404. gooblerFail.set(true);
  405. }
  406. try {
  407. is.close();
  408. } catch (IOException e) {
  409. // Just print on stderr for debugging
  410. if (debug) {
  411. LOG.debug("Caught exception in gobbler thread", e); //$NON-NLS-1$
  412. }
  413. gooblerFail.set(true);
  414. }
  415. }
  416. };
  417. gobbler.start();
  418. String r = null;
  419. try {
  420. r = lineRead.readLine();
  421. if (debug) {
  422. LOG.debug("readpipe may return '" + r + "'"); //$NON-NLS-1$ //$NON-NLS-2$
  423. LOG.debug("(ignoring remaing output:"); //$NON-NLS-1$
  424. }
  425. String l;
  426. while ((l = lineRead.readLine()) != null) {
  427. if (debug) {
  428. LOG.debug(l);
  429. }
  430. }
  431. } finally {
  432. p.getErrorStream().close();
  433. lineRead.close();
  434. }
  435. for (;;) {
  436. try {
  437. int rc = p.waitFor();
  438. gobbler.join();
  439. if (rc == 0 && r != null && r.length() > 0
  440. && !gooblerFail.get())
  441. return r;
  442. if (debug) {
  443. LOG.debug("readpipe rc=" + rc); //$NON-NLS-1$
  444. }
  445. break;
  446. } catch (InterruptedException ie) {
  447. // Stop bothering me, I have a zombie to reap.
  448. }
  449. }
  450. } catch (IOException e) {
  451. LOG.error("Caught exception in FS.readPipe()", e); //$NON-NLS-1$
  452. }
  453. if (debug) {
  454. LOG.debug("readpipe returns null"); //$NON-NLS-1$
  455. }
  456. return null;
  457. }
  458. /** @return the $prefix directory C Git would use. */
  459. public File gitPrefix() {
  460. Holder<File> p = gitPrefix;
  461. if (p == null) {
  462. String overrideGitPrefix = SystemReader.getInstance().getProperty(
  463. "jgit.gitprefix"); //$NON-NLS-1$
  464. if (overrideGitPrefix != null)
  465. p = new Holder<File>(new File(overrideGitPrefix));
  466. else
  467. p = new Holder<File>(discoverGitPrefix());
  468. gitPrefix = p;
  469. }
  470. return p.value;
  471. }
  472. /** @return the $prefix directory C Git would use. */
  473. protected abstract File discoverGitPrefix();
  474. /**
  475. * Set the $prefix directory C Git uses.
  476. *
  477. * @param path
  478. * the directory. Null if C Git is not installed.
  479. * @return {@code this}
  480. */
  481. public FS setGitPrefix(File path) {
  482. gitPrefix = new Holder<File>(path);
  483. return this;
  484. }
  485. /**
  486. * Check if a file is a symbolic link and read it
  487. *
  488. * @param path
  489. * @return target of link or null
  490. * @throws IOException
  491. * @since 3.0
  492. */
  493. public String readSymLink(File path) throws IOException {
  494. throw new SymlinksNotSupportedException(
  495. JGitText.get().errorSymlinksNotSupported);
  496. }
  497. /**
  498. * @param path
  499. * @return true if the path is a symbolic link (and we support these)
  500. * @throws IOException
  501. * @since 3.0
  502. */
  503. public boolean isSymLink(File path) throws IOException {
  504. return false;
  505. }
  506. /**
  507. * Tests if the path exists, in case of a symbolic link, true even if the
  508. * target does not exist
  509. *
  510. * @param path
  511. * @return true if path exists
  512. * @since 3.0
  513. */
  514. public boolean exists(File path) {
  515. return path.exists();
  516. }
  517. /**
  518. * Check if path is a directory. If the OS/JRE supports symbolic links and
  519. * path is a symbolic link to a directory, this method returns false.
  520. *
  521. * @param path
  522. * @return true if file is a directory,
  523. * @since 3.0
  524. */
  525. public boolean isDirectory(File path) {
  526. return path.isDirectory();
  527. }
  528. /**
  529. * Examine if path represents a regular file. If the OS/JRE supports
  530. * symbolic links the test returns false if path represents a symbolic link.
  531. *
  532. * @param path
  533. * @return true if path represents a regular file
  534. * @since 3.0
  535. */
  536. public boolean isFile(File path) {
  537. return path.isFile();
  538. }
  539. /**
  540. * @param path
  541. * @return true if path is hidden, either starts with . on unix or has the
  542. * hidden attribute in windows
  543. * @throws IOException
  544. * @since 3.0
  545. */
  546. public boolean isHidden(File path) throws IOException {
  547. return path.isHidden();
  548. }
  549. /**
  550. * Set the hidden attribute for file whose name starts with a period.
  551. *
  552. * @param path
  553. * @param hidden
  554. * @throws IOException
  555. * @since 3.0
  556. */
  557. public void setHidden(File path, boolean hidden) throws IOException {
  558. if (!path.getName().startsWith(".")) //$NON-NLS-1$
  559. throw new IllegalArgumentException(
  560. "Hiding only allowed for names that start with a period");
  561. }
  562. /**
  563. * Create a symbolic link
  564. *
  565. * @param path
  566. * @param target
  567. * @throws IOException
  568. * @since 3.0
  569. */
  570. public void createSymLink(File path, String target) throws IOException {
  571. throw new SymlinksNotSupportedException(
  572. JGitText.get().errorSymlinksNotSupported);
  573. }
  574. /**
  575. * See {@link FileUtils#relativize(String, String)}.
  576. *
  577. * @param base
  578. * The path against which <code>other</code> should be
  579. * relativized.
  580. * @param other
  581. * The path that will be made relative to <code>base</code>.
  582. * @return A relative path that, when resolved against <code>base</code>,
  583. * will yield the original <code>other</code>.
  584. * @see FileUtils#relativize(String, String)
  585. * @since 3.7
  586. */
  587. public String relativize(String base, String other) {
  588. return FileUtils.relativize(base, other);
  589. }
  590. /**
  591. * Checks whether the given hook is defined for the given repository, then
  592. * runs it with the given arguments.
  593. * <p>
  594. * The hook's standard output and error streams will be redirected to
  595. * <code>System.out</code> and <code>System.err</code> respectively. The
  596. * hook will have no stdin.
  597. * </p>
  598. *
  599. * @param repository
  600. * The repository for which a hook should be run.
  601. * @param hookName
  602. * The name of the hook to be executed.
  603. * @param args
  604. * Arguments to pass to this hook. Cannot be <code>null</code>,
  605. * but can be an empty array.
  606. * @return The ProcessResult describing this hook's execution.
  607. * @throws JGitInternalException
  608. * if we fail to run the hook somehow. Causes may include an
  609. * interrupted process or I/O errors.
  610. * @since 4.0
  611. */
  612. public ProcessResult runHookIfPresent(Repository repository,
  613. final String hookName,
  614. String[] args) throws JGitInternalException {
  615. return runHookIfPresent(repository, hookName, args, System.out, System.err,
  616. null);
  617. }
  618. /**
  619. * Checks whether the given hook is defined for the given repository, then
  620. * runs it with the given arguments.
  621. *
  622. * @param repository
  623. * The repository for which a hook should be run.
  624. * @param hookName
  625. * The name of the hook to be executed.
  626. * @param args
  627. * Arguments to pass to this hook. Cannot be <code>null</code>,
  628. * but can be an empty array.
  629. * @param outRedirect
  630. * A print stream on which to redirect the hook's stdout. Can be
  631. * <code>null</code>, in which case the hook's standard output
  632. * will be lost.
  633. * @param errRedirect
  634. * A print stream on which to redirect the hook's stderr. Can be
  635. * <code>null</code>, in which case the hook's standard error
  636. * will be lost.
  637. * @param stdinArgs
  638. * A string to pass on to the standard input of the hook. May be
  639. * <code>null</code>.
  640. * @return The ProcessResult describing this hook's execution.
  641. * @throws JGitInternalException
  642. * if we fail to run the hook somehow. Causes may include an
  643. * interrupted process or I/O errors.
  644. * @since 4.0
  645. */
  646. public ProcessResult runHookIfPresent(Repository repository,
  647. final String hookName,
  648. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  649. String stdinArgs) throws JGitInternalException {
  650. return new ProcessResult(Status.NOT_SUPPORTED);
  651. }
  652. /**
  653. * See
  654. * {@link #runHookIfPresent(Repository, String, String[], PrintStream, PrintStream, String)}
  655. * . Should only be called by FS supporting shell scripts execution.
  656. *
  657. * @param repository
  658. * The repository for which a hook should be run.
  659. * @param hookName
  660. * The name of the hook to be executed.
  661. * @param args
  662. * Arguments to pass to this hook. Cannot be <code>null</code>,
  663. * but can be an empty array.
  664. * @param outRedirect
  665. * A print stream on which to redirect the hook's stdout. Can be
  666. * <code>null</code>, in which case the hook's standard output
  667. * will be lost.
  668. * @param errRedirect
  669. * A print stream on which to redirect the hook's stderr. Can be
  670. * <code>null</code>, in which case the hook's standard error
  671. * will be lost.
  672. * @param stdinArgs
  673. * A string to pass on to the standard input of the hook. May be
  674. * <code>null</code>.
  675. * @return The ProcessResult describing this hook's execution.
  676. * @throws JGitInternalException
  677. * if we fail to run the hook somehow. Causes may include an
  678. * interrupted process or I/O errors.
  679. * @since 4.0
  680. */
  681. protected ProcessResult internalRunHookIfPresent(Repository repository,
  682. final String hookName, String[] args, PrintStream outRedirect,
  683. PrintStream errRedirect, String stdinArgs)
  684. throws JGitInternalException {
  685. final File hookFile = findHook(repository, hookName);
  686. if (hookFile == null)
  687. return new ProcessResult(Status.NOT_PRESENT);
  688. final String hookPath = hookFile.getAbsolutePath();
  689. final File runDirectory;
  690. if (repository.isBare())
  691. runDirectory = repository.getDirectory();
  692. else
  693. runDirectory = repository.getWorkTree();
  694. final String cmd = relativize(runDirectory.getAbsolutePath(),
  695. hookPath);
  696. ProcessBuilder hookProcess = runInShell(cmd, args);
  697. hookProcess.directory(runDirectory);
  698. try {
  699. return new ProcessResult(runProcess(hookProcess, outRedirect,
  700. errRedirect, stdinArgs), Status.OK);
  701. } catch (IOException e) {
  702. throw new JGitInternalException(MessageFormat.format(
  703. JGitText.get().exceptionCaughtDuringExecutionOfHook,
  704. hookName), e);
  705. } catch (InterruptedException e) {
  706. throw new JGitInternalException(MessageFormat.format(
  707. JGitText.get().exceptionHookExecutionInterrupted,
  708. hookName), e);
  709. }
  710. }
  711. /**
  712. * Tries to find a hook matching the given one in the given repository.
  713. *
  714. * @param repository
  715. * The repository within which to find a hook.
  716. * @param hookName
  717. * The name of the hook we're trying to find.
  718. * @return The {@link File} containing this particular hook if it exists in
  719. * the given repository, <code>null</code> otherwise.
  720. * @since 4.0
  721. */
  722. public File findHook(Repository repository, final String hookName) {
  723. final File hookFile = new File(new File(repository.getDirectory(),
  724. Constants.HOOKS), hookName);
  725. return hookFile.isFile() ? hookFile : null;
  726. }
  727. /**
  728. * Runs the given process until termination, clearing its stdout and stderr
  729. * streams on-the-fly.
  730. *
  731. * @param hookProcessBuilder
  732. * The process builder configured for this hook.
  733. * @param outRedirect
  734. * A print stream on which to redirect the hook's stdout. Can be
  735. * <code>null</code>, in which case the hook's standard output
  736. * will be lost.
  737. * @param errRedirect
  738. * A print stream on which to redirect the hook's stderr. Can be
  739. * <code>null</code>, in which case the hook's standard error
  740. * will be lost.
  741. * @param stdinArgs
  742. * A string to pass on to the standard input of the hook. Can be
  743. * <code>null</code>.
  744. * @return the exit value of this hook.
  745. * @throws IOException
  746. * if an I/O error occurs while executing this hook.
  747. * @throws InterruptedException
  748. * if the current thread is interrupted while waiting for the
  749. * process to end.
  750. * @since 3.7
  751. */
  752. protected int runProcess(ProcessBuilder hookProcessBuilder,
  753. OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
  754. throws IOException, InterruptedException {
  755. final ExecutorService executor = Executors.newFixedThreadPool(2);
  756. Process process = null;
  757. // We'll record the first I/O exception that occurs, but keep on trying
  758. // to dispose of our open streams and file handles
  759. IOException ioException = null;
  760. try {
  761. process = hookProcessBuilder.start();
  762. final Callable<Void> errorGobbler = new StreamGobbler(
  763. process.getErrorStream(), errRedirect);
  764. final Callable<Void> outputGobbler = new StreamGobbler(
  765. process.getInputStream(), outRedirect);
  766. executor.submit(errorGobbler);
  767. executor.submit(outputGobbler);
  768. if (stdinArgs != null) {
  769. final PrintWriter stdinWriter = new PrintWriter(
  770. process.getOutputStream());
  771. stdinWriter.print(stdinArgs);
  772. stdinWriter.flush();
  773. // We are done with this hook's input. Explicitly close its
  774. // stdin now to kick off any blocking read the hook might have.
  775. stdinWriter.close();
  776. }
  777. return process.waitFor();
  778. } catch (IOException e) {
  779. ioException = e;
  780. } finally {
  781. shutdownAndAwaitTermination(executor);
  782. if (process != null) {
  783. try {
  784. process.waitFor();
  785. } catch (InterruptedException e) {
  786. // Thrown by the outer try.
  787. // Swallow this one to carry on our cleanup, and clear the
  788. // interrupted flag (processes throw the exception without
  789. // clearing the flag).
  790. Thread.interrupted();
  791. }
  792. // A process doesn't clean its own resources even when destroyed
  793. // Explicitly try and close all three streams, preserving the
  794. // outer I/O exception if any.
  795. try {
  796. process.getErrorStream().close();
  797. } catch (IOException e) {
  798. ioException = ioException != null ? ioException : e;
  799. }
  800. try {
  801. process.getInputStream().close();
  802. } catch (IOException e) {
  803. ioException = ioException != null ? ioException : e;
  804. }
  805. try {
  806. process.getOutputStream().close();
  807. } catch (IOException e) {
  808. ioException = ioException != null ? ioException : e;
  809. }
  810. process.destroy();
  811. }
  812. }
  813. // We can only be here if the outer try threw an IOException.
  814. throw ioException;
  815. }
  816. /**
  817. * Shuts down an {@link ExecutorService} in two phases, first by calling
  818. * {@link ExecutorService#shutdown() shutdown} to reject incoming tasks, and
  819. * then calling {@link ExecutorService#shutdownNow() shutdownNow}, if
  820. * necessary, to cancel any lingering tasks. Returns true if the pool has
  821. * been properly shutdown, false otherwise.
  822. * <p>
  823. *
  824. * @param pool
  825. * the pool to shutdown
  826. * @return <code>true</code> if the pool has been properly shutdown,
  827. * <code>false</code> otherwise.
  828. */
  829. private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
  830. boolean hasShutdown = true;
  831. pool.shutdown(); // Disable new tasks from being submitted
  832. try {
  833. // Wait a while for existing tasks to terminate
  834. if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
  835. pool.shutdownNow(); // Cancel currently executing tasks
  836. // Wait a while for tasks to respond to being canceled
  837. if (!pool.awaitTermination(5, TimeUnit.SECONDS))
  838. hasShutdown = false;
  839. }
  840. } catch (InterruptedException ie) {
  841. // (Re-)Cancel if current thread also interrupted
  842. pool.shutdownNow();
  843. // Preserve interrupt status
  844. Thread.currentThread().interrupt();
  845. hasShutdown = false;
  846. }
  847. return hasShutdown;
  848. }
  849. /**
  850. * Initialize a ProcesssBuilder to run a command using the system shell.
  851. *
  852. * @param cmd
  853. * command to execute. This string should originate from the
  854. * end-user, and thus is platform specific.
  855. * @param args
  856. * arguments to pass to command. These should be protected from
  857. * shell evaluation.
  858. * @return a partially completed process builder. Caller should finish
  859. * populating directory, environment, and then start the process.
  860. */
  861. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  862. private static class Holder<V> {
  863. final V value;
  864. Holder(V value) {
  865. this.value = value;
  866. }
  867. }
  868. /**
  869. * File attributes we typically care for.
  870. *
  871. * @since 3.3
  872. */
  873. public static class Attributes {
  874. /**
  875. * @return true if this are the attributes of a directory
  876. */
  877. public boolean isDirectory() {
  878. return isDirectory;
  879. }
  880. /**
  881. * @return true if this are the attributes of an executable file
  882. */
  883. public boolean isExecutable() {
  884. return isExecutable;
  885. }
  886. /**
  887. * @return true if this are the attributes of a symbolic link
  888. */
  889. public boolean isSymbolicLink() {
  890. return isSymbolicLink;
  891. }
  892. /**
  893. * @return true if this are the attributes of a regular file
  894. */
  895. public boolean isRegularFile() {
  896. return isRegularFile;
  897. }
  898. /**
  899. * @return the time when the file was created
  900. */
  901. public long getCreationTime() {
  902. return creationTime;
  903. }
  904. /**
  905. * @return the time (milliseconds since 1970-01-01) when this object was
  906. * last modified
  907. */
  908. public long getLastModifiedTime() {
  909. return lastModifiedTime;
  910. }
  911. private boolean isDirectory;
  912. private boolean isSymbolicLink;
  913. private boolean isRegularFile;
  914. private long creationTime;
  915. private long lastModifiedTime;
  916. private boolean isExecutable;
  917. private File file;
  918. private boolean exists;
  919. /**
  920. * file length
  921. */
  922. protected long length = -1;
  923. FS fs;
  924. Attributes(FS fs, File file, boolean exists, boolean isDirectory,
  925. boolean isExecutable, boolean isSymbolicLink,
  926. boolean isRegularFile, long creationTime,
  927. long lastModifiedTime, long length) {
  928. this.fs = fs;
  929. this.file = file;
  930. this.exists = exists;
  931. this.isDirectory = isDirectory;
  932. this.isExecutable = isExecutable;
  933. this.isSymbolicLink = isSymbolicLink;
  934. this.isRegularFile = isRegularFile;
  935. this.creationTime = creationTime;
  936. this.lastModifiedTime = lastModifiedTime;
  937. this.length = length;
  938. }
  939. /**
  940. * Constructor when there are issues with reading
  941. *
  942. * @param fs
  943. * @param path
  944. */
  945. public Attributes(File path, FS fs) {
  946. this.file = path;
  947. this.fs = fs;
  948. }
  949. /**
  950. * @return length of this file object
  951. */
  952. public long getLength() {
  953. if (length == -1)
  954. return length = file.length();
  955. return length;
  956. }
  957. /**
  958. * @return the filename
  959. */
  960. public String getName() {
  961. return file.getName();
  962. }
  963. /**
  964. * @return the file the attributes apply to
  965. */
  966. public File getFile() {
  967. return file;
  968. }
  969. boolean exists() {
  970. return exists;
  971. }
  972. }
  973. /**
  974. * @param path
  975. * @return the file attributes we care for
  976. * @since 3.3
  977. */
  978. public Attributes getAttributes(File path) {
  979. boolean isDirectory = isDirectory(path);
  980. boolean isFile = !isDirectory && path.isFile();
  981. assert path.exists() == isDirectory || isFile;
  982. boolean exists = isDirectory || isFile;
  983. boolean canExecute = exists && !isDirectory && canExecute(path);
  984. boolean isSymlink = false;
  985. long lastModified = exists ? path.lastModified() : 0L;
  986. long createTime = 0L;
  987. return new Attributes(this, path, exists, isDirectory, canExecute,
  988. isSymlink, isFile, createTime, lastModified, -1);
  989. }
  990. /**
  991. * Normalize the unicode path to composed form.
  992. *
  993. * @param file
  994. * @return NFC-format File
  995. * @since 3.3
  996. */
  997. public File normalize(File file) {
  998. return file;
  999. }
  1000. /**
  1001. * Normalize the unicode path to composed form.
  1002. *
  1003. * @param name
  1004. * @return NFC-format string
  1005. * @since 3.3
  1006. */
  1007. public String normalize(String name) {
  1008. return name;
  1009. }
  1010. /**
  1011. * This runnable will consume an input stream's content into an output
  1012. * stream as soon as it gets available.
  1013. * <p>
  1014. * Typically used to empty processes' standard output and error, preventing
  1015. * them to choke.
  1016. * </p>
  1017. * <p>
  1018. * <b>Note</b> that a {@link StreamGobbler} will never close either of its
  1019. * streams.
  1020. * </p>
  1021. */
  1022. private static class StreamGobbler implements Callable<Void> {
  1023. private final BufferedReader reader;
  1024. private final BufferedWriter writer;
  1025. public StreamGobbler(InputStream stream, OutputStream output) {
  1026. this.reader = new BufferedReader(new InputStreamReader(stream));
  1027. if (output == null)
  1028. this.writer = null;
  1029. else
  1030. this.writer = new BufferedWriter(new OutputStreamWriter(output));
  1031. }
  1032. public Void call() throws IOException {
  1033. boolean writeFailure = false;
  1034. String line = null;
  1035. while ((line = reader.readLine()) != null) {
  1036. // Do not try to write again after a failure, but keep reading
  1037. // as long as possible to prevent the input stream from choking.
  1038. if (!writeFailure && writer != null) {
  1039. try {
  1040. writer.write(line);
  1041. writer.newLine();
  1042. writer.flush();
  1043. } catch (IOException e) {
  1044. writeFailure = true;
  1045. }
  1046. }
  1047. }
  1048. return null;
  1049. }
  1050. }
  1051. }