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

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