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