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 44KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  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.ByteArrayInputStream;
  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.PrintStream;
  52. import java.nio.charset.Charset;
  53. import java.security.AccessController;
  54. import java.security.PrivilegedAction;
  55. import java.text.MessageFormat;
  56. import java.util.Arrays;
  57. import java.util.HashMap;
  58. import java.util.Map;
  59. import java.util.Objects;
  60. import java.util.concurrent.ExecutorService;
  61. import java.util.concurrent.Executors;
  62. import java.util.concurrent.TimeUnit;
  63. import java.util.concurrent.atomic.AtomicBoolean;
  64. import java.util.concurrent.atomic.AtomicReference;
  65. import org.eclipse.jgit.annotations.Nullable;
  66. import org.eclipse.jgit.api.errors.JGitInternalException;
  67. import org.eclipse.jgit.errors.CommandFailedException;
  68. import org.eclipse.jgit.internal.JGitText;
  69. import org.eclipse.jgit.lib.Constants;
  70. import org.eclipse.jgit.lib.Repository;
  71. import org.eclipse.jgit.util.ProcessResult.Status;
  72. import org.slf4j.Logger;
  73. import org.slf4j.LoggerFactory;
  74. /**
  75. * Abstraction to support various file system operations not in Java.
  76. */
  77. public abstract class FS {
  78. private static final Logger LOG = LoggerFactory.getLogger(FS.class);
  79. /**
  80. * This class creates FS instances. It will be overridden by a Java7 variant
  81. * if such can be detected in {@link #detect(Boolean)}.
  82. *
  83. * @since 3.0
  84. */
  85. public static class FSFactory {
  86. /**
  87. * Constructor
  88. */
  89. protected FSFactory() {
  90. // empty
  91. }
  92. /**
  93. * Detect the file system
  94. *
  95. * @param cygwinUsed
  96. * @return FS instance
  97. */
  98. public FS detect(Boolean cygwinUsed) {
  99. if (SystemReader.getInstance().isWindows()) {
  100. if (cygwinUsed == null)
  101. cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
  102. if (cygwinUsed.booleanValue())
  103. return new FS_Win32_Cygwin();
  104. else
  105. return new FS_Win32();
  106. } else {
  107. return new FS_POSIX();
  108. }
  109. }
  110. }
  111. /**
  112. * Result of an executed process. The caller is responsible to close the
  113. * contained {@link TemporaryBuffer}s
  114. *
  115. * @since 4.2
  116. */
  117. public static class ExecutionResult {
  118. private TemporaryBuffer stdout;
  119. private TemporaryBuffer stderr;
  120. private int rc;
  121. /**
  122. * @param stdout
  123. * @param stderr
  124. * @param rc
  125. */
  126. public ExecutionResult(TemporaryBuffer stdout, TemporaryBuffer stderr,
  127. int rc) {
  128. this.stdout = stdout;
  129. this.stderr = stderr;
  130. this.rc = rc;
  131. }
  132. /**
  133. * @return buffered standard output stream
  134. */
  135. public TemporaryBuffer getStdout() {
  136. return stdout;
  137. }
  138. /**
  139. * @return buffered standard error stream
  140. */
  141. public TemporaryBuffer getStderr() {
  142. return stderr;
  143. }
  144. /**
  145. * @return the return code of the process
  146. */
  147. public int getRc() {
  148. return rc;
  149. }
  150. }
  151. /** The auto-detected implementation selected for this operating system and JRE. */
  152. public static final FS DETECTED = detect();
  153. private volatile static FSFactory factory;
  154. /**
  155. * Auto-detect the appropriate file system abstraction.
  156. *
  157. * @return detected file system abstraction
  158. */
  159. public static FS detect() {
  160. return detect(null);
  161. }
  162. /**
  163. * Auto-detect the appropriate file system abstraction, taking into account
  164. * the presence of a Cygwin installation on the system. Using jgit in
  165. * combination with Cygwin requires a more elaborate (and possibly slower)
  166. * resolution of file system paths.
  167. *
  168. * @param cygwinUsed
  169. * <ul>
  170. * <li><code>Boolean.TRUE</code> to assume that Cygwin is used in
  171. * combination with jgit</li>
  172. * <li><code>Boolean.FALSE</code> to assume that Cygwin is
  173. * <b>not</b> used with jgit</li>
  174. * <li><code>null</code> to auto-detect whether a Cygwin
  175. * installation is present on the system and in this case assume
  176. * that Cygwin is used</li>
  177. * </ul>
  178. *
  179. * Note: this parameter is only relevant on Windows.
  180. * @return detected file system abstraction
  181. */
  182. public static FS detect(Boolean cygwinUsed) {
  183. if (factory == null) {
  184. factory = new FS.FSFactory();
  185. }
  186. return factory.detect(cygwinUsed);
  187. }
  188. private volatile Holder<File> userHome;
  189. private volatile Holder<File> gitSystemConfig;
  190. /**
  191. * Constructs a file system abstraction.
  192. */
  193. protected FS() {
  194. // Do nothing by default.
  195. }
  196. /**
  197. * Initialize this FS using another's current settings.
  198. *
  199. * @param src
  200. * the source FS to copy from.
  201. */
  202. protected FS(FS src) {
  203. userHome = src.userHome;
  204. gitSystemConfig = src.gitSystemConfig;
  205. }
  206. /**
  207. * Create a new instance of the same type of FS.
  208. *
  209. * @return a new instance of the same type of FS.
  210. */
  211. public abstract FS newInstance();
  212. /**
  213. * Does this operating system and JRE support the execute flag on files?
  214. *
  215. * @return true if this implementation can provide reasonably accurate
  216. * executable bit information; false otherwise.
  217. */
  218. public abstract boolean supportsExecute();
  219. /**
  220. * Does this file system support atomic file creation via
  221. * java.io.File#createNewFile()? In certain environments (e.g. on NFS) it is
  222. * not guaranteed that when two file system clients run createNewFile() in
  223. * parallel only one will succeed. In such cases both clients may think they
  224. * created a new file.
  225. *
  226. * @return true if this implementation support atomic creation of new Files
  227. * by {@link java.io.File#createNewFile()}
  228. * @since 4.5
  229. */
  230. public boolean supportsAtomicCreateNewFile() {
  231. return true;
  232. }
  233. /**
  234. * Does this operating system and JRE supports symbolic links. The
  235. * capability to handle symbolic links is detected at runtime.
  236. *
  237. * @return true if symbolic links may be used
  238. * @since 3.0
  239. */
  240. public boolean supportsSymlinks() {
  241. return false;
  242. }
  243. /**
  244. * Is this file system case sensitive
  245. *
  246. * @return true if this implementation is case sensitive
  247. */
  248. public abstract boolean isCaseSensitive();
  249. /**
  250. * Determine if the file is executable (or not).
  251. * <p>
  252. * Not all platforms and JREs support executable flags on files. If the
  253. * feature is unsupported this method will always return false.
  254. * <p>
  255. * <em>If the platform supports symbolic links and <code>f</code> is a symbolic link
  256. * this method returns false, rather than the state of the executable flags
  257. * on the target file.</em>
  258. *
  259. * @param f
  260. * abstract path to test.
  261. * @return true if the file is believed to be executable by the user.
  262. */
  263. public abstract boolean canExecute(File f);
  264. /**
  265. * Set a file to be executable by the user.
  266. * <p>
  267. * Not all platforms and JREs support executable flags on files. If the
  268. * feature is unsupported this method will always return false and no
  269. * changes will be made to the file specified.
  270. *
  271. * @param f
  272. * path to modify the executable status of.
  273. * @param canExec
  274. * true to enable execution; false to disable it.
  275. * @return true if the change succeeded; false otherwise.
  276. */
  277. public abstract boolean setExecute(File f, boolean canExec);
  278. /**
  279. * Get the last modified time of a file system object. If the OS/JRE support
  280. * symbolic links, the modification time of the link is returned, rather
  281. * than that of the link target.
  282. *
  283. * @param f
  284. * a {@link java.io.File} object.
  285. * @return last modified time of f
  286. * @throws java.io.IOException
  287. * @since 3.0
  288. */
  289. public long lastModified(File f) throws IOException {
  290. return FileUtils.lastModified(f);
  291. }
  292. /**
  293. * Set the last modified time of a file system object. If the OS/JRE support
  294. * symbolic links, the link is modified, not the target,
  295. *
  296. * @param f
  297. * a {@link java.io.File} object.
  298. * @param time
  299. * last modified time
  300. * @throws java.io.IOException
  301. * @since 3.0
  302. */
  303. public void setLastModified(File f, long time) throws IOException {
  304. FileUtils.setLastModified(f, time);
  305. }
  306. /**
  307. * Get the length of a file or link, If the OS/JRE supports symbolic links
  308. * it's the length of the link, else the length of the target.
  309. *
  310. * @param path
  311. * a {@link java.io.File} object.
  312. * @return length of a file
  313. * @throws java.io.IOException
  314. * @since 3.0
  315. */
  316. public long length(File path) throws IOException {
  317. return FileUtils.getLength(path);
  318. }
  319. /**
  320. * Delete a file. Throws an exception if delete fails.
  321. *
  322. * @param f
  323. * a {@link java.io.File} object.
  324. * @throws java.io.IOException
  325. * this may be a Java7 subclass with detailed information
  326. * @since 3.3
  327. */
  328. public void delete(File f) throws IOException {
  329. FileUtils.delete(f);
  330. }
  331. /**
  332. * Resolve this file to its actual path name that the JRE can use.
  333. * <p>
  334. * This method can be relatively expensive. Computing a translation may
  335. * require forking an external process per path name translated. Callers
  336. * should try to minimize the number of translations necessary by caching
  337. * the results.
  338. * <p>
  339. * Not all platforms and JREs require path name translation. Currently only
  340. * Cygwin on Win32 require translation for Cygwin based paths.
  341. *
  342. * @param dir
  343. * directory relative to which the path name is.
  344. * @param name
  345. * path name to translate.
  346. * @return the translated path. <code>new File(dir,name)</code> if this
  347. * platform does not require path name translation.
  348. */
  349. public File resolve(final File dir, final String name) {
  350. final File abspn = new File(name);
  351. if (abspn.isAbsolute())
  352. return abspn;
  353. return new File(dir, name);
  354. }
  355. /**
  356. * Determine the user's home directory (location where preferences are).
  357. * <p>
  358. * This method can be expensive on the first invocation if path name
  359. * translation is required. Subsequent invocations return a cached result.
  360. * <p>
  361. * Not all platforms and JREs require path name translation. Currently only
  362. * Cygwin on Win32 requires translation of the Cygwin HOME directory.
  363. *
  364. * @return the user's home directory; null if the user does not have one.
  365. */
  366. public File userHome() {
  367. Holder<File> p = userHome;
  368. if (p == null) {
  369. p = new Holder<>(userHomeImpl());
  370. userHome = p;
  371. }
  372. return p.value;
  373. }
  374. /**
  375. * Set the user's home directory location.
  376. *
  377. * @param path
  378. * the location of the user's preferences; null if there is no
  379. * home directory for the current user.
  380. * @return {@code this}.
  381. */
  382. public FS setUserHome(File path) {
  383. userHome = new Holder<>(path);
  384. return this;
  385. }
  386. /**
  387. * Does this file system have problems with atomic renames?
  388. *
  389. * @return true if the caller should retry a failed rename of a lock file.
  390. */
  391. public abstract boolean retryFailedLockFileCommit();
  392. /**
  393. * Determine the user's home directory (location where preferences are).
  394. *
  395. * @return the user's home directory; null if the user does not have one.
  396. */
  397. protected File userHomeImpl() {
  398. final String home = AccessController
  399. .doPrivileged(new PrivilegedAction<String>() {
  400. @Override
  401. public String run() {
  402. return System.getProperty("user.home"); //$NON-NLS-1$
  403. }
  404. });
  405. if (home == null || home.length() == 0)
  406. return null;
  407. return new File(home).getAbsoluteFile();
  408. }
  409. /**
  410. * Searches the given path to see if it contains one of the given files.
  411. * Returns the first it finds. Returns null if not found or if path is null.
  412. *
  413. * @param path
  414. * List of paths to search separated by File.pathSeparator
  415. * @param lookFor
  416. * Files to search for in the given path
  417. * @return the first match found, or null
  418. * @since 3.0
  419. */
  420. protected static File searchPath(final String path, final String... lookFor) {
  421. if (path == null)
  422. return null;
  423. for (final String p : path.split(File.pathSeparator)) {
  424. for (String command : lookFor) {
  425. final File e = new File(p, command);
  426. if (e.isFile())
  427. return e.getAbsoluteFile();
  428. }
  429. }
  430. return null;
  431. }
  432. /**
  433. * Execute a command and return a single line of output as a String
  434. *
  435. * @param dir
  436. * Working directory for the command
  437. * @param command
  438. * as component array
  439. * @param encoding
  440. * to be used to parse the command's output
  441. * @return the one-line output of the command or {@code null} if there is
  442. * none
  443. * @throws org.eclipse.jgit.errors.CommandFailedException
  444. * thrown when the command failed (return code was non-zero)
  445. */
  446. @Nullable
  447. protected static String readPipe(File dir, String[] command,
  448. String encoding) throws CommandFailedException {
  449. return readPipe(dir, command, encoding, null);
  450. }
  451. /**
  452. * Execute a command and return a single line of output as a String
  453. *
  454. * @param dir
  455. * Working directory for the command
  456. * @param command
  457. * as component array
  458. * @param encoding
  459. * to be used to parse the command's output
  460. * @param env
  461. * Map of environment variables to be merged with those of the
  462. * current process
  463. * @return the one-line output of the command or {@code null} if there is
  464. * none
  465. * @throws org.eclipse.jgit.errors.CommandFailedException
  466. * thrown when the command failed (return code was non-zero)
  467. * @since 4.0
  468. */
  469. @Nullable
  470. protected static String readPipe(File dir, String[] command,
  471. String encoding, Map<String, String> env)
  472. throws CommandFailedException {
  473. final boolean debug = LOG.isDebugEnabled();
  474. try {
  475. if (debug) {
  476. LOG.debug("readpipe " + Arrays.asList(command) + "," //$NON-NLS-1$ //$NON-NLS-2$
  477. + dir);
  478. }
  479. ProcessBuilder pb = new ProcessBuilder(command);
  480. pb.directory(dir);
  481. if (env != null) {
  482. pb.environment().putAll(env);
  483. }
  484. Process p;
  485. try {
  486. p = pb.start();
  487. } catch (IOException e) {
  488. // Process failed to start
  489. throw new CommandFailedException(-1, e.getMessage(), e);
  490. }
  491. p.getOutputStream().close();
  492. GobblerThread gobbler = new GobblerThread(p, command, dir);
  493. gobbler.start();
  494. String r = null;
  495. try (BufferedReader lineRead = new BufferedReader(
  496. new InputStreamReader(p.getInputStream(), encoding))) {
  497. r = lineRead.readLine();
  498. if (debug) {
  499. LOG.debug("readpipe may return '" + r + "'"); //$NON-NLS-1$ //$NON-NLS-2$
  500. LOG.debug("remaining output:\n"); //$NON-NLS-1$
  501. String l;
  502. while ((l = lineRead.readLine()) != null) {
  503. LOG.debug(l);
  504. }
  505. }
  506. }
  507. for (;;) {
  508. try {
  509. int rc = p.waitFor();
  510. gobbler.join();
  511. if (rc == 0 && !gobbler.fail.get()) {
  512. return r;
  513. } else {
  514. if (debug) {
  515. LOG.debug("readpipe rc=" + rc); //$NON-NLS-1$
  516. }
  517. throw new CommandFailedException(rc,
  518. gobbler.errorMessage.get(),
  519. gobbler.exception.get());
  520. }
  521. } catch (InterruptedException ie) {
  522. // Stop bothering me, I have a zombie to reap.
  523. }
  524. }
  525. } catch (IOException e) {
  526. LOG.error("Caught exception in FS.readPipe()", e); //$NON-NLS-1$
  527. }
  528. if (debug) {
  529. LOG.debug("readpipe returns null"); //$NON-NLS-1$
  530. }
  531. return null;
  532. }
  533. private static class GobblerThread extends Thread {
  534. /* The process has 5 seconds to exit after closing stderr */
  535. private static final int PROCESS_EXIT_TIMEOUT = 5;
  536. private final Process p;
  537. private final String desc;
  538. private final String dir;
  539. final AtomicBoolean fail = new AtomicBoolean();
  540. final AtomicReference<String> errorMessage = new AtomicReference<>();
  541. final AtomicReference<Throwable> exception = new AtomicReference<>();
  542. GobblerThread(Process p, String[] command, File dir) {
  543. this.p = p;
  544. this.desc = Arrays.toString(command);
  545. this.dir = Objects.toString(dir);
  546. }
  547. @Override
  548. public void run() {
  549. StringBuilder err = new StringBuilder();
  550. try (InputStream is = p.getErrorStream()) {
  551. int ch;
  552. while ((ch = is.read()) != -1) {
  553. err.append((char) ch);
  554. }
  555. } catch (IOException e) {
  556. if (waitForProcessCompletion(e) && p.exitValue() != 0) {
  557. setError(e, e.getMessage(), p.exitValue());
  558. fail.set(true);
  559. } else {
  560. // ignore. command terminated faster and stream was just closed
  561. // or the process didn't terminate within timeout
  562. }
  563. } finally {
  564. if (waitForProcessCompletion(null) && err.length() > 0) {
  565. setError(null, err.toString(), p.exitValue());
  566. if (p.exitValue() != 0) {
  567. fail.set(true);
  568. }
  569. }
  570. }
  571. }
  572. @SuppressWarnings("boxing")
  573. private boolean waitForProcessCompletion(IOException originalError) {
  574. try {
  575. if (!p.waitFor(PROCESS_EXIT_TIMEOUT, TimeUnit.SECONDS)) {
  576. setError(originalError, MessageFormat.format(
  577. JGitText.get().commandClosedStderrButDidntExit,
  578. desc, PROCESS_EXIT_TIMEOUT), -1);
  579. fail.set(true);
  580. }
  581. } catch (InterruptedException e) {
  582. LOG.error(MessageFormat.format(
  583. JGitText.get().threadInterruptedWhileRunning, desc), e);
  584. }
  585. return false;
  586. }
  587. private void setError(IOException e, String message, int exitCode) {
  588. exception.set(e);
  589. errorMessage.set(MessageFormat.format(
  590. JGitText.get().exceptionCaughtDuringExecutionOfCommand,
  591. desc, dir, Integer.valueOf(exitCode), message));
  592. }
  593. }
  594. /**
  595. * Discover the path to the Git executable.
  596. *
  597. * @return the path to the Git executable or {@code null} if it cannot be
  598. * determined.
  599. * @since 4.0
  600. */
  601. protected abstract File discoverGitExe();
  602. /**
  603. * Discover the path to the system-wide Git configuration file
  604. *
  605. * @return the path to the system-wide Git configuration file or
  606. * {@code null} if it cannot be determined.
  607. * @since 4.0
  608. */
  609. protected File discoverGitSystemConfig() {
  610. File gitExe = discoverGitExe();
  611. if (gitExe == null) {
  612. return null;
  613. }
  614. // Bug 480782: Check if the discovered git executable is JGit CLI
  615. String v;
  616. try {
  617. v = readPipe(gitExe.getParentFile(),
  618. new String[] { "git", "--version" }, //$NON-NLS-1$ //$NON-NLS-2$
  619. Charset.defaultCharset().name());
  620. } catch (CommandFailedException e) {
  621. LOG.warn(e.getMessage());
  622. return null;
  623. }
  624. if (StringUtils.isEmptyOrNull(v)
  625. || (v != null && v.startsWith("jgit"))) { //$NON-NLS-1$
  626. return null;
  627. }
  628. // Trick Git into printing the path to the config file by using "echo"
  629. // as the editor.
  630. Map<String, String> env = new HashMap<>();
  631. env.put("GIT_EDITOR", "echo"); //$NON-NLS-1$ //$NON-NLS-2$
  632. String w;
  633. try {
  634. w = readPipe(gitExe.getParentFile(),
  635. new String[] { "git", "config", "--system", "--edit" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  636. Charset.defaultCharset().name(), env);
  637. } catch (CommandFailedException e) {
  638. LOG.warn(e.getMessage());
  639. return null;
  640. }
  641. if (StringUtils.isEmptyOrNull(w)) {
  642. return null;
  643. }
  644. return new File(w);
  645. }
  646. /**
  647. * Get the currently used path to the system-wide Git configuration file.
  648. *
  649. * @return the currently used path to the system-wide Git configuration file
  650. * or {@code null} if none has been set.
  651. * @since 4.0
  652. */
  653. public File getGitSystemConfig() {
  654. if (gitSystemConfig == null) {
  655. gitSystemConfig = new Holder<>(discoverGitSystemConfig());
  656. }
  657. return gitSystemConfig.value;
  658. }
  659. /**
  660. * Set the path to the system-wide Git configuration file to use.
  661. *
  662. * @param configFile
  663. * the path to the config file.
  664. * @return {@code this}
  665. * @since 4.0
  666. */
  667. public FS setGitSystemConfig(File configFile) {
  668. gitSystemConfig = new Holder<>(configFile);
  669. return this;
  670. }
  671. /**
  672. * Get the parent directory of this file's parent directory
  673. *
  674. * @param grandchild
  675. * a {@link java.io.File} object.
  676. * @return the parent directory of this file's parent directory or
  677. * {@code null} in case there's no grandparent directory
  678. * @since 4.0
  679. */
  680. protected static File resolveGrandparentFile(File grandchild) {
  681. if (grandchild != null) {
  682. File parent = grandchild.getParentFile();
  683. if (parent != null)
  684. return parent.getParentFile();
  685. }
  686. return null;
  687. }
  688. /**
  689. * Check if a file is a symbolic link and read it
  690. *
  691. * @param path
  692. * a {@link java.io.File} object.
  693. * @return target of link or null
  694. * @throws java.io.IOException
  695. * @since 3.0
  696. */
  697. public String readSymLink(File path) throws IOException {
  698. return FileUtils.readSymLink(path);
  699. }
  700. /**
  701. * Whether the path is a symbolic link (and we support these).
  702. *
  703. * @param path
  704. * a {@link java.io.File} object.
  705. * @return true if the path is a symbolic link (and we support these)
  706. * @throws java.io.IOException
  707. * @since 3.0
  708. */
  709. public boolean isSymLink(File path) throws IOException {
  710. return FileUtils.isSymlink(path);
  711. }
  712. /**
  713. * Tests if the path exists, in case of a symbolic link, true even if the
  714. * target does not exist
  715. *
  716. * @param path
  717. * a {@link java.io.File} object.
  718. * @return true if path exists
  719. * @since 3.0
  720. */
  721. public boolean exists(File path) {
  722. return FileUtils.exists(path);
  723. }
  724. /**
  725. * Check if path is a directory. If the OS/JRE supports symbolic links and
  726. * path is a symbolic link to a directory, this method returns false.
  727. *
  728. * @param path
  729. * a {@link java.io.File} object.
  730. * @return true if file is a directory,
  731. * @since 3.0
  732. */
  733. public boolean isDirectory(File path) {
  734. return FileUtils.isDirectory(path);
  735. }
  736. /**
  737. * Examine if path represents a regular file. If the OS/JRE supports
  738. * symbolic links the test returns false if path represents a symbolic link.
  739. *
  740. * @param path
  741. * a {@link java.io.File} object.
  742. * @return true if path represents a regular file
  743. * @since 3.0
  744. */
  745. public boolean isFile(File path) {
  746. return FileUtils.isFile(path);
  747. }
  748. /**
  749. * Whether path is hidden, either starts with . on unix or has the hidden
  750. * attribute in windows
  751. *
  752. * @param path
  753. * a {@link java.io.File} object.
  754. * @return true if path is hidden, either starts with . on unix or has the
  755. * hidden attribute in windows
  756. * @throws java.io.IOException
  757. * @since 3.0
  758. */
  759. public boolean isHidden(File path) throws IOException {
  760. return FileUtils.isHidden(path);
  761. }
  762. /**
  763. * Set the hidden attribute for file whose name starts with a period.
  764. *
  765. * @param path
  766. * a {@link java.io.File} object.
  767. * @param hidden
  768. * whether to set the file hidden
  769. * @throws java.io.IOException
  770. * @since 3.0
  771. */
  772. public void setHidden(File path, boolean hidden) throws IOException {
  773. FileUtils.setHidden(path, hidden);
  774. }
  775. /**
  776. * Create a symbolic link
  777. *
  778. * @param path
  779. * a {@link java.io.File} object.
  780. * @param target
  781. * target path of the symlink
  782. * @throws java.io.IOException
  783. * @since 3.0
  784. */
  785. public void createSymLink(File path, String target) throws IOException {
  786. FileUtils.createSymLink(path, target);
  787. }
  788. /**
  789. * Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
  790. * of this class may take care to provide a safe implementation for this
  791. * even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
  792. *
  793. * @param path
  794. * the file to be created
  795. * @return <code>true</code> if the file was created, <code>false</code> if
  796. * the file already existed
  797. * @throws java.io.IOException
  798. * @since 4.5
  799. */
  800. public boolean createNewFile(File path) throws IOException {
  801. return path.createNewFile();
  802. }
  803. /**
  804. * See
  805. * {@link org.eclipse.jgit.util.FileUtils#relativizePath(String, String, String, boolean)}.
  806. *
  807. * @param base
  808. * The path against which <code>other</code> should be
  809. * relativized.
  810. * @param other
  811. * The path that will be made relative to <code>base</code>.
  812. * @return A relative path that, when resolved against <code>base</code>,
  813. * will yield the original <code>other</code>.
  814. * @see FileUtils#relativizePath(String, String, String, boolean)
  815. * @since 3.7
  816. */
  817. public String relativize(String base, String other) {
  818. return FileUtils.relativizePath(base, other, File.separator, this.isCaseSensitive());
  819. }
  820. /**
  821. * Checks whether the given hook is defined for the given repository, then
  822. * runs it with the given arguments.
  823. * <p>
  824. * The hook's standard output and error streams will be redirected to
  825. * <code>System.out</code> and <code>System.err</code> respectively. The
  826. * hook will have no stdin.
  827. * </p>
  828. *
  829. * @param repository
  830. * The repository for which a hook should be run.
  831. * @param hookName
  832. * The name of the hook to be executed.
  833. * @param args
  834. * Arguments to pass to this hook. Cannot be <code>null</code>,
  835. * but can be an empty array.
  836. * @return The ProcessResult describing this hook's execution.
  837. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  838. * if we fail to run the hook somehow. Causes may include an
  839. * interrupted process or I/O errors.
  840. * @since 4.0
  841. */
  842. public ProcessResult runHookIfPresent(Repository repository,
  843. final String hookName,
  844. String[] args) throws JGitInternalException {
  845. return runHookIfPresent(repository, hookName, args, System.out, System.err,
  846. null);
  847. }
  848. /**
  849. * Checks whether the given hook is defined for the given repository, then
  850. * runs it with the given arguments.
  851. *
  852. * @param repository
  853. * The repository for which a hook should be run.
  854. * @param hookName
  855. * The name of the hook to be executed.
  856. * @param args
  857. * Arguments to pass to this hook. Cannot be <code>null</code>,
  858. * but can be an empty array.
  859. * @param outRedirect
  860. * A print stream on which to redirect the hook's stdout. Can be
  861. * <code>null</code>, in which case the hook's standard output
  862. * will be lost.
  863. * @param errRedirect
  864. * A print stream on which to redirect the hook's stderr. Can be
  865. * <code>null</code>, in which case the hook's standard error
  866. * will be lost.
  867. * @param stdinArgs
  868. * A string to pass on to the standard input of the hook. May be
  869. * <code>null</code>.
  870. * @return The ProcessResult describing this hook's execution.
  871. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  872. * if we fail to run the hook somehow. Causes may include an
  873. * interrupted process or I/O errors.
  874. * @since 4.0
  875. */
  876. public ProcessResult runHookIfPresent(Repository repository,
  877. final String hookName,
  878. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  879. String stdinArgs) throws JGitInternalException {
  880. return new ProcessResult(Status.NOT_SUPPORTED);
  881. }
  882. /**
  883. * See
  884. * {@link #runHookIfPresent(Repository, String, String[], PrintStream, PrintStream, String)}
  885. * . Should only be called by FS supporting shell scripts execution.
  886. *
  887. * @param repository
  888. * The repository for which a hook should be run.
  889. * @param hookName
  890. * The name of the hook to be executed.
  891. * @param args
  892. * Arguments to pass to this hook. Cannot be <code>null</code>,
  893. * but can be an empty array.
  894. * @param outRedirect
  895. * A print stream on which to redirect the hook's stdout. Can be
  896. * <code>null</code>, in which case the hook's standard output
  897. * will be lost.
  898. * @param errRedirect
  899. * A print stream on which to redirect the hook's stderr. Can be
  900. * <code>null</code>, in which case the hook's standard error
  901. * will be lost.
  902. * @param stdinArgs
  903. * A string to pass on to the standard input of the hook. May be
  904. * <code>null</code>.
  905. * @return The ProcessResult describing this hook's execution.
  906. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  907. * if we fail to run the hook somehow. Causes may include an
  908. * interrupted process or I/O errors.
  909. * @since 4.0
  910. */
  911. protected ProcessResult internalRunHookIfPresent(Repository repository,
  912. final String hookName, String[] args, PrintStream outRedirect,
  913. PrintStream errRedirect, String stdinArgs)
  914. throws JGitInternalException {
  915. final File hookFile = findHook(repository, hookName);
  916. if (hookFile == null)
  917. return new ProcessResult(Status.NOT_PRESENT);
  918. final String hookPath = hookFile.getAbsolutePath();
  919. final File runDirectory;
  920. if (repository.isBare())
  921. runDirectory = repository.getDirectory();
  922. else
  923. runDirectory = repository.getWorkTree();
  924. final String cmd = relativize(runDirectory.getAbsolutePath(),
  925. hookPath);
  926. ProcessBuilder hookProcess = runInShell(cmd, args);
  927. hookProcess.directory(runDirectory);
  928. try {
  929. return new ProcessResult(runProcess(hookProcess, outRedirect,
  930. errRedirect, stdinArgs), Status.OK);
  931. } catch (IOException e) {
  932. throw new JGitInternalException(MessageFormat.format(
  933. JGitText.get().exceptionCaughtDuringExecutionOfHook,
  934. hookName), e);
  935. } catch (InterruptedException e) {
  936. throw new JGitInternalException(MessageFormat.format(
  937. JGitText.get().exceptionHookExecutionInterrupted,
  938. hookName), e);
  939. }
  940. }
  941. /**
  942. * Tries to find a hook matching the given one in the given repository.
  943. *
  944. * @param repository
  945. * The repository within which to find a hook.
  946. * @param hookName
  947. * The name of the hook we're trying to find.
  948. * @return The {@link java.io.File} containing this particular hook if it
  949. * exists in the given repository, <code>null</code> otherwise.
  950. * @since 4.0
  951. */
  952. public File findHook(Repository repository, final String hookName) {
  953. File gitDir = repository.getDirectory();
  954. if (gitDir == null)
  955. return null;
  956. final File hookFile = new File(new File(gitDir,
  957. Constants.HOOKS), hookName);
  958. return hookFile.isFile() ? hookFile : null;
  959. }
  960. /**
  961. * Runs the given process until termination, clearing its stdout and stderr
  962. * streams on-the-fly.
  963. *
  964. * @param processBuilder
  965. * The process builder configured for this process.
  966. * @param outRedirect
  967. * A OutputStream on which to redirect the processes stdout. Can
  968. * be <code>null</code>, in which case the processes standard
  969. * output will be lost.
  970. * @param errRedirect
  971. * A OutputStream on which to redirect the processes stderr. Can
  972. * be <code>null</code>, in which case the processes standard
  973. * error will be lost.
  974. * @param stdinArgs
  975. * A string to pass on to the standard input of the hook. Can be
  976. * <code>null</code>.
  977. * @return the exit value of this process.
  978. * @throws java.io.IOException
  979. * if an I/O error occurs while executing this process.
  980. * @throws java.lang.InterruptedException
  981. * if the current thread is interrupted while waiting for the
  982. * process to end.
  983. * @since 4.2
  984. */
  985. public int runProcess(ProcessBuilder processBuilder,
  986. OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
  987. throws IOException, InterruptedException {
  988. InputStream in = (stdinArgs == null) ? null : new ByteArrayInputStream(
  989. stdinArgs.getBytes(Constants.CHARACTER_ENCODING));
  990. return runProcess(processBuilder, outRedirect, errRedirect, in);
  991. }
  992. /**
  993. * Runs the given process until termination, clearing its stdout and stderr
  994. * streams on-the-fly.
  995. *
  996. * @param processBuilder
  997. * The process builder configured for this process.
  998. * @param outRedirect
  999. * An OutputStream on which to redirect the processes stdout. Can
  1000. * be <code>null</code>, in which case the processes standard
  1001. * output will be lost.
  1002. * @param errRedirect
  1003. * An OutputStream on which to redirect the processes stderr. Can
  1004. * be <code>null</code>, in which case the processes standard
  1005. * error will be lost.
  1006. * @param inRedirect
  1007. * An InputStream from which to redirect the processes stdin. Can
  1008. * be <code>null</code>, in which case the process doesn't get
  1009. * any data over stdin. It is assumed that the whole InputStream
  1010. * will be consumed by the process. The method will close the
  1011. * inputstream after all bytes are read.
  1012. * @return the return code of this process.
  1013. * @throws java.io.IOException
  1014. * if an I/O error occurs while executing this process.
  1015. * @throws java.lang.InterruptedException
  1016. * if the current thread is interrupted while waiting for the
  1017. * process to end.
  1018. * @since 4.2
  1019. */
  1020. public int runProcess(ProcessBuilder processBuilder,
  1021. OutputStream outRedirect, OutputStream errRedirect,
  1022. InputStream inRedirect) throws IOException,
  1023. InterruptedException {
  1024. final ExecutorService executor = Executors.newFixedThreadPool(2);
  1025. Process process = null;
  1026. // We'll record the first I/O exception that occurs, but keep on trying
  1027. // to dispose of our open streams and file handles
  1028. IOException ioException = null;
  1029. try {
  1030. process = processBuilder.start();
  1031. executor.execute(
  1032. new StreamGobbler(process.getErrorStream(), errRedirect));
  1033. executor.execute(
  1034. new StreamGobbler(process.getInputStream(), outRedirect));
  1035. OutputStream outputStream = process.getOutputStream();
  1036. if (inRedirect != null) {
  1037. new StreamGobbler(inRedirect, outputStream).copy();
  1038. }
  1039. try {
  1040. outputStream.close();
  1041. } catch (IOException e) {
  1042. // When the process exits before consuming the input, the OutputStream
  1043. // is replaced with the null output stream. This null output stream
  1044. // throws IOException for all write calls. When StreamGobbler fails to
  1045. // flush the buffer because of this, this close call tries to flush it
  1046. // again. This causes another IOException. Since we ignore the
  1047. // IOException in StreamGobbler, we also ignore the exception here.
  1048. }
  1049. return process.waitFor();
  1050. } catch (IOException e) {
  1051. ioException = e;
  1052. } finally {
  1053. shutdownAndAwaitTermination(executor);
  1054. if (process != null) {
  1055. try {
  1056. process.waitFor();
  1057. } catch (InterruptedException e) {
  1058. // Thrown by the outer try.
  1059. // Swallow this one to carry on our cleanup, and clear the
  1060. // interrupted flag (processes throw the exception without
  1061. // clearing the flag).
  1062. Thread.interrupted();
  1063. }
  1064. // A process doesn't clean its own resources even when destroyed
  1065. // Explicitly try and close all three streams, preserving the
  1066. // outer I/O exception if any.
  1067. if (inRedirect != null) {
  1068. inRedirect.close();
  1069. }
  1070. try {
  1071. process.getErrorStream().close();
  1072. } catch (IOException e) {
  1073. ioException = ioException != null ? ioException : e;
  1074. }
  1075. try {
  1076. process.getInputStream().close();
  1077. } catch (IOException e) {
  1078. ioException = ioException != null ? ioException : e;
  1079. }
  1080. try {
  1081. process.getOutputStream().close();
  1082. } catch (IOException e) {
  1083. ioException = ioException != null ? ioException : e;
  1084. }
  1085. process.destroy();
  1086. }
  1087. }
  1088. // We can only be here if the outer try threw an IOException.
  1089. throw ioException;
  1090. }
  1091. /**
  1092. * Shuts down an {@link ExecutorService} in two phases, first by calling
  1093. * {@link ExecutorService#shutdown() shutdown} to reject incoming tasks, and
  1094. * then calling {@link ExecutorService#shutdownNow() shutdownNow}, if
  1095. * necessary, to cancel any lingering tasks. Returns true if the pool has
  1096. * been properly shutdown, false otherwise.
  1097. * <p>
  1098. *
  1099. * @param pool
  1100. * the pool to shutdown
  1101. * @return <code>true</code> if the pool has been properly shutdown,
  1102. * <code>false</code> otherwise.
  1103. */
  1104. private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
  1105. boolean hasShutdown = true;
  1106. pool.shutdown(); // Disable new tasks from being submitted
  1107. try {
  1108. // Wait a while for existing tasks to terminate
  1109. if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
  1110. pool.shutdownNow(); // Cancel currently executing tasks
  1111. // Wait a while for tasks to respond to being canceled
  1112. if (!pool.awaitTermination(60, TimeUnit.SECONDS))
  1113. hasShutdown = false;
  1114. }
  1115. } catch (InterruptedException ie) {
  1116. // (Re-)Cancel if current thread also interrupted
  1117. pool.shutdownNow();
  1118. // Preserve interrupt status
  1119. Thread.currentThread().interrupt();
  1120. hasShutdown = false;
  1121. }
  1122. return hasShutdown;
  1123. }
  1124. /**
  1125. * Initialize a ProcessBuilder to run a command using the system shell.
  1126. *
  1127. * @param cmd
  1128. * command to execute. This string should originate from the
  1129. * end-user, and thus is platform specific.
  1130. * @param args
  1131. * arguments to pass to command. These should be protected from
  1132. * shell evaluation.
  1133. * @return a partially completed process builder. Caller should finish
  1134. * populating directory, environment, and then start the process.
  1135. */
  1136. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  1137. /**
  1138. * Execute a command defined by a {@link java.lang.ProcessBuilder}.
  1139. *
  1140. * @param pb
  1141. * The command to be executed
  1142. * @param in
  1143. * The standard input stream passed to the process
  1144. * @return The result of the executed command
  1145. * @throws java.lang.InterruptedException
  1146. * @throws java.io.IOException
  1147. * @since 4.2
  1148. */
  1149. public ExecutionResult execute(ProcessBuilder pb, InputStream in)
  1150. throws IOException, InterruptedException {
  1151. TemporaryBuffer stdout = new TemporaryBuffer.LocalFile(null);
  1152. TemporaryBuffer stderr = new TemporaryBuffer.Heap(1024, 1024 * 1024);
  1153. try {
  1154. int rc = runProcess(pb, stdout, stderr, in);
  1155. return new ExecutionResult(stdout, stderr, rc);
  1156. } finally {
  1157. stdout.close();
  1158. stderr.close();
  1159. }
  1160. }
  1161. private static class Holder<V> {
  1162. final V value;
  1163. Holder(V value) {
  1164. this.value = value;
  1165. }
  1166. }
  1167. /**
  1168. * File attributes we typically care for.
  1169. *
  1170. * @since 3.3
  1171. */
  1172. public static class Attributes {
  1173. /**
  1174. * @return true if this are the attributes of a directory
  1175. */
  1176. public boolean isDirectory() {
  1177. return isDirectory;
  1178. }
  1179. /**
  1180. * @return true if this are the attributes of an executable file
  1181. */
  1182. public boolean isExecutable() {
  1183. return isExecutable;
  1184. }
  1185. /**
  1186. * @return true if this are the attributes of a symbolic link
  1187. */
  1188. public boolean isSymbolicLink() {
  1189. return isSymbolicLink;
  1190. }
  1191. /**
  1192. * @return true if this are the attributes of a regular file
  1193. */
  1194. public boolean isRegularFile() {
  1195. return isRegularFile;
  1196. }
  1197. /**
  1198. * @return the time when the file was created
  1199. */
  1200. public long getCreationTime() {
  1201. return creationTime;
  1202. }
  1203. /**
  1204. * @return the time (milliseconds since 1970-01-01) when this object was
  1205. * last modified
  1206. */
  1207. public long getLastModifiedTime() {
  1208. return lastModifiedTime;
  1209. }
  1210. private final boolean isDirectory;
  1211. private final boolean isSymbolicLink;
  1212. private final boolean isRegularFile;
  1213. private final long creationTime;
  1214. private final long lastModifiedTime;
  1215. private final boolean isExecutable;
  1216. private final File file;
  1217. private final boolean exists;
  1218. /**
  1219. * file length
  1220. */
  1221. protected long length = -1;
  1222. final FS fs;
  1223. Attributes(FS fs, File file, boolean exists, boolean isDirectory,
  1224. boolean isExecutable, boolean isSymbolicLink,
  1225. boolean isRegularFile, long creationTime,
  1226. long lastModifiedTime, long length) {
  1227. this.fs = fs;
  1228. this.file = file;
  1229. this.exists = exists;
  1230. this.isDirectory = isDirectory;
  1231. this.isExecutable = isExecutable;
  1232. this.isSymbolicLink = isSymbolicLink;
  1233. this.isRegularFile = isRegularFile;
  1234. this.creationTime = creationTime;
  1235. this.lastModifiedTime = lastModifiedTime;
  1236. this.length = length;
  1237. }
  1238. /**
  1239. * Constructor when there are issues with reading. All attributes except
  1240. * given will be set to the default values.
  1241. *
  1242. * @param fs
  1243. * @param path
  1244. */
  1245. public Attributes(File path, FS fs) {
  1246. this(fs, path, false, false, false, false, false, 0L, 0L, 0L);
  1247. }
  1248. /**
  1249. * @return length of this file object
  1250. */
  1251. public long getLength() {
  1252. if (length == -1)
  1253. return length = file.length();
  1254. return length;
  1255. }
  1256. /**
  1257. * @return the filename
  1258. */
  1259. public String getName() {
  1260. return file.getName();
  1261. }
  1262. /**
  1263. * @return the file the attributes apply to
  1264. */
  1265. public File getFile() {
  1266. return file;
  1267. }
  1268. boolean exists() {
  1269. return exists;
  1270. }
  1271. }
  1272. /**
  1273. * Get the file attributes we care for.
  1274. *
  1275. * @param path
  1276. * a {@link java.io.File} object.
  1277. * @return the file attributes we care for.
  1278. * @since 3.3
  1279. */
  1280. public Attributes getAttributes(File path) {
  1281. boolean isDirectory = isDirectory(path);
  1282. boolean isFile = !isDirectory && path.isFile();
  1283. assert path.exists() == isDirectory || isFile;
  1284. boolean exists = isDirectory || isFile;
  1285. boolean canExecute = exists && !isDirectory && canExecute(path);
  1286. boolean isSymlink = false;
  1287. long lastModified = exists ? path.lastModified() : 0L;
  1288. long createTime = 0L;
  1289. return new Attributes(this, path, exists, isDirectory, canExecute,
  1290. isSymlink, isFile, createTime, lastModified, -1);
  1291. }
  1292. /**
  1293. * Normalize the unicode path to composed form.
  1294. *
  1295. * @param file
  1296. * a {@link java.io.File} object.
  1297. * @return NFC-format File
  1298. * @since 3.3
  1299. */
  1300. public File normalize(File file) {
  1301. return file;
  1302. }
  1303. /**
  1304. * Normalize the unicode path to composed form.
  1305. *
  1306. * @param name
  1307. * path name
  1308. * @return NFC-format string
  1309. * @since 3.3
  1310. */
  1311. public String normalize(String name) {
  1312. return name;
  1313. }
  1314. /**
  1315. * This runnable will consume an input stream's content into an output
  1316. * stream as soon as it gets available.
  1317. * <p>
  1318. * Typically used to empty processes' standard output and error, preventing
  1319. * them to choke.
  1320. * </p>
  1321. * <p>
  1322. * <b>Note</b> that a {@link StreamGobbler} will never close either of its
  1323. * streams.
  1324. * </p>
  1325. */
  1326. private static class StreamGobbler implements Runnable {
  1327. private InputStream in;
  1328. private OutputStream out;
  1329. public StreamGobbler(InputStream stream, OutputStream output) {
  1330. this.in = stream;
  1331. this.out = output;
  1332. }
  1333. @Override
  1334. public void run() {
  1335. try {
  1336. copy();
  1337. } catch (IOException e) {
  1338. // Do nothing on read failure; leave streams open.
  1339. }
  1340. }
  1341. void copy() throws IOException {
  1342. boolean writeFailure = false;
  1343. byte buffer[] = new byte[4096];
  1344. int readBytes;
  1345. while ((readBytes = in.read(buffer)) != -1) {
  1346. // Do not try to write again after a failure, but keep
  1347. // reading as long as possible to prevent the input stream
  1348. // from choking.
  1349. if (!writeFailure && out != null) {
  1350. try {
  1351. out.write(buffer, 0, readBytes);
  1352. out.flush();
  1353. } catch (IOException e) {
  1354. writeFailure = true;
  1355. }
  1356. }
  1357. }
  1358. }
  1359. }
  1360. }