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

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