1
2
3
4
5
6
7
8
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.Writer;
26 import java.nio.file.AccessDeniedException;
27 import java.nio.file.FileStore;
28 import java.nio.file.Files;
29 import java.nio.file.InvalidPathException;
30 import java.nio.file.Path;
31 import java.nio.file.attribute.BasicFileAttributes;
32 import java.nio.file.attribute.FileTime;
33 import java.security.AccessControlException;
34 import java.security.AccessController;
35 import java.security.PrivilegedAction;
36 import java.text.MessageFormat;
37 import java.time.Duration;
38 import java.time.Instant;
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.HashMap;
42 import java.util.Map;
43 import java.util.Objects;
44 import java.util.Optional;
45 import java.util.UUID;
46 import java.util.concurrent.CancellationException;
47 import java.util.concurrent.CompletableFuture;
48 import java.util.concurrent.ConcurrentHashMap;
49 import java.util.concurrent.ExecutionException;
50 import java.util.concurrent.ExecutorService;
51 import java.util.concurrent.Executors;
52 import java.util.concurrent.LinkedBlockingQueue;
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 java.util.regex.Matcher;
62 import java.util.regex.Pattern;
63
64 import org.eclipse.jgit.annotations.NonNull;
65 import org.eclipse.jgit.annotations.Nullable;
66 import org.eclipse.jgit.api.errors.JGitInternalException;
67 import org.eclipse.jgit.errors.CommandFailedException;
68 import org.eclipse.jgit.errors.ConfigInvalidException;
69 import org.eclipse.jgit.errors.LockFailedException;
70 import org.eclipse.jgit.internal.JGitText;
71 import org.eclipse.jgit.internal.storage.file.FileSnapshot;
72 import org.eclipse.jgit.lib.Config;
73 import org.eclipse.jgit.lib.ConfigConstants;
74 import org.eclipse.jgit.lib.Constants;
75 import org.eclipse.jgit.lib.Repository;
76 import org.eclipse.jgit.lib.StoredConfig;
77 import org.eclipse.jgit.treewalk.FileTreeIterator.FileEntry;
78 import org.eclipse.jgit.treewalk.FileTreeIterator.FileModeStrategy;
79 import org.eclipse.jgit.treewalk.WorkingTreeIterator.Entry;
80 import org.eclipse.jgit.util.ProcessResult.Status;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84
85
86
87 public abstract class FS {
88 private static final Logger LOG = LoggerFactory.getLogger(FS.class);
89
90
91
92
93
94
95
96 protected static final Entry[] NO_ENTRIES = {};
97
98 private static final Pattern VERSION = Pattern
99 .compile("\\s(\\d+)\\.(\\d+)\\.(\\d+)");
100
101 private volatile Boolean supportSymlinks;
102
103
104
105
106
107
108
109 public static class FSFactory {
110
111
112
113 protected FSFactory() {
114
115 }
116
117
118
119
120
121
122
123 public FS detect(Boolean cygwinUsed) {
124 if (SystemReader.getInstance().isWindows()) {
125 if (cygwinUsed == null) {
126 cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
127 }
128 if (cygwinUsed.booleanValue()) {
129 return new FS_Win32_Cygwin();
130 }
131 return new FS_Win32();
132 }
133 return new FS_POSIX();
134 }
135 }
136
137
138
139
140
141
142
143 public static class ExecutionResult {
144 private TemporaryBuffer stdout;
145
146 private TemporaryBuffer stderr;
147
148 private int rc;
149
150
151
152
153
154
155 public ExecutionResult(TemporaryBuffer stdout, TemporaryBuffer stderr,
156 int rc) {
157 this.stdout = stdout;
158 this.stderr = stderr;
159 this.rc = rc;
160 }
161
162
163
164
165 public TemporaryBuffer getStdout() {
166 return stdout;
167 }
168
169
170
171
172 public TemporaryBuffer getStderr() {
173 return stderr;
174 }
175
176
177
178
179 public int getRc() {
180 return rc;
181 }
182 }
183
184
185
186
187
188
189 public static final class FileStoreAttributes {
190
191
192
193
194 private static final Duration UNDEFINED_DURATION = Duration
195 .ofNanos(Long.MAX_VALUE);
196
197
198
199
200
201
202
203
204 public static final Duration FALLBACK_TIMESTAMP_RESOLUTION = Duration
205 .ofMillis(2000);
206
207
208
209
210
211
212 public static final FileStoreAttributes FALLBACK_FILESTORE_ATTRIBUTES = new FileStoreAttributes(
213 FALLBACK_TIMESTAMP_RESOLUTION);
214
215 private static final long ONE_MICROSECOND = TimeUnit.MICROSECONDS
216 .toNanos(1);
217
218 private static final long ONE_MILLISECOND = TimeUnit.MILLISECONDS
219 .toNanos(1);
220
221 private static final long ONE_SECOND = TimeUnit.SECONDS.toNanos(1);
222
223
224
225
226
227
228
229
230
231
232 private static final long MINIMUM_RESOLUTION_NANOS = ONE_MICROSECOND;
233
234 private static final String JAVA_VERSION_PREFIX = System
235 .getProperty("java.vendor") + '|'
236 + System.getProperty("java.version") + '|';
237
238 private static final Duration FALLBACK_MIN_RACY_INTERVAL = Duration
239 .ofMillis(10);
240
241 private static final Map<FileStore, FileStoreAttributes> attributeCache = new ConcurrentHashMap<>();
242
243 private static final SimpleLruCache<Path, FileStoreAttributes> attrCacheByPath = new SimpleLruCache<>(
244 100, 0.2f);
245
246 private static final AtomicBoolean background = new AtomicBoolean();
247
248 private static final Map<FileStore, Lock> locks = new ConcurrentHashMap<>();
249
250 private static final AtomicInteger threadNumber = new AtomicInteger(1);
251
252
253
254
255
256
257
258
259
260
261
262
263
264 private static final ExecutorService FUTURE_RUNNER = new ThreadPoolExecutor(
265 0, 5, 30L, TimeUnit.SECONDS,
266 new LinkedBlockingQueue<Runnable>(),
267 runnable -> {
268 Thread t = new Thread(runnable,
269 "JGit-FileStoreAttributeReader-"
270 + threadNumber.getAndIncrement());
271
272
273 t.setDaemon(true);
274 return t;
275 });
276
277
278
279
280
281
282
283
284
285
286
287
288 private static final ExecutorService SAVE_RUNNER = new ThreadPoolExecutor(
289 0, 1, 1L, TimeUnit.MILLISECONDS,
290 new LinkedBlockingQueue<Runnable>(),
291 runnable -> {
292 Thread t = new Thread(runnable,
293 "JGit-FileStoreAttributeWriter-"
294 + threadNumber.getAndIncrement());
295
296 t.setDaemon(false);
297 return t;
298 });
299
300 static {
301
302 try {
303 Runtime.getRuntime().addShutdownHook(new Thread(() -> {
304 try {
305 SAVE_RUNNER.shutdownNow();
306 SAVE_RUNNER.awaitTermination(100,
307 TimeUnit.MILLISECONDS);
308 } catch (Exception e) {
309
310 }
311 }));
312 } catch (IllegalStateException e) {
313
314 }
315 }
316
317
318
319
320
321
322
323
324
325
326 public static void setBackground(boolean async) {
327 background.set(async);
328 }
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345 public static void configureAttributesPathCache(int maxSize,
346 float purgeFactor) {
347 FileStoreAttributes.attrCacheByPath.configure(maxSize, purgeFactor);
348 }
349
350
351
352
353
354
355
356
357 public static FileStoreAttributes get(Path path) {
358 try {
359 path = path.toAbsolutePath();
360 Path dir = Files.isDirectory(path) ? path : path.getParent();
361 if (dir == null) {
362 return FALLBACK_FILESTORE_ATTRIBUTES;
363 }
364 FileStoreAttributes cached = attrCacheByPath.get(dir);
365 if (cached != null) {
366 return cached;
367 }
368 FileStoreAttributes attrs = getFileStoreAttributes(dir);
369 if (attrs == null) {
370
371 return FALLBACK_FILESTORE_ATTRIBUTES;
372 }
373 attrCacheByPath.put(dir, attrs);
374 return attrs;
375 } catch (SecurityException e) {
376 return FALLBACK_FILESTORE_ATTRIBUTES;
377 }
378 }
379
380 private static FileStoreAttributes getFileStoreAttributes(Path dir) {
381 FileStore s;
382 try {
383 if (Files.exists(dir)) {
384 s = Files.getFileStore(dir);
385 FileStoreAttributes c = attributeCache.get(s);
386 if (c != null) {
387 return c;
388 }
389 if (!Files.isWritable(dir)) {
390
391 LOG.debug(
392 "{}: cannot measure timestamp resolution in read-only directory {}",
393 Thread.currentThread(), dir);
394 return FALLBACK_FILESTORE_ATTRIBUTES;
395 }
396 } else {
397
398 LOG.debug(
399 "{}: cannot measure timestamp resolution of unborn directory {}",
400 Thread.currentThread(), dir);
401 return FALLBACK_FILESTORE_ATTRIBUTES;
402 }
403
404 CompletableFuture<Optional<FileStoreAttributes>> f = CompletableFuture
405 .supplyAsync(() -> {
406 Lock lock = locks.computeIfAbsent(s,
407 l -> new ReentrantLock());
408 if (!lock.tryLock()) {
409 LOG.debug(
410 "{}: couldn't get lock to measure timestamp resolution in {}",
411 Thread.currentThread(), dir);
412 return Optional.empty();
413 }
414 Optional<FileStoreAttributes> attributes = Optional
415 .empty();
416 try {
417
418
419
420 FileStoreAttributes c = attributeCache.get(s);
421 if (c != null) {
422 return Optional.of(c);
423 }
424 attributes = readFromConfig(s);
425 if (attributes.isPresent()) {
426 attributeCache.put(s, attributes.get());
427 return attributes;
428 }
429
430 Optional<Duration> resolution = measureFsTimestampResolution(
431 s, dir);
432 if (resolution.isPresent()) {
433 c = new FileStoreAttributes(
434 resolution.get());
435 attributeCache.put(s, c);
436
437
438 if (c.fsTimestampResolution
439 .toNanos() < 100_000_000L) {
440 c.minimalRacyInterval = measureMinimalRacyInterval(
441 dir);
442 }
443 if (LOG.isDebugEnabled()) {
444 LOG.debug(c.toString());
445 }
446 FileStoreAttributes newAttrs = c;
447 SAVE_RUNNER.execute(
448 () -> saveToConfig(s, newAttrs));
449 }
450 attributes = Optional.of(c);
451 } finally {
452 lock.unlock();
453 locks.remove(s);
454 }
455 return attributes;
456 }, FUTURE_RUNNER);
457 f = f.exceptionally(e -> {
458 LOG.error(e.getLocalizedMessage(), e);
459 return Optional.empty();
460 });
461
462
463 boolean runInBackground = background.get();
464 Optional<FileStoreAttributes> d = runInBackground ? f.get(
465 100, TimeUnit.MILLISECONDS) : f.get();
466 if (d.isPresent()) {
467 return d.get();
468 } else if (runInBackground) {
469
470 return null;
471 }
472
473 } catch (IOException | ExecutionException | CancellationException e) {
474 LOG.error(e.getMessage(), e);
475 } catch (TimeoutException | SecurityException e) {
476
477 } catch (InterruptedException e) {
478 LOG.error(e.getMessage(), e);
479 Thread.currentThread().interrupt();
480 }
481 LOG.debug("{}: use fallback timestamp resolution for directory {}",
482 Thread.currentThread(), dir);
483 return FALLBACK_FILESTORE_ATTRIBUTES;
484 }
485
486 @SuppressWarnings("boxing")
487 private static Duration measureMinimalRacyInterval(Path dir) {
488 LOG.debug("{}: start measure minimal racy interval in {}",
489 Thread.currentThread(), dir);
490 int n = 0;
491 int failures = 0;
492 long racyNanos = 0;
493 ArrayList<Long> deltas = new ArrayList<>();
494 Path probe = dir.resolve(".probe-" + UUID.randomUUID());
495 Instant end = Instant.now().plusSeconds(3);
496 try {
497 probe.toFile().deleteOnExit();
498 Files.createFile(probe);
499 do {
500 n++;
501 write(probe, "a");
502 FileSnapshot snapshot = FileSnapshot.save(probe.toFile());
503 read(probe);
504 write(probe, "b");
505 if (!snapshot.isModified(probe.toFile())) {
506 deltas.add(Long.valueOf(snapshot.lastDelta()));
507 racyNanos = snapshot.lastRacyThreshold();
508 failures++;
509 }
510 } while (Instant.now().compareTo(end) < 0);
511 } catch (IOException e) {
512 LOG.error(e.getMessage(), e);
513 return FALLBACK_MIN_RACY_INTERVAL;
514 } finally {
515 deleteProbe(probe);
516 }
517 if (failures > 0) {
518 Stats stats = new Stats();
519 for (Long d : deltas) {
520 stats.add(d);
521 }
522 LOG.debug(
523 "delta [ns] since modification FileSnapshot failed to detect\n"
524 + "count, failures, racy limit [ns], delta min [ns],"
525 + " delta max [ns], delta avg [ns],"
526 + " delta stddev [ns]\n"
527 + "{}, {}, {}, {}, {}, {}, {}",
528 n, failures, racyNanos, stats.min(), stats.max(),
529 stats.avg(), stats.stddev());
530 return Duration
531 .ofNanos(Double.valueOf(stats.max()).longValue());
532 }
533
534
535 LOG.debug("{}: no failures when measuring minimal racy interval",
536 Thread.currentThread());
537 return Duration.ZERO;
538 }
539
540 private static void write(Path p, String body) throws IOException {
541 Path parent = p.getParent();
542 if (parent != null) {
543 FileUtils.mkdirs(parent.toFile(), true);
544 }
545 try (Writer w = new OutputStreamWriter(Files.newOutputStream(p),
546 UTF_8)) {
547 w.write(body);
548 }
549 }
550
551 private static String read(Path p) throws IOException {
552 byte[] body = IO.readFully(p.toFile());
553 return new String(body, 0, body.length, UTF_8);
554 }
555
556 private static Optional<Duration> measureFsTimestampResolution(
557 FileStore s, Path dir) {
558 if (LOG.isDebugEnabled()) {
559 LOG.debug("{}: start measure timestamp resolution {} in {}",
560 Thread.currentThread(), s, dir);
561 }
562 Path probe = dir.resolve(".probe-" + UUID.randomUUID());
563 try {
564 probe.toFile().deleteOnExit();
565 Files.createFile(probe);
566 Duration fsResolution = getFsResolution(s, dir, probe);
567 Duration clockResolution = measureClockResolution();
568 fsResolution = fsResolution.plus(clockResolution);
569 if (LOG.isDebugEnabled()) {
570 LOG.debug(
571 "{}: end measure timestamp resolution {} in {}; got {}",
572 Thread.currentThread(), s, dir, fsResolution);
573 }
574 return Optional.of(fsResolution);
575 } catch (SecurityException e) {
576
577
578
579 LOG.warn(e.getLocalizedMessage(), e);
580 } catch (AccessDeniedException e) {
581 LOG.warn(e.getLocalizedMessage(), e);
582 } catch (IOException e) {
583 LOG.error(e.getLocalizedMessage(), e);
584 } finally {
585 deleteProbe(probe);
586 }
587 return Optional.empty();
588 }
589
590 private static Duration getFsResolution(FileStore s, Path dir,
591 Path probe) throws IOException {
592 File probeFile = probe.toFile();
593 FileTime t1 = Files.getLastModifiedTime(probe);
594 Instant t1i = t1.toInstant();
595 FileTime t2;
596 Duration last = FALLBACK_TIMESTAMP_RESOLUTION;
597 long minScale = MINIMUM_RESOLUTION_NANOS;
598 long scale = ONE_SECOND;
599 long high = TimeUnit.MILLISECONDS.toSeconds(last.toMillis());
600 long low = 0;
601
602 long[] tries = { ONE_MICROSECOND, ONE_MILLISECOND };
603 for (long interval : tries) {
604 if (interval >= ONE_MILLISECOND) {
605 probeFile.setLastModified(
606 t1i.plusNanos(interval).toEpochMilli());
607 } else {
608 Files.setLastModifiedTime(probe,
609 FileTime.from(t1i.plusNanos(interval)));
610 }
611 t2 = Files.getLastModifiedTime(probe);
612 if (t2.compareTo(t1) > 0) {
613 Duration diff = Duration.between(t1i, t2.toInstant());
614 if (!diff.isZero() && !diff.isNegative()
615 && diff.compareTo(last) < 0) {
616 scale = interval;
617 high = 1;
618 last = diff;
619 break;
620 }
621 } else {
622
623 minScale = Math.max(minScale, interval);
624 }
625 }
626
627 while (high > low) {
628 long mid = (high + low) / 2;
629 if (mid == 0) {
630
631 long newScale = scale / 10;
632 if (newScale < minScale) {
633 break;
634 }
635 high *= scale / newScale;
636 low *= scale / newScale;
637 scale = newScale;
638 mid = (high + low) / 2;
639 }
640 long delta = mid * scale;
641 if (scale >= ONE_MILLISECOND) {
642 probeFile.setLastModified(
643 t1i.plusNanos(delta).toEpochMilli());
644 } else {
645 Files.setLastModifiedTime(probe,
646 FileTime.from(t1i.plusNanos(delta)));
647 }
648 t2 = Files.getLastModifiedTime(probe);
649 int cmp = t2.compareTo(t1);
650 if (cmp > 0) {
651 high = mid;
652 Duration diff = Duration.between(t1i, t2.toInstant());
653 if (diff.isZero() || diff.isNegative()) {
654 LOG.warn(JGitText.get().logInconsistentFiletimeDiff,
655 Thread.currentThread(), s, dir, t2, t1, diff,
656 last);
657 break;
658 } else if (diff.compareTo(last) > 0) {
659 LOG.warn(JGitText.get().logLargerFiletimeDiff,
660 Thread.currentThread(), s, dir, diff, last);
661 break;
662 }
663 last = diff;
664 } else if (cmp < 0) {
665 LOG.warn(JGitText.get().logSmallerFiletime,
666 Thread.currentThread(), s, dir, t2, t1, last);
667 break;
668 } else {
669
670 low = mid + 1;
671 }
672 }
673 return last;
674 }
675
676 private static Duration measureClockResolution() {
677 Duration clockResolution = Duration.ZERO;
678 for (int i = 0; i < 10; i++) {
679 Instant t1 = Instant.now();
680 Instant t2 = t1;
681 while (t2.compareTo(t1) <= 0) {
682 t2 = Instant.now();
683 }
684 Duration r = Duration.between(t1, t2);
685 if (r.compareTo(clockResolution) > 0) {
686 clockResolution = r;
687 }
688 }
689 return clockResolution;
690 }
691
692 private static void deleteProbe(Path probe) {
693 try {
694 FileUtils.delete(probe.toFile(),
695 FileUtils.SKIP_MISSING | FileUtils.RETRY);
696 } catch (IOException e) {
697 LOG.error(e.getMessage(), e);
698 }
699 }
700
701 private static Optional<FileStoreAttributes> readFromConfig(
702 FileStore s) {
703 StoredConfig userConfig;
704 try {
705 userConfig = SystemReader.getInstance().getUserConfig();
706 } catch (IOException | ConfigInvalidException e) {
707 LOG.error(JGitText.get().readFileStoreAttributesFailed, e);
708 return Optional.empty();
709 }
710 String key = getConfigKey(s);
711 Duration resolution = Duration.ofNanos(userConfig.getTimeUnit(
712 ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
713 ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION,
714 UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS));
715 if (UNDEFINED_DURATION.equals(resolution)) {
716 return Optional.empty();
717 }
718 Duration minRacyThreshold = Duration.ofNanos(userConfig.getTimeUnit(
719 ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
720 ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD,
721 UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS));
722 FileStoreAttributes c = new FileStoreAttributes(resolution);
723 if (!UNDEFINED_DURATION.equals(minRacyThreshold)) {
724 c.minimalRacyInterval = minRacyThreshold;
725 }
726 return Optional.of(c);
727 }
728
729 private static void saveToConfig(FileStore s,
730 FileStoreAttributes c) {
731 StoredConfig jgitConfig;
732 try {
733 jgitConfig = SystemReader.getInstance().getJGitConfig();
734 } catch (IOException | ConfigInvalidException e) {
735 LOG.error(JGitText.get().saveFileStoreAttributesFailed, e);
736 return;
737 }
738 long resolution = c.getFsTimestampResolution().toNanos();
739 TimeUnit resolutionUnit = getUnit(resolution);
740 long resolutionValue = resolutionUnit.convert(resolution,
741 TimeUnit.NANOSECONDS);
742
743 long minRacyThreshold = c.getMinimalRacyInterval().toNanos();
744 TimeUnit minRacyThresholdUnit = getUnit(minRacyThreshold);
745 long minRacyThresholdValue = minRacyThresholdUnit
746 .convert(minRacyThreshold, TimeUnit.NANOSECONDS);
747
748 final int max_retries = 5;
749 int retries = 0;
750 boolean succeeded = false;
751 String key = getConfigKey(s);
752 while (!succeeded && retries < max_retries) {
753 try {
754 jgitConfig.setString(
755 ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
756 ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION,
757 String.format("%d %s",
758 Long.valueOf(resolutionValue),
759 resolutionUnit.name().toLowerCase()));
760 jgitConfig.setString(
761 ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
762 ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD,
763 String.format("%d %s",
764 Long.valueOf(minRacyThresholdValue),
765 minRacyThresholdUnit.name().toLowerCase()));
766 jgitConfig.save();
767 succeeded = true;
768 } catch (LockFailedException e) {
769
770 try {
771 retries++;
772 if (retries < max_retries) {
773 Thread.sleep(100);
774 LOG.debug("locking {} failed, retries {}/{}",
775 jgitConfig, Integer.valueOf(retries),
776 Integer.valueOf(max_retries));
777 } else {
778 LOG.warn(MessageFormat.format(
779 JGitText.get().lockFailedRetry, jgitConfig,
780 Integer.valueOf(retries)));
781 }
782 } catch (InterruptedException e1) {
783 Thread.currentThread().interrupt();
784 break;
785 }
786 } catch (IOException e) {
787 LOG.error(MessageFormat.format(
788 JGitText.get().cannotSaveConfig, jgitConfig), e);
789 break;
790 }
791 }
792 }
793
794 private static String getConfigKey(FileStore s) {
795 String storeKey;
796 if (SystemReader.getInstance().isWindows()) {
797 Object attribute = null;
798 try {
799 attribute = s.getAttribute("volume:vsn");
800 } catch (IOException ignored) {
801
802 }
803 if (attribute instanceof Integer) {
804 storeKey = attribute.toString();
805 } else {
806 storeKey = s.name();
807 }
808 } else {
809 storeKey = s.name();
810 }
811 return JAVA_VERSION_PREFIX + storeKey;
812 }
813
814 private static TimeUnit getUnit(long nanos) {
815 TimeUnit unit;
816 if (nanos < 200_000L) {
817 unit = TimeUnit.NANOSECONDS;
818 } else if (nanos < 200_000_000L) {
819 unit = TimeUnit.MICROSECONDS;
820 } else {
821 unit = TimeUnit.MILLISECONDS;
822 }
823 return unit;
824 }
825
826 private final @NonNull Duration fsTimestampResolution;
827
828 private Duration minimalRacyInterval;
829
830
831
832
833
834
835 public Duration getMinimalRacyInterval() {
836 return minimalRacyInterval;
837 }
838
839
840
841
842 @NonNull
843 public Duration getFsTimestampResolution() {
844 return fsTimestampResolution;
845 }
846
847
848
849
850
851
852
853 public FileStoreAttributes(
854 @NonNull Duration fsTimestampResolution) {
855 this.fsTimestampResolution = fsTimestampResolution;
856 this.minimalRacyInterval = Duration.ZERO;
857 }
858
859 @SuppressWarnings({ "nls", "boxing" })
860 @Override
861 public String toString() {
862 return String.format(
863 "FileStoreAttributes[fsTimestampResolution=%,d µs, "
864 + "minimalRacyInterval=%,d µs]",
865 fsTimestampResolution.toNanos() / 1000,
866 minimalRacyInterval.toNanos() / 1000);
867 }
868
869 }
870
871
872 public static final FS DETECTED = detect();
873
874 private static volatile FSFactory factory;
875
876
877
878
879
880
881 public static FS detect() {
882 return detect(null);
883 }
884
885
886
887
888
889
890
891
892
893
894
895 @Deprecated
896 public static void setAsyncFileStoreAttributes(boolean asynch) {
897 FileStoreAttributes.setBackground(asynch);
898 }
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920 public static FS detect(Boolean cygwinUsed) {
921 if (factory == null) {
922 factory = new FS.FSFactory();
923 }
924 return factory.detect(cygwinUsed);
925 }
926
927
928
929
930
931
932
933
934
935
936
937 public static FileStoreAttributes getFileStoreAttributes(
938 @NonNull Path dir) {
939 return FileStoreAttributes.get(dir);
940 }
941
942 private volatile Holder<File> userHome;
943
944 private volatile Holder<File> gitSystemConfig;
945
946
947
948
949 protected FS() {
950
951 }
952
953
954
955
956
957
958
959 protected FS(FS src) {
960 userHome = src.userHome;
961 gitSystemConfig = src.gitSystemConfig;
962 }
963
964
965
966
967
968
969 public abstract FS newInstance();
970
971
972
973
974
975
976
977 public abstract boolean supportsExecute();
978
979
980
981
982
983
984
985
986
987
988
989
990 public boolean supportsAtomicCreateNewFile() {
991 return true;
992 }
993
994
995
996
997
998
999
1000
1001 public boolean supportsSymlinks() {
1002 if (supportSymlinks == null) {
1003 detectSymlinkSupport();
1004 }
1005 return Boolean.TRUE.equals(supportSymlinks);
1006 }
1007
1008 private void detectSymlinkSupport() {
1009 File tempFile = null;
1010 try {
1011 tempFile = File.createTempFile("tempsymlinktarget", "");
1012 File linkName = new File(tempFile.getParentFile(), "tempsymlink");
1013 createSymLink(linkName, tempFile.getPath());
1014 supportSymlinks = Boolean.TRUE;
1015 linkName.delete();
1016 } catch (IOException | UnsupportedOperationException | SecurityException
1017 | InternalError e) {
1018 supportSymlinks = Boolean.FALSE;
1019 } finally {
1020 if (tempFile != null) {
1021 try {
1022 FileUtils.delete(tempFile);
1023 } catch (IOException e) {
1024 LOG.error(JGitText.get().cannotDeleteFile, tempFile);
1025 }
1026 }
1027 }
1028 }
1029
1030
1031
1032
1033
1034
1035 public abstract boolean isCaseSensitive();
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051 public abstract boolean canExecute(File f);
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066 public abstract boolean setExecute(File f, boolean canExec);
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080 @Deprecated
1081 public long lastModified(File f) throws IOException {
1082 return FileUtils.lastModified(f);
1083 }
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095 public Instant lastModifiedInstant(Path p) {
1096 return FileUtils.lastModifiedInstant(p);
1097 }
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109 public Instant lastModifiedInstant(File f) {
1110 return FileUtils.lastModifiedInstant(f.toPath());
1111 }
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126 @Deprecated
1127 public void setLastModified(File f, long time) throws IOException {
1128 FileUtils.setLastModified(f, time);
1129 }
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143 public void setLastModified(Path p, Instant time) throws IOException {
1144 FileUtils.setLastModified(p, time);
1145 }
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157 public long length(File path) throws IOException {
1158 return FileUtils.getLength(path);
1159 }
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170 public void delete(File f) throws IOException {
1171 FileUtils.delete(f);
1172 }
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192 public File resolve(File dir, String name) {
1193 File abspn = new File(name);
1194 if (abspn.isAbsolute())
1195 return abspn;
1196 return new File(dir, name);
1197 }
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210 public File userHome() {
1211 Holder<File> p = userHome;
1212 if (p == null) {
1213 p = new Holder<>(safeUserHomeImpl());
1214 userHome = p;
1215 }
1216 return p.value;
1217 }
1218
1219 private File safeUserHomeImpl() {
1220 File home;
1221 try {
1222 home = userHomeImpl();
1223 if (home != null) {
1224 home.toPath();
1225 return home;
1226 }
1227 } catch (RuntimeException e) {
1228 LOG.error(JGitText.get().exceptionWhileFindingUserHome, e);
1229 }
1230 home = defaultUserHomeImpl();
1231 if (home != null) {
1232 try {
1233 home.toPath();
1234 return home;
1235 } catch (InvalidPathException e) {
1236 LOG.error(MessageFormat
1237 .format(JGitText.get().invalidHomeDirectory, home), e);
1238 }
1239 }
1240 return null;
1241 }
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251 public FS setUserHome(File path) {
1252 userHome = new Holder<>(path);
1253 return this;
1254 }
1255
1256
1257
1258
1259
1260
1261 public abstract boolean retryFailedLockFileCommit();
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272 public BasicFileAttributes fileAttributes(File file) throws IOException {
1273 return FileUtils.fileAttributes(file);
1274 }
1275
1276
1277
1278
1279
1280
1281 protected File userHomeImpl() {
1282 return defaultUserHomeImpl();
1283 }
1284
1285 private File defaultUserHomeImpl() {
1286 String home = AccessController.doPrivileged(
1287 (PrivilegedAction<String>) () -> System.getProperty("user.home")
1288 );
1289 if (home == null || home.length() == 0)
1290 return null;
1291 return new File(home).getAbsoluteFile();
1292 }
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306 protected static File searchPath(String path, String... lookFor) {
1307 if (path == null) {
1308 return null;
1309 }
1310
1311 for (String p : path.split(File.pathSeparator)) {
1312 for (String command : lookFor) {
1313 File file = new File(p, command);
1314 try {
1315 if (file.isFile() && file.canExecute()) {
1316 return file.getAbsoluteFile();
1317 }
1318 } catch (SecurityException e) {
1319 LOG.warn(MessageFormat.format(
1320 JGitText.get().skipNotAccessiblePath,
1321 file.getPath()));
1322 }
1323 }
1324 }
1325 return null;
1326 }
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342 @Nullable
1343 protected static String readPipe(File dir, String[] command,
1344 String encoding) throws CommandFailedException {
1345 return readPipe(dir, command, encoding, null);
1346 }
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366 @Nullable
1367 protected static String readPipe(File dir, String[] command,
1368 String encoding, Map<String, String> env)
1369 throws CommandFailedException {
1370 boolean debug = LOG.isDebugEnabled();
1371 try {
1372 if (debug) {
1373 LOG.debug("readpipe " + Arrays.asList(command) + ","
1374 + dir);
1375 }
1376 ProcessBuilder pb = new ProcessBuilder(command);
1377 pb.directory(dir);
1378 if (env != null) {
1379 pb.environment().putAll(env);
1380 }
1381 Process p;
1382 try {
1383 p = pb.start();
1384 } catch (IOException e) {
1385
1386 throw new CommandFailedException(-1, e.getMessage(), e);
1387 }
1388 p.getOutputStream().close();
1389 GobblerThread gobbler = new GobblerThread(p, command, dir);
1390 gobbler.start();
1391 String r = null;
1392 try (BufferedReader lineRead = new BufferedReader(
1393 new InputStreamReader(p.getInputStream(), encoding))) {
1394 r = lineRead.readLine();
1395 if (debug) {
1396 LOG.debug("readpipe may return '" + r + "'");
1397 LOG.debug("remaining output:\n");
1398 String l;
1399 while ((l = lineRead.readLine()) != null) {
1400 LOG.debug(l);
1401 }
1402 }
1403 }
1404
1405 for (;;) {
1406 try {
1407 int rc = p.waitFor();
1408 gobbler.join();
1409 if (rc == 0 && !gobbler.fail.get()) {
1410 return r;
1411 }
1412 if (debug) {
1413 LOG.debug("readpipe rc=" + rc);
1414 }
1415 throw new CommandFailedException(rc,
1416 gobbler.errorMessage.get(),
1417 gobbler.exception.get());
1418 } catch (InterruptedException ie) {
1419
1420 }
1421 }
1422 } catch (IOException e) {
1423 LOG.error("Caught exception in FS.readPipe()", e);
1424 } catch (AccessControlException e) {
1425 LOG.warn(MessageFormat.format(
1426 JGitText.get().readPipeIsNotAllowedRequiredPermission,
1427 command, dir, e.getPermission()));
1428 } catch (SecurityException e) {
1429 LOG.warn(MessageFormat.format(JGitText.get().readPipeIsNotAllowed,
1430 command, dir));
1431 }
1432 if (debug) {
1433 LOG.debug("readpipe returns null");
1434 }
1435 return null;
1436 }
1437
1438 private static class GobblerThread extends Thread {
1439
1440
1441 private static final int PROCESS_EXIT_TIMEOUT = 5;
1442
1443 private final Process p;
1444 private final String desc;
1445 private final String dir;
1446 final AtomicBoolean fail = new AtomicBoolean();
1447 final AtomicReference<String> errorMessage = new AtomicReference<>();
1448 final AtomicReference<Throwable> exception = new AtomicReference<>();
1449
1450 GobblerThread(Process p, String[] command, File dir) {
1451 this.p = p;
1452 this.desc = Arrays.toString(command);
1453 this.dir = Objects.toString(dir);
1454 }
1455
1456 @Override
1457 public void run() {
1458 StringBuilder err = new StringBuilder();
1459 try (InputStream is = p.getErrorStream()) {
1460 int ch;
1461 while ((ch = is.read()) != -1) {
1462 err.append((char) ch);
1463 }
1464 } catch (IOException e) {
1465 if (waitForProcessCompletion(e) && p.exitValue() != 0) {
1466 setError(e, e.getMessage(), p.exitValue());
1467 fail.set(true);
1468 } else {
1469
1470
1471 }
1472 } finally {
1473 if (waitForProcessCompletion(null) && err.length() > 0) {
1474 setError(null, err.toString(), p.exitValue());
1475 if (p.exitValue() != 0) {
1476 fail.set(true);
1477 }
1478 }
1479 }
1480 }
1481
1482 @SuppressWarnings("boxing")
1483 private boolean waitForProcessCompletion(IOException originalError) {
1484 try {
1485 if (!p.waitFor(PROCESS_EXIT_TIMEOUT, TimeUnit.SECONDS)) {
1486 setError(originalError, MessageFormat.format(
1487 JGitText.get().commandClosedStderrButDidntExit,
1488 desc, PROCESS_EXIT_TIMEOUT), -1);
1489 fail.set(true);
1490 return false;
1491 }
1492 } catch (InterruptedException e) {
1493 setError(originalError, MessageFormat.format(
1494 JGitText.get().threadInterruptedWhileRunning, desc), -1);
1495 fail.set(true);
1496 return false;
1497 }
1498 return true;
1499 }
1500
1501 private void setError(IOException e, String message, int exitCode) {
1502 exception.set(e);
1503 errorMessage.set(MessageFormat.format(
1504 JGitText.get().exceptionCaughtDuringExecutionOfCommand,
1505 desc, dir, Integer.valueOf(exitCode), message));
1506 }
1507 }
1508
1509
1510
1511
1512
1513
1514
1515
1516 protected abstract File discoverGitExe();
1517
1518
1519
1520
1521
1522
1523
1524
1525 protected File discoverGitSystemConfig() {
1526 File gitExe = discoverGitExe();
1527 if (gitExe == null) {
1528 return null;
1529 }
1530
1531
1532 String v;
1533 try {
1534 v = readPipe(gitExe.getParentFile(),
1535 new String[] { gitExe.getPath(), "--version" },
1536 SystemReader.getInstance().getDefaultCharset().name());
1537 } catch (CommandFailedException e) {
1538 LOG.warn(e.getMessage());
1539 return null;
1540 }
1541 if (StringUtils.isEmptyOrNull(v)
1542 || (v != null && v.startsWith("jgit"))) {
1543 return null;
1544 }
1545
1546 if (parseVersion(v) < makeVersion(2, 8, 0)) {
1547
1548
1549
1550 Map<String, String> env = new HashMap<>();
1551 env.put("GIT_EDITOR", "echo");
1552
1553 String w;
1554 try {
1555
1556 w = readPipe(gitExe.getParentFile(),
1557 new String[] { gitExe.getPath(), "config", "--system",
1558 "--edit" },
1559 SystemReader.getInstance().getDefaultCharset().name(),
1560 env);
1561 } catch (CommandFailedException e) {
1562 LOG.warn(e.getMessage());
1563 return null;
1564 }
1565 if (StringUtils.isEmptyOrNull(w)) {
1566 return null;
1567 }
1568
1569 return new File(w);
1570 }
1571 String w;
1572 try {
1573 w = readPipe(gitExe.getParentFile(),
1574 new String[] { gitExe.getPath(), "config", "--system",
1575 "--show-origin", "--list", "-z" },
1576 SystemReader.getInstance().getDefaultCharset().name());
1577 } catch (CommandFailedException e) {
1578
1579 if (LOG.isDebugEnabled()) {
1580 LOG.debug(e.getMessage());
1581 }
1582 return null;
1583 }
1584 if (w == null) {
1585 return null;
1586 }
1587
1588
1589
1590 int nul = w.indexOf(0);
1591 if (nul <= 0) {
1592 return null;
1593 }
1594 w = w.substring(0, nul);
1595 int colon = w.indexOf(':');
1596 if (colon < 0) {
1597 return null;
1598 }
1599 w = w.substring(colon + 1);
1600 return w.isEmpty() ? null : new File(w);
1601 }
1602
1603 private long parseVersion(String version) {
1604 Matcher m = VERSION.matcher(version);
1605 if (m.find()) {
1606 try {
1607 return makeVersion(
1608 Integer.parseInt(m.group(1)),
1609 Integer.parseInt(m.group(2)),
1610 Integer.parseInt(m.group(3)));
1611 } catch (NumberFormatException e) {
1612
1613 }
1614 }
1615 return -1;
1616 }
1617
1618 private long makeVersion(int major, int minor, int patch) {
1619 return ((major * 10_000L) + minor) * 10_000L + patch;
1620 }
1621
1622
1623
1624
1625
1626
1627
1628
1629 public File getGitSystemConfig() {
1630 if (gitSystemConfig == null) {
1631 gitSystemConfig = new Holder<>(discoverGitSystemConfig());
1632 }
1633 return gitSystemConfig.value;
1634 }
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644 public FS setGitSystemConfig(File configFile) {
1645 gitSystemConfig = new Holder<>(configFile);
1646 return this;
1647 }
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658 protected static File resolveGrandparentFile(File grandchild) {
1659 if (grandchild != null) {
1660 File parent = grandchild.getParentFile();
1661 if (parent != null)
1662 return parent.getParentFile();
1663 }
1664 return null;
1665 }
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676 public String readSymLink(File path) throws IOException {
1677 return FileUtils.readSymLink(path);
1678 }
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689 public boolean isSymLink(File path) throws IOException {
1690 return FileUtils.isSymlink(path);
1691 }
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702 public boolean exists(File path) {
1703 return FileUtils.exists(path);
1704 }
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715 public boolean isDirectory(File path) {
1716 return FileUtils.isDirectory(path);
1717 }
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728 public boolean isFile(File path) {
1729 return FileUtils.isFile(path);
1730 }
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743 public boolean isHidden(File path) throws IOException {
1744 return FileUtils.isHidden(path);
1745 }
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757 public void setHidden(File path, boolean hidden) throws IOException {
1758 FileUtils.setHidden(path, hidden);
1759 }
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771 public void createSymLink(File path, String target) throws IOException {
1772 FileUtils.createSymLink(path, target);
1773 }
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788 @Deprecated
1789 public boolean createNewFile(File path) throws IOException {
1790 return path.createNewFile();
1791 }
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802 public static class LockToken implements Closeable {
1803 private boolean isCreated;
1804
1805 private Optional<Path> link;
1806
1807 LockToken(boolean isCreated, Optional<Path> link) {
1808 this.isCreated = isCreated;
1809 this.link = link;
1810 }
1811
1812
1813
1814
1815 public boolean isCreated() {
1816 return isCreated;
1817 }
1818
1819 @Override
1820 public void close() {
1821 if (!link.isPresent()) {
1822 return;
1823 }
1824 Path p = link.get();
1825 if (!Files.exists(p)) {
1826 return;
1827 }
1828 try {
1829 Files.delete(p);
1830 } catch (IOException e) {
1831 LOG.error(MessageFormat
1832 .format(JGitText.get().closeLockTokenFailed, this), e);
1833 }
1834 }
1835
1836 @Override
1837 public String toString() {
1838 return "LockToken [lockCreated=" + isCreated +
1839 ", link="
1840 + (link.isPresent() ? link.get().getFileName() + "]"
1841 : "<null>]");
1842 }
1843 }
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857 public LockToken createNewFileAtomic(File path) throws IOException {
1858 return new LockToken(path.createNewFile(), Optional.empty());
1859 }
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875 public String relativize(String base, String other) {
1876 return FileUtils.relativizePath(base, other, File.separator, this.isCaseSensitive());
1877 }
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890 public Entry[] list(File directory, FileModeStrategy fileModeStrategy) {
1891 File[] all = directory.listFiles();
1892 if (all == null) {
1893 return NO_ENTRIES;
1894 }
1895 Entry[] result = new Entry[all.length];
1896 for (int i = 0; i < result.length; i++) {
1897 result[i] = new FileEntry(all[i], this, fileModeStrategy);
1898 }
1899 return result;
1900 }
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924 public ProcessResult runHookIfPresent(Repository repository,
1925 String hookName, String[] args) throws JGitInternalException {
1926 return runHookIfPresent(repository, hookName, args, System.out,
1927 System.err, null);
1928 }
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958 public ProcessResult runHookIfPresent(Repository repository,
1959 String hookName, String[] args, OutputStream outRedirect,
1960 OutputStream errRedirect, String stdinArgs)
1961 throws JGitInternalException {
1962 return new ProcessResult(Status.NOT_SUPPORTED);
1963 }
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994 protected ProcessResult internalRunHookIfPresent(Repository repository,
1995 String hookName, String[] args, OutputStream outRedirect,
1996 OutputStream errRedirect, String stdinArgs)
1997 throws JGitInternalException {
1998 File hookFile = findHook(repository, hookName);
1999 if (hookFile == null || hookName == null) {
2000 return new ProcessResult(Status.NOT_PRESENT);
2001 }
2002
2003 File runDirectory = getRunDirectory(repository, hookName);
2004 if (runDirectory == null) {
2005 return new ProcessResult(Status.NOT_PRESENT);
2006 }
2007 String cmd = hookFile.getAbsolutePath();
2008 ProcessBuilder hookProcess = runInShell(shellQuote(cmd), args);
2009 hookProcess.directory(runDirectory.getAbsoluteFile());
2010 Map<String, String> environment = hookProcess.environment();
2011 environment.put(Constants.GIT_DIR_KEY,
2012 repository.getDirectory().getAbsolutePath());
2013 if (!repository.isBare()) {
2014 environment.put(Constants.GIT_WORK_TREE_KEY,
2015 repository.getWorkTree().getAbsolutePath());
2016 }
2017 try {
2018 return new ProcessResult(runProcess(hookProcess, outRedirect,
2019 errRedirect, stdinArgs), Status.OK);
2020 } catch (IOException e) {
2021 throw new JGitInternalException(MessageFormat.format(
2022 JGitText.get().exceptionCaughtDuringExecutionOfHook,
2023 hookName), e);
2024 } catch (InterruptedException e) {
2025 throw new JGitInternalException(MessageFormat.format(
2026 JGitText.get().exceptionHookExecutionInterrupted,
2027 hookName), e);
2028 }
2029 }
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043 String shellQuote(String cmd) {
2044 return cmd;
2045 }
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058 public File findHook(Repository repository, String hookName) {
2059 if (hookName == null) {
2060 return null;
2061 }
2062 File hookDir = getHooksDirectory(repository);
2063 if (hookDir == null) {
2064 return null;
2065 }
2066 File hookFile = new File(hookDir, hookName);
2067 if (hookFile.isAbsolute()) {
2068 if (!hookFile.exists() || (FS.DETECTED.supportsExecute()
2069 && !FS.DETECTED.canExecute(hookFile))) {
2070 return null;
2071 }
2072 } else {
2073 try {
2074 File runDirectory = getRunDirectory(repository, hookName);
2075 if (runDirectory == null) {
2076 return null;
2077 }
2078 Path hookPath = runDirectory.getAbsoluteFile().toPath()
2079 .resolve(hookFile.toPath());
2080 FS fs = repository.getFS();
2081 if (fs == null) {
2082 fs = FS.DETECTED;
2083 }
2084 if (!Files.exists(hookPath) || (fs.supportsExecute()
2085 && !fs.canExecute(hookPath.toFile()))) {
2086 return null;
2087 }
2088 hookFile = hookPath.toFile();
2089 } catch (InvalidPathException e) {
2090 LOG.warn(MessageFormat.format(JGitText.get().invalidHooksPath,
2091 hookFile));
2092 return null;
2093 }
2094 }
2095 return hookFile;
2096 }
2097
2098 private File getRunDirectory(Repository repository,
2099 @NonNull String hookName) {
2100 if (repository.isBare()) {
2101 return repository.getDirectory();
2102 }
2103 switch (hookName) {
2104 case "pre-receive":
2105 case "update":
2106 case "post-receive":
2107 case "post-update":
2108 case "push-to-checkout":
2109 return repository.getDirectory();
2110 default:
2111 return repository.getWorkTree();
2112 }
2113 }
2114
2115 private File getHooksDirectory(Repository repository) {
2116 Config config = repository.getConfig();
2117 String hooksDir = config.getString(ConfigConstants.CONFIG_CORE_SECTION,
2118 null, ConfigConstants.CONFIG_KEY_HOOKS_PATH);
2119 if (hooksDir != null) {
2120 return new File(hooksDir);
2121 }
2122 File dir = repository.getDirectory();
2123 return dir == null ? null : new File(dir, Constants.HOOKS);
2124 }
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151 public int runProcess(ProcessBuilder processBuilder,
2152 OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
2153 throws IOException, InterruptedException {
2154 InputStream in = (stdinArgs == null) ? null : new ByteArrayInputStream(
2155 stdinArgs.getBytes(UTF_8));
2156 return runProcess(processBuilder, outRedirect, errRedirect, in);
2157 }
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187 public int runProcess(ProcessBuilder processBuilder,
2188 OutputStream outRedirect, OutputStream errRedirect,
2189 InputStream inRedirect) throws IOException,
2190 InterruptedException {
2191 ExecutorService executor = Executors.newFixedThreadPool(2);
2192 Process process = null;
2193
2194
2195 IOException ioException = null;
2196 try {
2197 process = processBuilder.start();
2198 executor.execute(
2199 new StreamGobbler(process.getErrorStream(), errRedirect));
2200 executor.execute(
2201 new StreamGobbler(process.getInputStream(), outRedirect));
2202 @SuppressWarnings("resource")
2203 OutputStream outputStream = process.getOutputStream();
2204 try {
2205 if (inRedirect != null) {
2206 new StreamGobbler(inRedirect, outputStream).copy();
2207 }
2208 } finally {
2209 try {
2210 outputStream.close();
2211 } catch (IOException e) {
2212
2213
2214
2215
2216
2217
2218 }
2219 }
2220 return process.waitFor();
2221 } catch (IOException e) {
2222 ioException = e;
2223 } finally {
2224 shutdownAndAwaitTermination(executor);
2225 if (process != null) {
2226 try {
2227 process.waitFor();
2228 } catch (InterruptedException e) {
2229
2230
2231
2232
2233 Thread.interrupted();
2234 }
2235
2236
2237
2238 if (inRedirect != null) {
2239 inRedirect.close();
2240 }
2241 try {
2242 process.getErrorStream().close();
2243 } catch (IOException e) {
2244 ioException = ioException != null ? ioException : e;
2245 }
2246 try {
2247 process.getInputStream().close();
2248 } catch (IOException e) {
2249 ioException = ioException != null ? ioException : e;
2250 }
2251 try {
2252 process.getOutputStream().close();
2253 } catch (IOException e) {
2254 ioException = ioException != null ? ioException : e;
2255 }
2256 process.destroy();
2257 }
2258 }
2259
2260 throw ioException;
2261 }
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276 private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
2277 boolean hasShutdown = true;
2278 pool.shutdown();
2279 try {
2280
2281 if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
2282 pool.shutdownNow();
2283
2284 if (!pool.awaitTermination(60, TimeUnit.SECONDS))
2285 hasShutdown = false;
2286 }
2287 } catch (InterruptedException ie) {
2288
2289 pool.shutdownNow();
2290
2291 Thread.currentThread().interrupt();
2292 hasShutdown = false;
2293 }
2294 return hasShutdown;
2295 }
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309 public abstract ProcessBuilder runInShell(String cmd, String[] args);
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323 public ExecutionResult execute(ProcessBuilder pb, InputStream in)
2324 throws IOException, InterruptedException {
2325 try (TemporaryBuffer stdout = new TemporaryBuffer.LocalFile(null);
2326 TemporaryBuffer stderr = new TemporaryBuffer.Heap(1024,
2327 1024 * 1024)) {
2328 int rc = runProcess(pb, stdout, stderr, in);
2329 return new ExecutionResult(stdout, stderr, rc);
2330 }
2331 }
2332
2333 private static class Holder<V> {
2334 final V value;
2335
2336 Holder(V value) {
2337 this.value = value;
2338 }
2339 }
2340
2341
2342
2343
2344
2345
2346 public static class Attributes {
2347
2348
2349
2350
2351 public boolean isDirectory() {
2352 return isDirectory;
2353 }
2354
2355
2356
2357
2358 public boolean isExecutable() {
2359 return isExecutable;
2360 }
2361
2362
2363
2364
2365 public boolean isSymbolicLink() {
2366 return isSymbolicLink;
2367 }
2368
2369
2370
2371
2372 public boolean isRegularFile() {
2373 return isRegularFile;
2374 }
2375
2376
2377
2378
2379 public long getCreationTime() {
2380 return creationTime;
2381 }
2382
2383
2384
2385
2386
2387
2388 @Deprecated
2389 public long getLastModifiedTime() {
2390 return lastModifiedInstant.toEpochMilli();
2391 }
2392
2393
2394
2395
2396
2397 public Instant getLastModifiedInstant() {
2398 return lastModifiedInstant;
2399 }
2400
2401 private final boolean isDirectory;
2402
2403 private final boolean isSymbolicLink;
2404
2405 private final boolean isRegularFile;
2406
2407 private final long creationTime;
2408
2409 private final Instant lastModifiedInstant;
2410
2411 private final boolean isExecutable;
2412
2413 private final File file;
2414
2415 private final boolean exists;
2416
2417
2418
2419
2420 protected long length = -1;
2421
2422 final FS fs;
2423
2424 Attributes(FS fs, File file, boolean exists, boolean isDirectory,
2425 boolean isExecutable, boolean isSymbolicLink,
2426 boolean isRegularFile, long creationTime,
2427 Instant lastModifiedInstant, long length) {
2428 this.fs = fs;
2429 this.file = file;
2430 this.exists = exists;
2431 this.isDirectory = isDirectory;
2432 this.isExecutable = isExecutable;
2433 this.isSymbolicLink = isSymbolicLink;
2434 this.isRegularFile = isRegularFile;
2435 this.creationTime = creationTime;
2436 this.lastModifiedInstant = lastModifiedInstant;
2437 this.length = length;
2438 }
2439
2440
2441
2442
2443
2444
2445
2446
2447 public Attributes(File path, FS fs) {
2448 this(fs, path, false, false, false, false, false, 0L, EPOCH, 0L);
2449 }
2450
2451
2452
2453
2454 public long getLength() {
2455 if (length == -1)
2456 return length = file.length();
2457 return length;
2458 }
2459
2460
2461
2462
2463 public String getName() {
2464 return file.getName();
2465 }
2466
2467
2468
2469
2470 public File getFile() {
2471 return file;
2472 }
2473
2474 boolean exists() {
2475 return exists;
2476 }
2477 }
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487 public Attributes getAttributes(File path) {
2488 boolean isDirectory = isDirectory(path);
2489 boolean isFile = !isDirectory && path.isFile();
2490 assert path.exists() == isDirectory || isFile;
2491 boolean exists = isDirectory || isFile;
2492 boolean canExecute = exists && !isDirectory && canExecute(path);
2493 boolean isSymlink = false;
2494 Instant lastModified = exists ? lastModifiedInstant(path) : EPOCH;
2495 long createTime = 0L;
2496 return new Attributes(this, path, exists, isDirectory, canExecute,
2497 isSymlink, isFile, createTime, lastModified, -1);
2498 }
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508 public File normalize(File file) {
2509 return file;
2510 }
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520 public String normalize(String name) {
2521 return name;
2522 }
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536 private static class StreamGobbler implements Runnable {
2537 private InputStream in;
2538
2539 private OutputStream out;
2540
2541 public StreamGobbler(InputStream stream, OutputStream output) {
2542 this.in = stream;
2543 this.out = output;
2544 }
2545
2546 @Override
2547 public void run() {
2548 try {
2549 copy();
2550 } catch (IOException e) {
2551
2552 }
2553 }
2554
2555 void copy() throws IOException {
2556 boolean writeFailure = false;
2557 byte[] buffer = new byte[4096];
2558 int readBytes;
2559 while ((readBytes = in.read(buffer)) != -1) {
2560
2561
2562
2563 if (!writeFailure && out != null) {
2564 try {
2565 out.write(buffer, 0, readBytes);
2566 out.flush();
2567 } catch (IOException e) {
2568 writeFailure = true;
2569 }
2570 }
2571 }
2572 }
2573 }
2574 }