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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182
  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 static java.nio.charset.StandardCharsets.UTF_8;
  45. import static java.time.Instant.EPOCH;
  46. import java.io.BufferedReader;
  47. import java.io.ByteArrayInputStream;
  48. import java.io.Closeable;
  49. import java.io.File;
  50. import java.io.IOException;
  51. import java.io.InputStream;
  52. import java.io.InputStreamReader;
  53. import java.io.OutputStream;
  54. import java.io.OutputStreamWriter;
  55. import java.io.PrintStream;
  56. import java.io.Writer;
  57. import java.nio.charset.Charset;
  58. import java.nio.file.AccessDeniedException;
  59. import java.nio.file.FileStore;
  60. import java.nio.file.Files;
  61. import java.nio.file.Path;
  62. import java.nio.file.attribute.BasicFileAttributes;
  63. import java.nio.file.attribute.FileTime;
  64. import java.security.AccessController;
  65. import java.security.PrivilegedAction;
  66. import java.text.MessageFormat;
  67. import java.time.Duration;
  68. import java.time.Instant;
  69. import java.util.ArrayList;
  70. import java.util.Arrays;
  71. import java.util.HashMap;
  72. import java.util.Map;
  73. import java.util.Objects;
  74. import java.util.Optional;
  75. import java.util.UUID;
  76. import java.util.concurrent.CancellationException;
  77. import java.util.concurrent.CompletableFuture;
  78. import java.util.concurrent.ConcurrentHashMap;
  79. import java.util.concurrent.ExecutionException;
  80. import java.util.concurrent.ExecutorService;
  81. import java.util.concurrent.Executors;
  82. import java.util.concurrent.TimeUnit;
  83. import java.util.concurrent.TimeoutException;
  84. import java.util.concurrent.atomic.AtomicBoolean;
  85. import java.util.concurrent.atomic.AtomicReference;
  86. import java.util.concurrent.locks.Lock;
  87. import java.util.concurrent.locks.ReentrantLock;
  88. import org.eclipse.jgit.annotations.NonNull;
  89. import org.eclipse.jgit.annotations.Nullable;
  90. import org.eclipse.jgit.api.errors.JGitInternalException;
  91. import org.eclipse.jgit.errors.CommandFailedException;
  92. import org.eclipse.jgit.errors.ConfigInvalidException;
  93. import org.eclipse.jgit.errors.LockFailedException;
  94. import org.eclipse.jgit.internal.JGitText;
  95. import org.eclipse.jgit.internal.storage.file.FileSnapshot;
  96. import org.eclipse.jgit.lib.ConfigConstants;
  97. import org.eclipse.jgit.lib.Constants;
  98. import org.eclipse.jgit.lib.Repository;
  99. import org.eclipse.jgit.storage.file.FileBasedConfig;
  100. import org.eclipse.jgit.treewalk.FileTreeIterator.FileEntry;
  101. import org.eclipse.jgit.treewalk.FileTreeIterator.FileModeStrategy;
  102. import org.eclipse.jgit.treewalk.WorkingTreeIterator.Entry;
  103. import org.eclipse.jgit.util.ProcessResult.Status;
  104. import org.slf4j.Logger;
  105. import org.slf4j.LoggerFactory;
  106. /**
  107. * Abstraction to support various file system operations not in Java.
  108. */
  109. public abstract class FS {
  110. private static final Logger LOG = LoggerFactory.getLogger(FS.class);
  111. /**
  112. * An empty array of entries, suitable as a return value for
  113. * {@link #list(File, FileModeStrategy)}.
  114. *
  115. * @since 5.0
  116. */
  117. protected static final Entry[] NO_ENTRIES = {};
  118. /**
  119. * This class creates FS instances. It will be overridden by a Java7 variant
  120. * if such can be detected in {@link #detect(Boolean)}.
  121. *
  122. * @since 3.0
  123. */
  124. public static class FSFactory {
  125. /**
  126. * Constructor
  127. */
  128. protected FSFactory() {
  129. // empty
  130. }
  131. /**
  132. * Detect the file system
  133. *
  134. * @param cygwinUsed
  135. * @return FS instance
  136. */
  137. public FS detect(Boolean cygwinUsed) {
  138. if (SystemReader.getInstance().isWindows()) {
  139. if (cygwinUsed == null)
  140. cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
  141. if (cygwinUsed.booleanValue())
  142. return new FS_Win32_Cygwin();
  143. else
  144. return new FS_Win32();
  145. } else {
  146. return new FS_POSIX();
  147. }
  148. }
  149. }
  150. /**
  151. * Result of an executed process. The caller is responsible to close the
  152. * contained {@link TemporaryBuffer}s
  153. *
  154. * @since 4.2
  155. */
  156. public static class ExecutionResult {
  157. private TemporaryBuffer stdout;
  158. private TemporaryBuffer stderr;
  159. private int rc;
  160. /**
  161. * @param stdout
  162. * @param stderr
  163. * @param rc
  164. */
  165. public ExecutionResult(TemporaryBuffer stdout, TemporaryBuffer stderr,
  166. int rc) {
  167. this.stdout = stdout;
  168. this.stderr = stderr;
  169. this.rc = rc;
  170. }
  171. /**
  172. * @return buffered standard output stream
  173. */
  174. public TemporaryBuffer getStdout() {
  175. return stdout;
  176. }
  177. /**
  178. * @return buffered standard error stream
  179. */
  180. public TemporaryBuffer getStderr() {
  181. return stderr;
  182. }
  183. /**
  184. * @return the return code of the process
  185. */
  186. public int getRc() {
  187. return rc;
  188. }
  189. }
  190. /**
  191. * Attributes of FileStores on this system
  192. *
  193. * @since 5.1.9
  194. */
  195. public final static class FileStoreAttributes {
  196. private static final Duration UNDEFINED_DURATION = Duration
  197. .ofNanos(Long.MAX_VALUE);
  198. /**
  199. * Fallback filesystem timestamp resolution. The worst case timestamp
  200. * resolution on FAT filesystems is 2 seconds.
  201. */
  202. public static final Duration FALLBACK_TIMESTAMP_RESOLUTION = Duration
  203. .ofMillis(2000);
  204. /**
  205. * Fallback FileStore attributes used when we can't measure the
  206. * filesystem timestamp resolution. The last modified time granularity
  207. * of FAT filesystems is 2 seconds.
  208. */
  209. public static final FileStoreAttributes FALLBACK_FILESTORE_ATTRIBUTES = new FileStoreAttributes(
  210. FALLBACK_TIMESTAMP_RESOLUTION);
  211. private static final Map<FileStore, FileStoreAttributes> attributeCache = new ConcurrentHashMap<>();
  212. private static final SimpleLruCache<Path, FileStoreAttributes> attrCacheByPath = new SimpleLruCache<>(
  213. 100, 0.2f);
  214. private static AtomicBoolean background = new AtomicBoolean();
  215. private static Map<FileStore, Lock> locks = new ConcurrentHashMap<>();
  216. private static void setBackground(boolean async) {
  217. background.set(async);
  218. }
  219. private static final String javaVersionPrefix = System
  220. .getProperty("java.vendor") + '|' //$NON-NLS-1$
  221. + System.getProperty("java.version") + '|'; //$NON-NLS-1$
  222. private static final Duration FALLBACK_MIN_RACY_INTERVAL = Duration
  223. .ofMillis(10);
  224. /**
  225. * Configures size and purge factor of the path-based cache for file
  226. * system attributes. Caching of file system attributes avoids recurring
  227. * lookup of @{code FileStore} of files which may be expensive on some
  228. * platforms.
  229. *
  230. * @param maxSize
  231. * maximum size of the cache, default is 100
  232. * @param purgeFactor
  233. * when the size of the map reaches maxSize the oldest
  234. * entries will be purged to free up some space for new
  235. * entries, {@code purgeFactor} is the fraction of
  236. * {@code maxSize} to purge when this happens
  237. * @since 5.1.9
  238. */
  239. public static void configureAttributesPathCache(int maxSize,
  240. float purgeFactor) {
  241. FileStoreAttributes.attrCacheByPath.configure(maxSize, purgeFactor);
  242. }
  243. /**
  244. * Get the FileStoreAttributes for the given FileStore
  245. *
  246. * @param path
  247. * file residing in the FileStore to get attributes for
  248. * @return FileStoreAttributes for the given path.
  249. */
  250. public static FileStoreAttributes get(Path path) {
  251. path = path.toAbsolutePath();
  252. Path dir = Files.isDirectory(path) ? path : path.getParent();
  253. FileStoreAttributes cached = attrCacheByPath.get(dir);
  254. if (cached != null) {
  255. return cached;
  256. }
  257. FileStoreAttributes attrs = getFileStoreAttributes(dir);
  258. attrCacheByPath.put(dir, attrs);
  259. return attrs;
  260. }
  261. private static FileStoreAttributes getFileStoreAttributes(Path dir) {
  262. FileStore s;
  263. try {
  264. if (Files.exists(dir)) {
  265. s = Files.getFileStore(dir);
  266. FileStoreAttributes c = attributeCache.get(s);
  267. if (c != null) {
  268. return c;
  269. }
  270. if (!Files.isWritable(dir)) {
  271. // cannot measure resolution in a read-only directory
  272. LOG.debug(
  273. "{}: cannot measure timestamp resolution in read-only directory {}", //$NON-NLS-1$
  274. Thread.currentThread(), dir);
  275. return FALLBACK_FILESTORE_ATTRIBUTES;
  276. }
  277. } else {
  278. // cannot determine FileStore of an unborn directory
  279. LOG.debug(
  280. "{}: cannot measure timestamp resolution of unborn directory {}", //$NON-NLS-1$
  281. Thread.currentThread(), dir);
  282. return FALLBACK_FILESTORE_ATTRIBUTES;
  283. }
  284. CompletableFuture<Optional<FileStoreAttributes>> f = CompletableFuture
  285. .supplyAsync(() -> {
  286. Lock lock = locks.computeIfAbsent(s,
  287. l -> new ReentrantLock());
  288. if (!lock.tryLock()) {
  289. LOG.debug(
  290. "{}: couldn't get lock to measure timestamp resolution in {}", //$NON-NLS-1$
  291. Thread.currentThread(), dir);
  292. return Optional.empty();
  293. }
  294. Optional<FileStoreAttributes> attributes = Optional
  295. .empty();
  296. try {
  297. // Some earlier future might have set the value
  298. // and removed itself since we checked for the
  299. // value above. Hence check cache again.
  300. FileStoreAttributes c = attributeCache
  301. .get(s);
  302. if (c != null) {
  303. return Optional.of(c);
  304. }
  305. attributes = readFromConfig(s);
  306. if (attributes.isPresent()) {
  307. attributeCache.put(s, attributes.get());
  308. return attributes;
  309. }
  310. Optional<Duration> resolution = measureFsTimestampResolution(
  311. s, dir);
  312. if (resolution.isPresent()) {
  313. c = new FileStoreAttributes(
  314. resolution.get());
  315. attributeCache.put(s, c);
  316. // for high timestamp resolution measure
  317. // minimal racy interval
  318. if (c.fsTimestampResolution
  319. .toNanos() < 100_000_000L) {
  320. c.minimalRacyInterval = measureMinimalRacyInterval(
  321. dir);
  322. }
  323. if (LOG.isDebugEnabled()) {
  324. LOG.debug(c.toString());
  325. }
  326. saveToConfig(s, c);
  327. }
  328. attributes = Optional.of(c);
  329. } finally {
  330. lock.unlock();
  331. locks.remove(s);
  332. }
  333. return attributes;
  334. });
  335. f.exceptionally(e -> {
  336. LOG.error(e.getLocalizedMessage(), e);
  337. return Optional.empty();
  338. });
  339. // even if measuring in background wait a little - if the result
  340. // arrives, it's better than returning the large fallback
  341. Optional<FileStoreAttributes> d = background.get() ? f.get(
  342. 100, TimeUnit.MILLISECONDS) : f.get();
  343. if (d.isPresent()) {
  344. return d.get();
  345. }
  346. // return fallback until measurement is finished
  347. } catch (IOException | InterruptedException
  348. | ExecutionException | CancellationException e) {
  349. LOG.error(e.getMessage(), e);
  350. } catch (TimeoutException | SecurityException e) {
  351. // use fallback
  352. }
  353. LOG.debug("{}: use fallback timestamp resolution for directory {}", //$NON-NLS-1$
  354. Thread.currentThread(), dir);
  355. return FALLBACK_FILESTORE_ATTRIBUTES;
  356. }
  357. @SuppressWarnings("boxing")
  358. private static Duration measureMinimalRacyInterval(Path dir) {
  359. LOG.debug("{}: start measure minimal racy interval in {}", //$NON-NLS-1$
  360. Thread.currentThread(), dir);
  361. int n = 0;
  362. int failures = 0;
  363. long racyNanos = 0;
  364. ArrayList<Long> deltas = new ArrayList<>();
  365. Path probe = dir.resolve(".probe-" + UUID.randomUUID()); //$NON-NLS-1$
  366. Instant end = Instant.now().plusSeconds(3);
  367. try {
  368. Files.createFile(probe);
  369. do {
  370. n++;
  371. write(probe, "a"); //$NON-NLS-1$
  372. FileSnapshot snapshot = FileSnapshot.save(probe.toFile());
  373. read(probe);
  374. write(probe, "b"); //$NON-NLS-1$
  375. if (!snapshot.isModified(probe.toFile())) {
  376. deltas.add(Long.valueOf(snapshot.lastDelta()));
  377. racyNanos = snapshot.lastRacyThreshold();
  378. failures++;
  379. }
  380. } while (Instant.now().compareTo(end) < 0);
  381. } catch (IOException e) {
  382. LOG.error(e.getMessage(), e);
  383. return FALLBACK_MIN_RACY_INTERVAL;
  384. } finally {
  385. deleteProbe(probe);
  386. }
  387. if (failures > 0) {
  388. Stats stats = new Stats();
  389. for (Long d : deltas) {
  390. stats.add(d);
  391. }
  392. LOG.debug(
  393. "delta [ns] since modification FileSnapshot failed to detect\n" //$NON-NLS-1$
  394. + "count, failures, racy limit [ns], delta min [ns]," //$NON-NLS-1$
  395. + " delta max [ns], delta avg [ns]," //$NON-NLS-1$
  396. + " delta stddev [ns]\n" //$NON-NLS-1$
  397. + "{}, {}, {}, {}, {}, {}, {}", //$NON-NLS-1$
  398. n, failures, racyNanos, stats.min(), stats.max(),
  399. stats.avg(), stats.stddev());
  400. return Duration
  401. .ofNanos(Double.valueOf(stats.max()).longValue());
  402. }
  403. // since no failures occurred using the measured filesystem
  404. // timestamp resolution there is no need for minimal racy interval
  405. LOG.debug("{}: no failures when measuring minimal racy interval", //$NON-NLS-1$
  406. Thread.currentThread());
  407. return Duration.ZERO;
  408. }
  409. private static void write(Path p, String body) throws IOException {
  410. FileUtils.mkdirs(p.getParent().toFile(), true);
  411. try (Writer w = new OutputStreamWriter(Files.newOutputStream(p),
  412. UTF_8)) {
  413. w.write(body);
  414. }
  415. }
  416. private static String read(Path p) throws IOException {
  417. final byte[] body = IO.readFully(p.toFile());
  418. return new String(body, 0, body.length, UTF_8);
  419. }
  420. private static Optional<Duration> measureFsTimestampResolution(
  421. FileStore s, Path dir) {
  422. LOG.debug("{}: start measure timestamp resolution {} in {}", //$NON-NLS-1$
  423. Thread.currentThread(), s, dir);
  424. Path probe = dir.resolve(".probe-" + UUID.randomUUID()); //$NON-NLS-1$
  425. try {
  426. Files.createFile(probe);
  427. FileTime t1 = Files.getLastModifiedTime(probe);
  428. FileTime t2 = t1;
  429. Instant t1i = t1.toInstant();
  430. for (long i = 1; t2.compareTo(t1) <= 0; i += 1 + i / 20) {
  431. Files.setLastModifiedTime(probe,
  432. FileTime.from(t1i.plusNanos(i * 1000)));
  433. t2 = Files.getLastModifiedTime(probe);
  434. }
  435. Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant());
  436. Duration clockResolution = measureClockResolution();
  437. fsResolution = fsResolution.plus(clockResolution);
  438. LOG.debug("{}: end measure timestamp resolution {} in {}", //$NON-NLS-1$
  439. Thread.currentThread(), s, dir);
  440. return Optional.of(fsResolution);
  441. } catch (AccessDeniedException e) {
  442. LOG.warn(e.getLocalizedMessage(), e); // see bug 548648
  443. } catch (IOException e) {
  444. LOG.error(e.getLocalizedMessage(), e);
  445. } finally {
  446. deleteProbe(probe);
  447. }
  448. return Optional.empty();
  449. }
  450. private static Duration measureClockResolution() {
  451. Duration clockResolution = Duration.ZERO;
  452. for (int i = 0; i < 10; i++) {
  453. Instant t1 = Instant.now();
  454. Instant t2 = t1;
  455. while (t2.compareTo(t1) <= 0) {
  456. t2 = Instant.now();
  457. }
  458. Duration r = Duration.between(t1, t2);
  459. if (r.compareTo(clockResolution) > 0) {
  460. clockResolution = r;
  461. }
  462. }
  463. return clockResolution;
  464. }
  465. private static void deleteProbe(Path probe) {
  466. try {
  467. FileUtils.delete(probe.toFile(),
  468. FileUtils.SKIP_MISSING | FileUtils.RETRY);
  469. } catch (IOException e) {
  470. LOG.error(e.getMessage(), e);
  471. }
  472. }
  473. private static Optional<FileStoreAttributes> readFromConfig(
  474. FileStore s) {
  475. FileBasedConfig userConfig = SystemReader.getInstance()
  476. .openUserConfig(null, FS.DETECTED);
  477. try {
  478. userConfig.load(false);
  479. } catch (IOException e) {
  480. LOG.error(MessageFormat.format(JGitText.get().readConfigFailed,
  481. userConfig.getFile().getAbsolutePath()), e);
  482. } catch (ConfigInvalidException e) {
  483. LOG.error(MessageFormat.format(
  484. JGitText.get().repositoryConfigFileInvalid,
  485. userConfig.getFile().getAbsolutePath(),
  486. e.getMessage()));
  487. }
  488. String key = getConfigKey(s);
  489. Duration resolution = Duration.ofNanos(userConfig.getTimeUnit(
  490. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  491. ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION,
  492. UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS));
  493. if (UNDEFINED_DURATION.equals(resolution)) {
  494. return Optional.empty();
  495. }
  496. Duration minRacyThreshold = Duration.ofNanos(userConfig.getTimeUnit(
  497. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  498. ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD,
  499. UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS));
  500. FileStoreAttributes c = new FileStoreAttributes(resolution);
  501. if (!UNDEFINED_DURATION.equals(minRacyThreshold)) {
  502. c.minimalRacyInterval = minRacyThreshold;
  503. }
  504. return Optional.of(c);
  505. }
  506. private static void saveToConfig(FileStore s,
  507. FileStoreAttributes c) {
  508. FileBasedConfig userConfig = SystemReader.getInstance()
  509. .openUserConfig(null, FS.DETECTED);
  510. long resolution = c.getFsTimestampResolution().toNanos();
  511. TimeUnit resolutionUnit = getUnit(resolution);
  512. long resolutionValue = resolutionUnit.convert(resolution,
  513. TimeUnit.NANOSECONDS);
  514. long minRacyThreshold = c.getMinimalRacyInterval().toNanos();
  515. TimeUnit minRacyThresholdUnit = getUnit(minRacyThreshold);
  516. long minRacyThresholdValue = minRacyThresholdUnit
  517. .convert(minRacyThreshold, TimeUnit.NANOSECONDS);
  518. final int max_retries = 5;
  519. int retries = 0;
  520. boolean succeeded = false;
  521. String key = getConfigKey(s);
  522. while (!succeeded && retries < max_retries) {
  523. try {
  524. userConfig.load(false);
  525. userConfig.setString(
  526. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  527. ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION,
  528. String.format("%d %s", //$NON-NLS-1$
  529. Long.valueOf(resolutionValue),
  530. resolutionUnit.name().toLowerCase()));
  531. userConfig.setString(
  532. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  533. ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD,
  534. String.format("%d %s", //$NON-NLS-1$
  535. Long.valueOf(minRacyThresholdValue),
  536. minRacyThresholdUnit.name().toLowerCase()));
  537. userConfig.save();
  538. succeeded = true;
  539. } catch (LockFailedException e) {
  540. // race with another thread, wait a bit and try again
  541. try {
  542. LOG.warn(MessageFormat.format(JGitText.get().cannotLock,
  543. userConfig.getFile().getAbsolutePath()));
  544. retries++;
  545. Thread.sleep(20);
  546. } catch (InterruptedException e1) {
  547. Thread.interrupted();
  548. }
  549. } catch (IOException e) {
  550. LOG.error(MessageFormat.format(
  551. JGitText.get().cannotSaveConfig,
  552. userConfig.getFile().getAbsolutePath()), e);
  553. } catch (ConfigInvalidException e) {
  554. LOG.error(MessageFormat.format(
  555. JGitText.get().repositoryConfigFileInvalid,
  556. userConfig.getFile().getAbsolutePath(),
  557. e.getMessage()));
  558. }
  559. }
  560. }
  561. private static String getConfigKey(FileStore s) {
  562. final String storeKey;
  563. if (SystemReader.getInstance().isWindows()) {
  564. Object attribute = null;
  565. try {
  566. attribute = s.getAttribute("volume:vsn"); //$NON-NLS-1$
  567. } catch (IOException ignored) {
  568. // ignore
  569. }
  570. if (attribute instanceof Integer) {
  571. storeKey = attribute.toString();
  572. } else {
  573. storeKey = s.name();
  574. }
  575. } else {
  576. storeKey = s.name();
  577. }
  578. return javaVersionPrefix + storeKey;
  579. }
  580. private static TimeUnit getUnit(long nanos) {
  581. TimeUnit unit;
  582. if (nanos < 200_000L) {
  583. unit = TimeUnit.NANOSECONDS;
  584. } else if (nanos < 200_000_000L) {
  585. unit = TimeUnit.MICROSECONDS;
  586. } else {
  587. unit = TimeUnit.MILLISECONDS;
  588. }
  589. return unit;
  590. }
  591. private final @NonNull Duration fsTimestampResolution;
  592. private Duration minimalRacyInterval;
  593. /**
  594. * @return the measured minimal interval after a file has been modified
  595. * in which we cannot rely on lastModified to detect
  596. * modifications
  597. */
  598. public Duration getMinimalRacyInterval() {
  599. return minimalRacyInterval;
  600. }
  601. /**
  602. * @return the measured filesystem timestamp resolution
  603. */
  604. @NonNull
  605. public Duration getFsTimestampResolution() {
  606. return fsTimestampResolution;
  607. }
  608. /**
  609. * Construct a FileStoreAttributeCache entry for the given filesystem
  610. * timestamp resolution
  611. *
  612. * @param fsTimestampResolution
  613. */
  614. public FileStoreAttributes(
  615. @NonNull Duration fsTimestampResolution) {
  616. this.fsTimestampResolution = fsTimestampResolution;
  617. this.minimalRacyInterval = Duration.ZERO;
  618. }
  619. @SuppressWarnings({ "nls", "boxing" })
  620. @Override
  621. public String toString() {
  622. return String.format(
  623. "FileStoreAttributes[fsTimestampResolution=%,d µs, "
  624. + "minimalRacyInterval=%,d µs]",
  625. fsTimestampResolution.toNanos() / 1000,
  626. minimalRacyInterval.toNanos() / 1000);
  627. }
  628. }
  629. /** The auto-detected implementation selected for this operating system and JRE. */
  630. public static final FS DETECTED = detect();
  631. private volatile static FSFactory factory;
  632. /**
  633. * Auto-detect the appropriate file system abstraction.
  634. *
  635. * @return detected file system abstraction
  636. */
  637. public static FS detect() {
  638. return detect(null);
  639. }
  640. /**
  641. * Whether FileStore attributes should be determined asynchronously
  642. *
  643. * @param asynch
  644. * whether FileStore attributes should be determined
  645. * asynchronously. If false access to cached attributes may block
  646. * for some seconds for the first call per FileStore
  647. * @since 5.1.9
  648. */
  649. public static void setAsyncFileStoreAttributes(boolean asynch) {
  650. FileStoreAttributes.setBackground(asynch);
  651. }
  652. /**
  653. * Auto-detect the appropriate file system abstraction, taking into account
  654. * the presence of a Cygwin installation on the system. Using jgit in
  655. * combination with Cygwin requires a more elaborate (and possibly slower)
  656. * resolution of file system paths.
  657. *
  658. * @param cygwinUsed
  659. * <ul>
  660. * <li><code>Boolean.TRUE</code> to assume that Cygwin is used in
  661. * combination with jgit</li>
  662. * <li><code>Boolean.FALSE</code> to assume that Cygwin is
  663. * <b>not</b> used with jgit</li>
  664. * <li><code>null</code> to auto-detect whether a Cygwin
  665. * installation is present on the system and in this case assume
  666. * that Cygwin is used</li>
  667. * </ul>
  668. *
  669. * Note: this parameter is only relevant on Windows.
  670. * @return detected file system abstraction
  671. */
  672. public static FS detect(Boolean cygwinUsed) {
  673. if (factory == null) {
  674. factory = new FS.FSFactory();
  675. }
  676. return factory.detect(cygwinUsed);
  677. }
  678. /**
  679. * Get cached FileStore attributes, if not yet available measure them using
  680. * a probe file under the given directory.
  681. *
  682. * @param dir
  683. * the directory under which the probe file will be created to
  684. * measure the timer resolution.
  685. * @return measured filesystem timestamp resolution
  686. * @since 5.1.9
  687. */
  688. public static FileStoreAttributes getFileStoreAttributes(
  689. @NonNull Path dir) {
  690. return FileStoreAttributes.get(dir);
  691. }
  692. private volatile Holder<File> userHome;
  693. private volatile Holder<File> gitSystemConfig;
  694. /**
  695. * Constructs a file system abstraction.
  696. */
  697. protected FS() {
  698. // Do nothing by default.
  699. }
  700. /**
  701. * Initialize this FS using another's current settings.
  702. *
  703. * @param src
  704. * the source FS to copy from.
  705. */
  706. protected FS(FS src) {
  707. userHome = src.userHome;
  708. gitSystemConfig = src.gitSystemConfig;
  709. }
  710. /**
  711. * Create a new instance of the same type of FS.
  712. *
  713. * @return a new instance of the same type of FS.
  714. */
  715. public abstract FS newInstance();
  716. /**
  717. * Does this operating system and JRE support the execute flag on files?
  718. *
  719. * @return true if this implementation can provide reasonably accurate
  720. * executable bit information; false otherwise.
  721. */
  722. public abstract boolean supportsExecute();
  723. /**
  724. * Does this file system support atomic file creation via
  725. * java.io.File#createNewFile()? In certain environments (e.g. on NFS) it is
  726. * not guaranteed that when two file system clients run createNewFile() in
  727. * parallel only one will succeed. In such cases both clients may think they
  728. * created a new file.
  729. *
  730. * @return true if this implementation support atomic creation of new Files
  731. * by {@link java.io.File#createNewFile()}
  732. * @since 4.5
  733. */
  734. public boolean supportsAtomicCreateNewFile() {
  735. return true;
  736. }
  737. /**
  738. * Does this operating system and JRE supports symbolic links. The
  739. * capability to handle symbolic links is detected at runtime.
  740. *
  741. * @return true if symbolic links may be used
  742. * @since 3.0
  743. */
  744. public boolean supportsSymlinks() {
  745. return false;
  746. }
  747. /**
  748. * Is this file system case sensitive
  749. *
  750. * @return true if this implementation is case sensitive
  751. */
  752. public abstract boolean isCaseSensitive();
  753. /**
  754. * Determine if the file is executable (or not).
  755. * <p>
  756. * Not all platforms and JREs support executable flags on files. If the
  757. * feature is unsupported this method will always return false.
  758. * <p>
  759. * <em>If the platform supports symbolic links and <code>f</code> is a symbolic link
  760. * this method returns false, rather than the state of the executable flags
  761. * on the target file.</em>
  762. *
  763. * @param f
  764. * abstract path to test.
  765. * @return true if the file is believed to be executable by the user.
  766. */
  767. public abstract boolean canExecute(File f);
  768. /**
  769. * Set a file to be executable by the user.
  770. * <p>
  771. * Not all platforms and JREs support executable flags on files. If the
  772. * feature is unsupported this method will always return false and no
  773. * changes will be made to the file specified.
  774. *
  775. * @param f
  776. * path to modify the executable status of.
  777. * @param canExec
  778. * true to enable execution; false to disable it.
  779. * @return true if the change succeeded; false otherwise.
  780. */
  781. public abstract boolean setExecute(File f, boolean canExec);
  782. /**
  783. * Get the last modified time of a file system object. If the OS/JRE support
  784. * symbolic links, the modification time of the link is returned, rather
  785. * than that of the link target.
  786. *
  787. * @param f
  788. * a {@link java.io.File} object.
  789. * @return last modified time of f
  790. * @throws java.io.IOException
  791. * @since 3.0
  792. * @deprecated use {@link #lastModifiedInstant(Path)} instead
  793. */
  794. @Deprecated
  795. public long lastModified(File f) throws IOException {
  796. return FileUtils.lastModified(f);
  797. }
  798. /**
  799. * Get the last modified time of a file system object. If the OS/JRE support
  800. * symbolic links, the modification time of the link is returned, rather
  801. * than that of the link target.
  802. *
  803. * @param p
  804. * a {@link Path} object.
  805. * @return last modified time of p
  806. * @since 5.1.9
  807. */
  808. public Instant lastModifiedInstant(Path p) {
  809. return FileUtils.lastModifiedInstant(p);
  810. }
  811. /**
  812. * Get the last modified time of a file system object. If the OS/JRE support
  813. * symbolic links, the modification time of the link is returned, rather
  814. * than that of the link target.
  815. *
  816. * @param f
  817. * a {@link File} object.
  818. * @return last modified time of p
  819. * @since 5.1.9
  820. */
  821. public Instant lastModifiedInstant(File f) {
  822. return FileUtils.lastModifiedInstant(f.toPath());
  823. }
  824. /**
  825. * Set the last modified time of a file system object. If the OS/JRE support
  826. * symbolic links, the link is modified, not the target,
  827. *
  828. * @param f
  829. * a {@link java.io.File} object.
  830. * @param time
  831. * last modified time
  832. * @throws java.io.IOException
  833. * @since 3.0
  834. * @deprecated use {@link #setLastModified(Path, Instant)} instead
  835. */
  836. @Deprecated
  837. public void setLastModified(File f, long time) throws IOException {
  838. FileUtils.setLastModified(f, time);
  839. }
  840. /**
  841. * Set the last modified time of a file system object. If the OS/JRE support
  842. * symbolic links, the link is modified, not the target,
  843. *
  844. * @param p
  845. * a {@link Path} object.
  846. * @param time
  847. * last modified time
  848. * @throws java.io.IOException
  849. * @since 5.1.9
  850. */
  851. public void setLastModified(Path p, Instant time) throws IOException {
  852. FileUtils.setLastModified(p, time);
  853. }
  854. /**
  855. * Get the length of a file or link, If the OS/JRE supports symbolic links
  856. * it's the length of the link, else the length of the target.
  857. *
  858. * @param path
  859. * a {@link java.io.File} object.
  860. * @return length of a file
  861. * @throws java.io.IOException
  862. * @since 3.0
  863. */
  864. public long length(File path) throws IOException {
  865. return FileUtils.getLength(path);
  866. }
  867. /**
  868. * Delete a file. Throws an exception if delete fails.
  869. *
  870. * @param f
  871. * a {@link java.io.File} object.
  872. * @throws java.io.IOException
  873. * this may be a Java7 subclass with detailed information
  874. * @since 3.3
  875. */
  876. public void delete(File f) throws IOException {
  877. FileUtils.delete(f);
  878. }
  879. /**
  880. * Resolve this file to its actual path name that the JRE can use.
  881. * <p>
  882. * This method can be relatively expensive. Computing a translation may
  883. * require forking an external process per path name translated. Callers
  884. * should try to minimize the number of translations necessary by caching
  885. * the results.
  886. * <p>
  887. * Not all platforms and JREs require path name translation. Currently only
  888. * Cygwin on Win32 require translation for Cygwin based paths.
  889. *
  890. * @param dir
  891. * directory relative to which the path name is.
  892. * @param name
  893. * path name to translate.
  894. * @return the translated path. <code>new File(dir,name)</code> if this
  895. * platform does not require path name translation.
  896. */
  897. public File resolve(File dir, String name) {
  898. final File abspn = new File(name);
  899. if (abspn.isAbsolute())
  900. return abspn;
  901. return new File(dir, name);
  902. }
  903. /**
  904. * Determine the user's home directory (location where preferences are).
  905. * <p>
  906. * This method can be expensive on the first invocation if path name
  907. * translation is required. Subsequent invocations return a cached result.
  908. * <p>
  909. * Not all platforms and JREs require path name translation. Currently only
  910. * Cygwin on Win32 requires translation of the Cygwin HOME directory.
  911. *
  912. * @return the user's home directory; null if the user does not have one.
  913. */
  914. public File userHome() {
  915. Holder<File> p = userHome;
  916. if (p == null) {
  917. p = new Holder<>(userHomeImpl());
  918. userHome = p;
  919. }
  920. return p.value;
  921. }
  922. /**
  923. * Set the user's home directory location.
  924. *
  925. * @param path
  926. * the location of the user's preferences; null if there is no
  927. * home directory for the current user.
  928. * @return {@code this}.
  929. */
  930. public FS setUserHome(File path) {
  931. userHome = new Holder<>(path);
  932. return this;
  933. }
  934. /**
  935. * Does this file system have problems with atomic renames?
  936. *
  937. * @return true if the caller should retry a failed rename of a lock file.
  938. */
  939. public abstract boolean retryFailedLockFileCommit();
  940. /**
  941. * Return all the attributes of a file, without following symbolic links.
  942. *
  943. * @param file
  944. * @return {@link BasicFileAttributes} of the file
  945. * @throws IOException in case of any I/O errors accessing the file
  946. *
  947. * @since 4.5.6
  948. */
  949. public BasicFileAttributes fileAttributes(File file) throws IOException {
  950. return FileUtils.fileAttributes(file);
  951. }
  952. /**
  953. * Determine the user's home directory (location where preferences are).
  954. *
  955. * @return the user's home directory; null if the user does not have one.
  956. */
  957. protected File userHomeImpl() {
  958. final String home = AccessController
  959. .doPrivileged(new PrivilegedAction<String>() {
  960. @Override
  961. public String run() {
  962. return System.getProperty("user.home"); //$NON-NLS-1$
  963. }
  964. });
  965. if (home == null || home.length() == 0)
  966. return null;
  967. return new File(home).getAbsoluteFile();
  968. }
  969. /**
  970. * Searches the given path to see if it contains one of the given files.
  971. * Returns the first it finds. Returns null if not found or if path is null.
  972. *
  973. * @param path
  974. * List of paths to search separated by File.pathSeparator
  975. * @param lookFor
  976. * Files to search for in the given path
  977. * @return the first match found, or null
  978. * @since 3.0
  979. */
  980. protected static File searchPath(String path, String... lookFor) {
  981. if (path == null)
  982. return null;
  983. for (String p : path.split(File.pathSeparator)) {
  984. for (String command : lookFor) {
  985. final File e = new File(p, command);
  986. if (e.isFile())
  987. return e.getAbsoluteFile();
  988. }
  989. }
  990. return null;
  991. }
  992. /**
  993. * Execute a command and return a single line of output as a String
  994. *
  995. * @param dir
  996. * Working directory for the command
  997. * @param command
  998. * as component array
  999. * @param encoding
  1000. * to be used to parse the command's output
  1001. * @return the one-line output of the command or {@code null} if there is
  1002. * none
  1003. * @throws org.eclipse.jgit.errors.CommandFailedException
  1004. * thrown when the command failed (return code was non-zero)
  1005. */
  1006. @Nullable
  1007. protected static String readPipe(File dir, String[] command,
  1008. String encoding) throws CommandFailedException {
  1009. return readPipe(dir, command, encoding, null);
  1010. }
  1011. /**
  1012. * Execute a command and return a single line of output as a String
  1013. *
  1014. * @param dir
  1015. * Working directory for the command
  1016. * @param command
  1017. * as component array
  1018. * @param encoding
  1019. * to be used to parse the command's output
  1020. * @param env
  1021. * Map of environment variables to be merged with those of the
  1022. * current process
  1023. * @return the one-line output of the command or {@code null} if there is
  1024. * none
  1025. * @throws org.eclipse.jgit.errors.CommandFailedException
  1026. * thrown when the command failed (return code was non-zero)
  1027. * @since 4.0
  1028. */
  1029. @Nullable
  1030. protected static String readPipe(File dir, String[] command,
  1031. String encoding, Map<String, String> env)
  1032. throws CommandFailedException {
  1033. final boolean debug = LOG.isDebugEnabled();
  1034. try {
  1035. if (debug) {
  1036. LOG.debug("readpipe " + Arrays.asList(command) + "," //$NON-NLS-1$ //$NON-NLS-2$
  1037. + dir);
  1038. }
  1039. ProcessBuilder pb = new ProcessBuilder(command);
  1040. pb.directory(dir);
  1041. if (env != null) {
  1042. pb.environment().putAll(env);
  1043. }
  1044. Process p;
  1045. try {
  1046. p = pb.start();
  1047. } catch (IOException e) {
  1048. // Process failed to start
  1049. throw new CommandFailedException(-1, e.getMessage(), e);
  1050. }
  1051. p.getOutputStream().close();
  1052. GobblerThread gobbler = new GobblerThread(p, command, dir);
  1053. gobbler.start();
  1054. String r = null;
  1055. try (BufferedReader lineRead = new BufferedReader(
  1056. new InputStreamReader(p.getInputStream(), encoding))) {
  1057. r = lineRead.readLine();
  1058. if (debug) {
  1059. LOG.debug("readpipe may return '" + r + "'"); //$NON-NLS-1$ //$NON-NLS-2$
  1060. LOG.debug("remaining output:\n"); //$NON-NLS-1$
  1061. String l;
  1062. while ((l = lineRead.readLine()) != null) {
  1063. LOG.debug(l);
  1064. }
  1065. }
  1066. }
  1067. for (;;) {
  1068. try {
  1069. int rc = p.waitFor();
  1070. gobbler.join();
  1071. if (rc == 0 && !gobbler.fail.get()) {
  1072. return r;
  1073. } else {
  1074. if (debug) {
  1075. LOG.debug("readpipe rc=" + rc); //$NON-NLS-1$
  1076. }
  1077. throw new CommandFailedException(rc,
  1078. gobbler.errorMessage.get(),
  1079. gobbler.exception.get());
  1080. }
  1081. } catch (InterruptedException ie) {
  1082. // Stop bothering me, I have a zombie to reap.
  1083. }
  1084. }
  1085. } catch (IOException e) {
  1086. LOG.error("Caught exception in FS.readPipe()", e); //$NON-NLS-1$
  1087. }
  1088. if (debug) {
  1089. LOG.debug("readpipe returns null"); //$NON-NLS-1$
  1090. }
  1091. return null;
  1092. }
  1093. private static class GobblerThread extends Thread {
  1094. /* The process has 5 seconds to exit after closing stderr */
  1095. private static final int PROCESS_EXIT_TIMEOUT = 5;
  1096. private final Process p;
  1097. private final String desc;
  1098. private final String dir;
  1099. final AtomicBoolean fail = new AtomicBoolean();
  1100. final AtomicReference<String> errorMessage = new AtomicReference<>();
  1101. final AtomicReference<Throwable> exception = new AtomicReference<>();
  1102. GobblerThread(Process p, String[] command, File dir) {
  1103. this.p = p;
  1104. this.desc = Arrays.toString(command);
  1105. this.dir = Objects.toString(dir);
  1106. }
  1107. @Override
  1108. public void run() {
  1109. StringBuilder err = new StringBuilder();
  1110. try (InputStream is = p.getErrorStream()) {
  1111. int ch;
  1112. while ((ch = is.read()) != -1) {
  1113. err.append((char) ch);
  1114. }
  1115. } catch (IOException e) {
  1116. if (waitForProcessCompletion(e) && p.exitValue() != 0) {
  1117. setError(e, e.getMessage(), p.exitValue());
  1118. fail.set(true);
  1119. } else {
  1120. // ignore. command terminated faster and stream was just closed
  1121. // or the process didn't terminate within timeout
  1122. }
  1123. } finally {
  1124. if (waitForProcessCompletion(null) && err.length() > 0) {
  1125. setError(null, err.toString(), p.exitValue());
  1126. if (p.exitValue() != 0) {
  1127. fail.set(true);
  1128. }
  1129. }
  1130. }
  1131. }
  1132. @SuppressWarnings("boxing")
  1133. private boolean waitForProcessCompletion(IOException originalError) {
  1134. try {
  1135. if (!p.waitFor(PROCESS_EXIT_TIMEOUT, TimeUnit.SECONDS)) {
  1136. setError(originalError, MessageFormat.format(
  1137. JGitText.get().commandClosedStderrButDidntExit,
  1138. desc, PROCESS_EXIT_TIMEOUT), -1);
  1139. fail.set(true);
  1140. return false;
  1141. }
  1142. } catch (InterruptedException e) {
  1143. setError(originalError, MessageFormat.format(
  1144. JGitText.get().threadInterruptedWhileRunning, desc), -1);
  1145. fail.set(true);
  1146. return false;
  1147. }
  1148. return true;
  1149. }
  1150. private void setError(IOException e, String message, int exitCode) {
  1151. exception.set(e);
  1152. errorMessage.set(MessageFormat.format(
  1153. JGitText.get().exceptionCaughtDuringExecutionOfCommand,
  1154. desc, dir, Integer.valueOf(exitCode), message));
  1155. }
  1156. }
  1157. /**
  1158. * Discover the path to the Git executable.
  1159. *
  1160. * @return the path to the Git executable or {@code null} if it cannot be
  1161. * determined.
  1162. * @since 4.0
  1163. */
  1164. protected abstract File discoverGitExe();
  1165. /**
  1166. * Discover the path to the system-wide Git configuration file
  1167. *
  1168. * @return the path to the system-wide Git configuration file or
  1169. * {@code null} if it cannot be determined.
  1170. * @since 4.0
  1171. */
  1172. protected File discoverGitSystemConfig() {
  1173. File gitExe = discoverGitExe();
  1174. if (gitExe == null) {
  1175. return null;
  1176. }
  1177. // Bug 480782: Check if the discovered git executable is JGit CLI
  1178. String v;
  1179. try {
  1180. v = readPipe(gitExe.getParentFile(),
  1181. new String[] { "git", "--version" }, //$NON-NLS-1$ //$NON-NLS-2$
  1182. Charset.defaultCharset().name());
  1183. } catch (CommandFailedException e) {
  1184. LOG.warn(e.getMessage());
  1185. return null;
  1186. }
  1187. if (StringUtils.isEmptyOrNull(v)
  1188. || (v != null && v.startsWith("jgit"))) { //$NON-NLS-1$
  1189. return null;
  1190. }
  1191. // Trick Git into printing the path to the config file by using "echo"
  1192. // as the editor.
  1193. Map<String, String> env = new HashMap<>();
  1194. env.put("GIT_EDITOR", "echo"); //$NON-NLS-1$ //$NON-NLS-2$
  1195. String w;
  1196. try {
  1197. w = readPipe(gitExe.getParentFile(),
  1198. new String[] { "git", "config", "--system", "--edit" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  1199. Charset.defaultCharset().name(), env);
  1200. } catch (CommandFailedException e) {
  1201. LOG.warn(e.getMessage());
  1202. return null;
  1203. }
  1204. if (StringUtils.isEmptyOrNull(w)) {
  1205. return null;
  1206. }
  1207. return new File(w);
  1208. }
  1209. /**
  1210. * Get the currently used path to the system-wide Git configuration file.
  1211. *
  1212. * @return the currently used path to the system-wide Git configuration file
  1213. * or {@code null} if none has been set.
  1214. * @since 4.0
  1215. */
  1216. public File getGitSystemConfig() {
  1217. if (gitSystemConfig == null) {
  1218. gitSystemConfig = new Holder<>(discoverGitSystemConfig());
  1219. }
  1220. return gitSystemConfig.value;
  1221. }
  1222. /**
  1223. * Set the path to the system-wide Git configuration file to use.
  1224. *
  1225. * @param configFile
  1226. * the path to the config file.
  1227. * @return {@code this}
  1228. * @since 4.0
  1229. */
  1230. public FS setGitSystemConfig(File configFile) {
  1231. gitSystemConfig = new Holder<>(configFile);
  1232. return this;
  1233. }
  1234. /**
  1235. * Get the parent directory of this file's parent directory
  1236. *
  1237. * @param grandchild
  1238. * a {@link java.io.File} object.
  1239. * @return the parent directory of this file's parent directory or
  1240. * {@code null} in case there's no grandparent directory
  1241. * @since 4.0
  1242. */
  1243. protected static File resolveGrandparentFile(File grandchild) {
  1244. if (grandchild != null) {
  1245. File parent = grandchild.getParentFile();
  1246. if (parent != null)
  1247. return parent.getParentFile();
  1248. }
  1249. return null;
  1250. }
  1251. /**
  1252. * Check if a file is a symbolic link and read it
  1253. *
  1254. * @param path
  1255. * a {@link java.io.File} object.
  1256. * @return target of link or null
  1257. * @throws java.io.IOException
  1258. * @since 3.0
  1259. */
  1260. public String readSymLink(File path) throws IOException {
  1261. return FileUtils.readSymLink(path);
  1262. }
  1263. /**
  1264. * Whether the path is a symbolic link (and we support these).
  1265. *
  1266. * @param path
  1267. * a {@link java.io.File} object.
  1268. * @return true if the path is a symbolic link (and we support these)
  1269. * @throws java.io.IOException
  1270. * @since 3.0
  1271. */
  1272. public boolean isSymLink(File path) throws IOException {
  1273. return FileUtils.isSymlink(path);
  1274. }
  1275. /**
  1276. * Tests if the path exists, in case of a symbolic link, true even if the
  1277. * target does not exist
  1278. *
  1279. * @param path
  1280. * a {@link java.io.File} object.
  1281. * @return true if path exists
  1282. * @since 3.0
  1283. */
  1284. public boolean exists(File path) {
  1285. return FileUtils.exists(path);
  1286. }
  1287. /**
  1288. * Check if path is a directory. If the OS/JRE supports symbolic links and
  1289. * path is a symbolic link to a directory, this method returns false.
  1290. *
  1291. * @param path
  1292. * a {@link java.io.File} object.
  1293. * @return true if file is a directory,
  1294. * @since 3.0
  1295. */
  1296. public boolean isDirectory(File path) {
  1297. return FileUtils.isDirectory(path);
  1298. }
  1299. /**
  1300. * Examine if path represents a regular file. If the OS/JRE supports
  1301. * symbolic links the test returns false if path represents a symbolic link.
  1302. *
  1303. * @param path
  1304. * a {@link java.io.File} object.
  1305. * @return true if path represents a regular file
  1306. * @since 3.0
  1307. */
  1308. public boolean isFile(File path) {
  1309. return FileUtils.isFile(path);
  1310. }
  1311. /**
  1312. * Whether path is hidden, either starts with . on unix or has the hidden
  1313. * attribute in windows
  1314. *
  1315. * @param path
  1316. * a {@link java.io.File} object.
  1317. * @return true if path is hidden, either starts with . on unix or has the
  1318. * hidden attribute in windows
  1319. * @throws java.io.IOException
  1320. * @since 3.0
  1321. */
  1322. public boolean isHidden(File path) throws IOException {
  1323. return FileUtils.isHidden(path);
  1324. }
  1325. /**
  1326. * Set the hidden attribute for file whose name starts with a period.
  1327. *
  1328. * @param path
  1329. * a {@link java.io.File} object.
  1330. * @param hidden
  1331. * whether to set the file hidden
  1332. * @throws java.io.IOException
  1333. * @since 3.0
  1334. */
  1335. public void setHidden(File path, boolean hidden) throws IOException {
  1336. FileUtils.setHidden(path, hidden);
  1337. }
  1338. /**
  1339. * Create a symbolic link
  1340. *
  1341. * @param path
  1342. * a {@link java.io.File} object.
  1343. * @param target
  1344. * target path of the symlink
  1345. * @throws java.io.IOException
  1346. * @since 3.0
  1347. */
  1348. public void createSymLink(File path, String target) throws IOException {
  1349. FileUtils.createSymLink(path, target);
  1350. }
  1351. /**
  1352. * Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
  1353. * of this class may take care to provide a safe implementation for this
  1354. * even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
  1355. *
  1356. * @param path
  1357. * the file to be created
  1358. * @return <code>true</code> if the file was created, <code>false</code> if
  1359. * the file already existed
  1360. * @throws java.io.IOException
  1361. * @deprecated use {@link #createNewFileAtomic(File)} instead
  1362. * @since 4.5
  1363. */
  1364. @Deprecated
  1365. public boolean createNewFile(File path) throws IOException {
  1366. return path.createNewFile();
  1367. }
  1368. /**
  1369. * A token representing a file created by
  1370. * {@link #createNewFileAtomic(File)}. The token must be retained until the
  1371. * file has been deleted in order to guarantee that the unique file was
  1372. * created atomically. As soon as the file is no longer needed the lock
  1373. * token must be closed.
  1374. *
  1375. * @since 4.7
  1376. */
  1377. public static class LockToken implements Closeable {
  1378. private boolean isCreated;
  1379. private Optional<Path> link;
  1380. LockToken(boolean isCreated, Optional<Path> link) {
  1381. this.isCreated = isCreated;
  1382. this.link = link;
  1383. }
  1384. /**
  1385. * @return {@code true} if the file was created successfully
  1386. */
  1387. public boolean isCreated() {
  1388. return isCreated;
  1389. }
  1390. @Override
  1391. public void close() {
  1392. if (!link.isPresent()) {
  1393. return;
  1394. }
  1395. Path p = link.get();
  1396. if (!Files.exists(p)) {
  1397. return;
  1398. }
  1399. try {
  1400. Files.delete(p);
  1401. } catch (IOException e) {
  1402. LOG.error(MessageFormat
  1403. .format(JGitText.get().closeLockTokenFailed, this), e);
  1404. }
  1405. }
  1406. @Override
  1407. public String toString() {
  1408. return "LockToken [lockCreated=" + isCreated + //$NON-NLS-1$
  1409. ", link=" //$NON-NLS-1$
  1410. + (link.isPresent() ? link.get().getFileName() + "]" //$NON-NLS-1$
  1411. : "<null>]"); //$NON-NLS-1$
  1412. }
  1413. }
  1414. /**
  1415. * Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
  1416. * of this class may take care to provide a safe implementation for this
  1417. * even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
  1418. *
  1419. * @param path
  1420. * the file to be created
  1421. * @return LockToken this token must be closed after the created file was
  1422. * deleted
  1423. * @throws IOException
  1424. * @since 4.7
  1425. */
  1426. public LockToken createNewFileAtomic(File path) throws IOException {
  1427. return new LockToken(path.createNewFile(), Optional.empty());
  1428. }
  1429. /**
  1430. * See
  1431. * {@link org.eclipse.jgit.util.FileUtils#relativizePath(String, String, String, boolean)}.
  1432. *
  1433. * @param base
  1434. * The path against which <code>other</code> should be
  1435. * relativized.
  1436. * @param other
  1437. * The path that will be made relative to <code>base</code>.
  1438. * @return A relative path that, when resolved against <code>base</code>,
  1439. * will yield the original <code>other</code>.
  1440. * @see FileUtils#relativizePath(String, String, String, boolean)
  1441. * @since 3.7
  1442. */
  1443. public String relativize(String base, String other) {
  1444. return FileUtils.relativizePath(base, other, File.separator, this.isCaseSensitive());
  1445. }
  1446. /**
  1447. * Enumerates children of a directory.
  1448. *
  1449. * @param directory
  1450. * to get the children of
  1451. * @param fileModeStrategy
  1452. * to use to calculate the git mode of a child
  1453. * @return an array of entries for the children
  1454. *
  1455. * @since 5.0
  1456. */
  1457. public Entry[] list(File directory, FileModeStrategy fileModeStrategy) {
  1458. final File[] all = directory.listFiles();
  1459. if (all == null) {
  1460. return NO_ENTRIES;
  1461. }
  1462. final Entry[] result = new Entry[all.length];
  1463. for (int i = 0; i < result.length; i++) {
  1464. result[i] = new FileEntry(all[i], this, fileModeStrategy);
  1465. }
  1466. return result;
  1467. }
  1468. /**
  1469. * Checks whether the given hook is defined for the given repository, then
  1470. * runs it with the given arguments.
  1471. * <p>
  1472. * The hook's standard output and error streams will be redirected to
  1473. * <code>System.out</code> and <code>System.err</code> respectively. The
  1474. * hook will have no stdin.
  1475. * </p>
  1476. *
  1477. * @param repository
  1478. * The repository for which a hook should be run.
  1479. * @param hookName
  1480. * The name of the hook to be executed.
  1481. * @param args
  1482. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1483. * but can be an empty array.
  1484. * @return The ProcessResult describing this hook's execution.
  1485. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1486. * if we fail to run the hook somehow. Causes may include an
  1487. * interrupted process or I/O errors.
  1488. * @since 4.0
  1489. */
  1490. public ProcessResult runHookIfPresent(Repository repository,
  1491. final String hookName,
  1492. String[] args) throws JGitInternalException {
  1493. return runHookIfPresent(repository, hookName, args, System.out, System.err,
  1494. null);
  1495. }
  1496. /**
  1497. * Checks whether the given hook is defined for the given repository, then
  1498. * runs it with the given arguments.
  1499. *
  1500. * @param repository
  1501. * The repository for which a hook should be run.
  1502. * @param hookName
  1503. * The name of the hook to be executed.
  1504. * @param args
  1505. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1506. * but can be an empty array.
  1507. * @param outRedirect
  1508. * A print stream on which to redirect the hook's stdout. Can be
  1509. * <code>null</code>, in which case the hook's standard output
  1510. * will be lost.
  1511. * @param errRedirect
  1512. * A print stream on which to redirect the hook's stderr. Can be
  1513. * <code>null</code>, in which case the hook's standard error
  1514. * will be lost.
  1515. * @param stdinArgs
  1516. * A string to pass on to the standard input of the hook. May be
  1517. * <code>null</code>.
  1518. * @return The ProcessResult describing this hook's execution.
  1519. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1520. * if we fail to run the hook somehow. Causes may include an
  1521. * interrupted process or I/O errors.
  1522. * @since 4.0
  1523. */
  1524. public ProcessResult runHookIfPresent(Repository repository,
  1525. final String hookName,
  1526. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  1527. String stdinArgs) throws JGitInternalException {
  1528. return new ProcessResult(Status.NOT_SUPPORTED);
  1529. }
  1530. /**
  1531. * See
  1532. * {@link #runHookIfPresent(Repository, String, String[], PrintStream, PrintStream, String)}
  1533. * . Should only be called by FS supporting shell scripts execution.
  1534. *
  1535. * @param repository
  1536. * The repository for which a hook should be run.
  1537. * @param hookName
  1538. * The name of the hook to be executed.
  1539. * @param args
  1540. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1541. * but can be an empty array.
  1542. * @param outRedirect
  1543. * A print stream on which to redirect the hook's stdout. Can be
  1544. * <code>null</code>, in which case the hook's standard output
  1545. * will be lost.
  1546. * @param errRedirect
  1547. * A print stream on which to redirect the hook's stderr. Can be
  1548. * <code>null</code>, in which case the hook's standard error
  1549. * will be lost.
  1550. * @param stdinArgs
  1551. * A string to pass on to the standard input of the hook. May be
  1552. * <code>null</code>.
  1553. * @return The ProcessResult describing this hook's execution.
  1554. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1555. * if we fail to run the hook somehow. Causes may include an
  1556. * interrupted process or I/O errors.
  1557. * @since 4.0
  1558. */
  1559. protected ProcessResult internalRunHookIfPresent(Repository repository,
  1560. final String hookName, String[] args, PrintStream outRedirect,
  1561. PrintStream errRedirect, String stdinArgs)
  1562. throws JGitInternalException {
  1563. final File hookFile = findHook(repository, hookName);
  1564. if (hookFile == null)
  1565. return new ProcessResult(Status.NOT_PRESENT);
  1566. final String hookPath = hookFile.getAbsolutePath();
  1567. final File runDirectory;
  1568. if (repository.isBare())
  1569. runDirectory = repository.getDirectory();
  1570. else
  1571. runDirectory = repository.getWorkTree();
  1572. final String cmd = relativize(runDirectory.getAbsolutePath(),
  1573. hookPath);
  1574. ProcessBuilder hookProcess = runInShell(cmd, args);
  1575. hookProcess.directory(runDirectory);
  1576. try {
  1577. return new ProcessResult(runProcess(hookProcess, outRedirect,
  1578. errRedirect, stdinArgs), Status.OK);
  1579. } catch (IOException e) {
  1580. throw new JGitInternalException(MessageFormat.format(
  1581. JGitText.get().exceptionCaughtDuringExecutionOfHook,
  1582. hookName), e);
  1583. } catch (InterruptedException e) {
  1584. throw new JGitInternalException(MessageFormat.format(
  1585. JGitText.get().exceptionHookExecutionInterrupted,
  1586. hookName), e);
  1587. }
  1588. }
  1589. /**
  1590. * Tries to find a hook matching the given one in the given repository.
  1591. *
  1592. * @param repository
  1593. * The repository within which to find a hook.
  1594. * @param hookName
  1595. * The name of the hook we're trying to find.
  1596. * @return The {@link java.io.File} containing this particular hook if it
  1597. * exists in the given repository, <code>null</code> otherwise.
  1598. * @since 4.0
  1599. */
  1600. public File findHook(Repository repository, String hookName) {
  1601. File gitDir = repository.getDirectory();
  1602. if (gitDir == null)
  1603. return null;
  1604. final File hookFile = new File(new File(gitDir,
  1605. Constants.HOOKS), hookName);
  1606. return hookFile.isFile() ? hookFile : null;
  1607. }
  1608. /**
  1609. * Runs the given process until termination, clearing its stdout and stderr
  1610. * streams on-the-fly.
  1611. *
  1612. * @param processBuilder
  1613. * The process builder configured for this process.
  1614. * @param outRedirect
  1615. * A OutputStream on which to redirect the processes stdout. Can
  1616. * be <code>null</code>, in which case the processes standard
  1617. * output will be lost.
  1618. * @param errRedirect
  1619. * A OutputStream on which to redirect the processes stderr. Can
  1620. * be <code>null</code>, in which case the processes standard
  1621. * error will be lost.
  1622. * @param stdinArgs
  1623. * A string to pass on to the standard input of the hook. Can be
  1624. * <code>null</code>.
  1625. * @return the exit value of this process.
  1626. * @throws java.io.IOException
  1627. * if an I/O error occurs while executing this process.
  1628. * @throws java.lang.InterruptedException
  1629. * if the current thread is interrupted while waiting for the
  1630. * process to end.
  1631. * @since 4.2
  1632. */
  1633. public int runProcess(ProcessBuilder processBuilder,
  1634. OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
  1635. throws IOException, InterruptedException {
  1636. InputStream in = (stdinArgs == null) ? null : new ByteArrayInputStream(
  1637. stdinArgs.getBytes(UTF_8));
  1638. return runProcess(processBuilder, outRedirect, errRedirect, in);
  1639. }
  1640. /**
  1641. * Runs the given process until termination, clearing its stdout and stderr
  1642. * streams on-the-fly.
  1643. *
  1644. * @param processBuilder
  1645. * The process builder configured for this process.
  1646. * @param outRedirect
  1647. * An OutputStream on which to redirect the processes stdout. Can
  1648. * be <code>null</code>, in which case the processes standard
  1649. * output will be lost.
  1650. * @param errRedirect
  1651. * An OutputStream on which to redirect the processes stderr. Can
  1652. * be <code>null</code>, in which case the processes standard
  1653. * error will be lost.
  1654. * @param inRedirect
  1655. * An InputStream from which to redirect the processes stdin. Can
  1656. * be <code>null</code>, in which case the process doesn't get
  1657. * any data over stdin. It is assumed that the whole InputStream
  1658. * will be consumed by the process. The method will close the
  1659. * inputstream after all bytes are read.
  1660. * @return the return code of this process.
  1661. * @throws java.io.IOException
  1662. * if an I/O error occurs while executing this process.
  1663. * @throws java.lang.InterruptedException
  1664. * if the current thread is interrupted while waiting for the
  1665. * process to end.
  1666. * @since 4.2
  1667. */
  1668. public int runProcess(ProcessBuilder processBuilder,
  1669. OutputStream outRedirect, OutputStream errRedirect,
  1670. InputStream inRedirect) throws IOException,
  1671. InterruptedException {
  1672. final ExecutorService executor = Executors.newFixedThreadPool(2);
  1673. Process process = null;
  1674. // We'll record the first I/O exception that occurs, but keep on trying
  1675. // to dispose of our open streams and file handles
  1676. IOException ioException = null;
  1677. try {
  1678. process = processBuilder.start();
  1679. executor.execute(
  1680. new StreamGobbler(process.getErrorStream(), errRedirect));
  1681. executor.execute(
  1682. new StreamGobbler(process.getInputStream(), outRedirect));
  1683. @SuppressWarnings("resource") // Closed in the finally block
  1684. OutputStream outputStream = process.getOutputStream();
  1685. try {
  1686. if (inRedirect != null) {
  1687. new StreamGobbler(inRedirect, outputStream).copy();
  1688. }
  1689. } finally {
  1690. try {
  1691. outputStream.close();
  1692. } catch (IOException e) {
  1693. // When the process exits before consuming the input, the OutputStream
  1694. // is replaced with the null output stream. This null output stream
  1695. // throws IOException for all write calls. When StreamGobbler fails to
  1696. // flush the buffer because of this, this close call tries to flush it
  1697. // again. This causes another IOException. Since we ignore the
  1698. // IOException in StreamGobbler, we also ignore the exception here.
  1699. }
  1700. }
  1701. return process.waitFor();
  1702. } catch (IOException e) {
  1703. ioException = e;
  1704. } finally {
  1705. shutdownAndAwaitTermination(executor);
  1706. if (process != null) {
  1707. try {
  1708. process.waitFor();
  1709. } catch (InterruptedException e) {
  1710. // Thrown by the outer try.
  1711. // Swallow this one to carry on our cleanup, and clear the
  1712. // interrupted flag (processes throw the exception without
  1713. // clearing the flag).
  1714. Thread.interrupted();
  1715. }
  1716. // A process doesn't clean its own resources even when destroyed
  1717. // Explicitly try and close all three streams, preserving the
  1718. // outer I/O exception if any.
  1719. if (inRedirect != null) {
  1720. inRedirect.close();
  1721. }
  1722. try {
  1723. process.getErrorStream().close();
  1724. } catch (IOException e) {
  1725. ioException = ioException != null ? ioException : e;
  1726. }
  1727. try {
  1728. process.getInputStream().close();
  1729. } catch (IOException e) {
  1730. ioException = ioException != null ? ioException : e;
  1731. }
  1732. try {
  1733. process.getOutputStream().close();
  1734. } catch (IOException e) {
  1735. ioException = ioException != null ? ioException : e;
  1736. }
  1737. process.destroy();
  1738. }
  1739. }
  1740. // We can only be here if the outer try threw an IOException.
  1741. throw ioException;
  1742. }
  1743. /**
  1744. * Shuts down an {@link ExecutorService} in two phases, first by calling
  1745. * {@link ExecutorService#shutdown() shutdown} to reject incoming tasks, and
  1746. * then calling {@link ExecutorService#shutdownNow() shutdownNow}, if
  1747. * necessary, to cancel any lingering tasks. Returns true if the pool has
  1748. * been properly shutdown, false otherwise.
  1749. * <p>
  1750. *
  1751. * @param pool
  1752. * the pool to shutdown
  1753. * @return <code>true</code> if the pool has been properly shutdown,
  1754. * <code>false</code> otherwise.
  1755. */
  1756. private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
  1757. boolean hasShutdown = true;
  1758. pool.shutdown(); // Disable new tasks from being submitted
  1759. try {
  1760. // Wait a while for existing tasks to terminate
  1761. if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
  1762. pool.shutdownNow(); // Cancel currently executing tasks
  1763. // Wait a while for tasks to respond to being canceled
  1764. if (!pool.awaitTermination(60, TimeUnit.SECONDS))
  1765. hasShutdown = false;
  1766. }
  1767. } catch (InterruptedException ie) {
  1768. // (Re-)Cancel if current thread also interrupted
  1769. pool.shutdownNow();
  1770. // Preserve interrupt status
  1771. Thread.currentThread().interrupt();
  1772. hasShutdown = false;
  1773. }
  1774. return hasShutdown;
  1775. }
  1776. /**
  1777. * Initialize a ProcessBuilder to run a command using the system shell.
  1778. *
  1779. * @param cmd
  1780. * command to execute. This string should originate from the
  1781. * end-user, and thus is platform specific.
  1782. * @param args
  1783. * arguments to pass to command. These should be protected from
  1784. * shell evaluation.
  1785. * @return a partially completed process builder. Caller should finish
  1786. * populating directory, environment, and then start the process.
  1787. */
  1788. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  1789. /**
  1790. * Execute a command defined by a {@link java.lang.ProcessBuilder}.
  1791. *
  1792. * @param pb
  1793. * The command to be executed
  1794. * @param in
  1795. * The standard input stream passed to the process
  1796. * @return The result of the executed command
  1797. * @throws java.lang.InterruptedException
  1798. * @throws java.io.IOException
  1799. * @since 4.2
  1800. */
  1801. public ExecutionResult execute(ProcessBuilder pb, InputStream in)
  1802. throws IOException, InterruptedException {
  1803. try (TemporaryBuffer stdout = new TemporaryBuffer.LocalFile(null);
  1804. TemporaryBuffer stderr = new TemporaryBuffer.Heap(1024,
  1805. 1024 * 1024)) {
  1806. int rc = runProcess(pb, stdout, stderr, in);
  1807. return new ExecutionResult(stdout, stderr, rc);
  1808. }
  1809. }
  1810. private static class Holder<V> {
  1811. final V value;
  1812. Holder(V value) {
  1813. this.value = value;
  1814. }
  1815. }
  1816. /**
  1817. * File attributes we typically care for.
  1818. *
  1819. * @since 3.3
  1820. */
  1821. public static class Attributes {
  1822. /**
  1823. * @return true if this are the attributes of a directory
  1824. */
  1825. public boolean isDirectory() {
  1826. return isDirectory;
  1827. }
  1828. /**
  1829. * @return true if this are the attributes of an executable file
  1830. */
  1831. public boolean isExecutable() {
  1832. return isExecutable;
  1833. }
  1834. /**
  1835. * @return true if this are the attributes of a symbolic link
  1836. */
  1837. public boolean isSymbolicLink() {
  1838. return isSymbolicLink;
  1839. }
  1840. /**
  1841. * @return true if this are the attributes of a regular file
  1842. */
  1843. public boolean isRegularFile() {
  1844. return isRegularFile;
  1845. }
  1846. /**
  1847. * @return the time when the file was created
  1848. */
  1849. public long getCreationTime() {
  1850. return creationTime;
  1851. }
  1852. /**
  1853. * @return the time (milliseconds since 1970-01-01) when this object was
  1854. * last modified
  1855. * @deprecated use getLastModifiedInstant instead
  1856. */
  1857. @Deprecated
  1858. public long getLastModifiedTime() {
  1859. return lastModifiedInstant.toEpochMilli();
  1860. }
  1861. /**
  1862. * @return the time when this object was last modified
  1863. * @since 5.1.9
  1864. */
  1865. public Instant getLastModifiedInstant() {
  1866. return lastModifiedInstant;
  1867. }
  1868. private final boolean isDirectory;
  1869. private final boolean isSymbolicLink;
  1870. private final boolean isRegularFile;
  1871. private final long creationTime;
  1872. private final Instant lastModifiedInstant;
  1873. private final boolean isExecutable;
  1874. private final File file;
  1875. private final boolean exists;
  1876. /**
  1877. * file length
  1878. */
  1879. protected long length = -1;
  1880. final FS fs;
  1881. Attributes(FS fs, File file, boolean exists, boolean isDirectory,
  1882. boolean isExecutable, boolean isSymbolicLink,
  1883. boolean isRegularFile, long creationTime,
  1884. Instant lastModifiedInstant, long length) {
  1885. this.fs = fs;
  1886. this.file = file;
  1887. this.exists = exists;
  1888. this.isDirectory = isDirectory;
  1889. this.isExecutable = isExecutable;
  1890. this.isSymbolicLink = isSymbolicLink;
  1891. this.isRegularFile = isRegularFile;
  1892. this.creationTime = creationTime;
  1893. this.lastModifiedInstant = lastModifiedInstant;
  1894. this.length = length;
  1895. }
  1896. /**
  1897. * Constructor when there are issues with reading. All attributes except
  1898. * given will be set to the default values.
  1899. *
  1900. * @param fs
  1901. * @param path
  1902. */
  1903. public Attributes(File path, FS fs) {
  1904. this(fs, path, false, false, false, false, false, 0L, EPOCH, 0L);
  1905. }
  1906. /**
  1907. * @return length of this file object
  1908. */
  1909. public long getLength() {
  1910. if (length == -1)
  1911. return length = file.length();
  1912. return length;
  1913. }
  1914. /**
  1915. * @return the filename
  1916. */
  1917. public String getName() {
  1918. return file.getName();
  1919. }
  1920. /**
  1921. * @return the file the attributes apply to
  1922. */
  1923. public File getFile() {
  1924. return file;
  1925. }
  1926. boolean exists() {
  1927. return exists;
  1928. }
  1929. }
  1930. /**
  1931. * Get the file attributes we care for.
  1932. *
  1933. * @param path
  1934. * a {@link java.io.File} object.
  1935. * @return the file attributes we care for.
  1936. * @since 3.3
  1937. */
  1938. public Attributes getAttributes(File path) {
  1939. boolean isDirectory = isDirectory(path);
  1940. boolean isFile = !isDirectory && path.isFile();
  1941. assert path.exists() == isDirectory || isFile;
  1942. boolean exists = isDirectory || isFile;
  1943. boolean canExecute = exists && !isDirectory && canExecute(path);
  1944. boolean isSymlink = false;
  1945. Instant lastModified = exists ? lastModifiedInstant(path) : EPOCH;
  1946. long createTime = 0L;
  1947. return new Attributes(this, path, exists, isDirectory, canExecute,
  1948. isSymlink, isFile, createTime, lastModified, -1);
  1949. }
  1950. /**
  1951. * Normalize the unicode path to composed form.
  1952. *
  1953. * @param file
  1954. * a {@link java.io.File} object.
  1955. * @return NFC-format File
  1956. * @since 3.3
  1957. */
  1958. public File normalize(File file) {
  1959. return file;
  1960. }
  1961. /**
  1962. * Normalize the unicode path to composed form.
  1963. *
  1964. * @param name
  1965. * path name
  1966. * @return NFC-format string
  1967. * @since 3.3
  1968. */
  1969. public String normalize(String name) {
  1970. return name;
  1971. }
  1972. /**
  1973. * This runnable will consume an input stream's content into an output
  1974. * stream as soon as it gets available.
  1975. * <p>
  1976. * Typically used to empty processes' standard output and error, preventing
  1977. * them to choke.
  1978. * </p>
  1979. * <p>
  1980. * <b>Note</b> that a {@link StreamGobbler} will never close either of its
  1981. * streams.
  1982. * </p>
  1983. */
  1984. private static class StreamGobbler implements Runnable {
  1985. private InputStream in;
  1986. private OutputStream out;
  1987. public StreamGobbler(InputStream stream, OutputStream output) {
  1988. this.in = stream;
  1989. this.out = output;
  1990. }
  1991. @Override
  1992. public void run() {
  1993. try {
  1994. copy();
  1995. } catch (IOException e) {
  1996. // Do nothing on read failure; leave streams open.
  1997. }
  1998. }
  1999. void copy() throws IOException {
  2000. boolean writeFailure = false;
  2001. byte buffer[] = new byte[4096];
  2002. int readBytes;
  2003. while ((readBytes = in.read(buffer)) != -1) {
  2004. // Do not try to write again after a failure, but keep
  2005. // reading as long as possible to prevent the input stream
  2006. // from choking.
  2007. if (!writeFailure && out != null) {
  2008. try {
  2009. out.write(buffer, 0, readBytes);
  2010. out.flush();
  2011. } catch (IOException e) {
  2012. writeFailure = true;
  2013. }
  2014. }
  2015. }
  2016. }
  2017. }
  2018. }