1
2
3
4
5
6
7
8
9
10
11
12
13 package org.eclipse.jgit.util;
14
15 import static java.nio.charset.StandardCharsets.UTF_8;
16
17 import java.io.File;
18 import java.io.FileNotFoundException;
19 import java.io.IOException;
20 import java.io.InterruptedIOException;
21 import java.nio.channels.FileChannel;
22 import java.nio.file.AtomicMoveNotSupportedException;
23 import java.nio.file.CopyOption;
24 import java.nio.file.DirectoryNotEmptyException;
25 import java.nio.file.Files;
26 import java.nio.file.InvalidPathException;
27 import java.nio.file.LinkOption;
28 import java.nio.file.NoSuchFileException;
29 import java.nio.file.Path;
30 import java.nio.file.StandardCopyOption;
31 import java.nio.file.StandardOpenOption;
32 import java.nio.file.attribute.BasicFileAttributeView;
33 import java.nio.file.attribute.BasicFileAttributes;
34 import java.nio.file.attribute.FileTime;
35 import java.nio.file.attribute.PosixFileAttributeView;
36 import java.nio.file.attribute.PosixFileAttributes;
37 import java.nio.file.attribute.PosixFilePermission;
38 import java.text.MessageFormat;
39 import java.text.Normalizer;
40 import java.text.Normalizer.Form;
41 import java.time.Instant;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.Locale;
45 import java.util.Random;
46 import java.util.regex.Pattern;
47 import java.util.stream.Stream;
48
49 import org.eclipse.jgit.internal.JGitText;
50 import org.eclipse.jgit.lib.Constants;
51 import org.eclipse.jgit.util.FS.Attributes;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55
56
57
58 public class FileUtils {
59 private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);
60
61 private static final Random RNG = new Random();
62
63
64
65
66 public static final int NONE = 0;
67
68
69
70
71 public static final int RECURSIVE = 1;
72
73
74
75
76 public static final int RETRY = 2;
77
78
79
80
81 public static final int SKIP_MISSING = 4;
82
83
84
85
86
87 public static final int IGNORE_ERRORS = 8;
88
89
90
91
92
93
94
95 public static final int EMPTY_DIRECTORIES_ONLY = 16;
96
97
98
99
100
101
102
103
104
105
106
107
108 public static Path toPath(File f) throws IOException {
109 try {
110 return f.toPath();
111 } catch (InvalidPathException ex) {
112 throw new IOException(ex);
113 }
114 }
115
116
117
118
119
120
121
122
123
124
125
126
127 public static void delete(File f) throws IOException {
128 delete(f, NONE);
129 }
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148 public static void delete(File f, int options) throws IOException {
149 FS fs = FS.DETECTED;
150 if ((options & SKIP_MISSING) != 0 && !fs.exists(f))
151 return;
152
153 if ((options & RECURSIVE) != 0 && fs.isDirectory(f)) {
154 final File[] items = f.listFiles();
155 if (items != null) {
156 List<File> files = new ArrayList<>();
157 List<File> dirs = new ArrayList<>();
158 for (File c : items)
159 if (c.isFile())
160 files.add(c);
161 else
162 dirs.add(c);
163
164
165
166 for (File file : files)
167 delete(file, options);
168 for (File d : dirs)
169 delete(d, options);
170 }
171 }
172
173 boolean delete = false;
174 if ((options & EMPTY_DIRECTORIES_ONLY) != 0) {
175 if (f.isDirectory()) {
176 delete = true;
177 } else if ((options & IGNORE_ERRORS) == 0) {
178 throw new IOException(MessageFormat.format(
179 JGitText.get().deleteFileFailed, f.getAbsolutePath()));
180 }
181 } else {
182 delete = true;
183 }
184
185 if (delete) {
186 IOException t = null;
187 Path p = f.toPath();
188 boolean tryAgain;
189 do {
190 tryAgain = false;
191 try {
192 Files.delete(p);
193 return;
194 } catch (NoSuchFileException | FileNotFoundException e) {
195 handleDeleteException(f, e, options,
196 SKIP_MISSING | IGNORE_ERRORS);
197 return;
198 } catch (DirectoryNotEmptyException e) {
199 handleDeleteException(f, e, options, IGNORE_ERRORS);
200 return;
201 } catch (IOException e) {
202 if (!f.canWrite()) {
203 tryAgain = f.setWritable(true);
204 }
205 if (!tryAgain) {
206 t = e;
207 }
208 }
209 } while (tryAgain);
210
211 if ((options & RETRY) != 0) {
212 for (int i = 1; i < 10; i++) {
213 try {
214 Thread.sleep(100);
215 } catch (InterruptedException ex) {
216
217 }
218 try {
219 Files.deleteIfExists(p);
220 return;
221 } catch (IOException e) {
222 t = e;
223 }
224 }
225 }
226 handleDeleteException(f, t, options, IGNORE_ERRORS);
227 }
228 }
229
230 private static void handleDeleteException(File f, IOException e,
231 int allOptions, int checkOptions) throws IOException {
232 if (e != null && (allOptions & checkOptions) == 0) {
233 throw new IOException(MessageFormat.format(
234 JGitText.get().deleteFileFailed, f.getAbsolutePath()), e);
235 }
236 }
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260 public static void rename(File src, File dst)
261 throws IOException {
262 rename(src, dst, StandardCopyOption.REPLACE_EXISTING);
263 }
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293 public static void rename(final File src, final File dst,
294 CopyOption... options)
295 throws AtomicMoveNotSupportedException, IOException {
296 int attempts = FS.DETECTED.retryFailedLockFileCommit() ? 10 : 1;
297 while (--attempts >= 0) {
298 try {
299 Files.move(toPath(src), toPath(dst), options);
300 return;
301 } catch (AtomicMoveNotSupportedException e) {
302 throw e;
303 } catch (IOException e) {
304 try {
305 if (!dst.delete()) {
306 delete(dst, EMPTY_DIRECTORIES_ONLY | RECURSIVE);
307 }
308
309 Files.move(toPath(src), toPath(dst), options);
310 return;
311 } catch (IOException e2) {
312
313 }
314 }
315 try {
316 Thread.sleep(100);
317 } catch (InterruptedException e) {
318 throw new IOException(
319 MessageFormat.format(JGitText.get().renameFileFailed,
320 src.getAbsolutePath(), dst.getAbsolutePath()),
321 e);
322 }
323 }
324 throw new IOException(
325 MessageFormat.format(JGitText.get().renameFileFailed,
326 src.getAbsolutePath(), dst.getAbsolutePath()));
327 }
328
329
330
331
332
333
334
335
336
337
338
339
340
341 public static void mkdir(File d)
342 throws IOException {
343 mkdir(d, false);
344 }
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361 public static void mkdir(File d, boolean skipExisting)
362 throws IOException {
363 if (!d.mkdir()) {
364 if (skipExisting && d.isDirectory())
365 return;
366 throw new IOException(MessageFormat.format(
367 JGitText.get().mkDirFailed, d.getAbsolutePath()));
368 }
369 }
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386 public static void mkdirs(File d) throws IOException {
387 mkdirs(d, false);
388 }
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408 public static void mkdirs(File d, boolean skipExisting)
409 throws IOException {
410 if (!d.mkdirs()) {
411 if (skipExisting && d.isDirectory())
412 return;
413 throw new IOException(MessageFormat.format(
414 JGitText.get().mkDirsFailed, d.getAbsolutePath()));
415 }
416 }
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434 public static void createNewFile(File f) throws IOException {
435 if (!f.createNewFile())
436 throw new IOException(MessageFormat.format(
437 JGitText.get().createNewFileFailed, f));
438 }
439
440
441
442
443
444
445
446
447
448
449
450
451 public static Path createSymLink(File path, String target)
452 throws IOException {
453 Path nioPath = toPath(path);
454 if (Files.exists(nioPath, LinkOption.NOFOLLOW_LINKS)) {
455 BasicFileAttributes attrs = Files.readAttributes(nioPath,
456 BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
457 if (attrs.isRegularFile() || attrs.isSymbolicLink()) {
458 delete(path);
459 } else {
460 delete(path, EMPTY_DIRECTORIES_ONLY | RECURSIVE);
461 }
462 }
463 if (SystemReader.getInstance().isWindows()) {
464 target = target.replace('/', '\\');
465 }
466 Path nioTarget = toPath(new File(target));
467 return Files.createSymbolicLink(nioPath, nioTarget);
468 }
469
470
471
472
473
474
475
476
477
478
479 public static String readSymLink(File path) throws IOException {
480 Path nioPath = toPath(path);
481 Path target = Files.readSymbolicLink(nioPath);
482 String targetString = target.toString();
483 if (SystemReader.getInstance().isWindows()) {
484 targetString = targetString.replace('\\', '/');
485 } else if (SystemReader.getInstance().isMacOS()) {
486 targetString = Normalizer.normalize(targetString, Form.NFC);
487 }
488 return targetString;
489 }
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504 public static File createTempDir(String prefix, String suffix, File dir)
505 throws IOException {
506 final int RETRIES = 1;
507 for (int i = 0; i < RETRIES; i++) {
508 File tmp = File.createTempFile(prefix, suffix, dir);
509 if (!tmp.delete())
510 continue;
511 if (!tmp.mkdir())
512 continue;
513 return tmp;
514 }
515 throw new IOException(JGitText.get().cannotCreateTempDir);
516 }
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533 public static String relativizeNativePath(String base, String other) {
534 return FS.DETECTED.relativize(base, other);
535 }
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552 public static String relativizeGitPath(String base, String other) {
553 return relativizePath(base, other, "/", false);
554 }
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588 public static String relativizePath(String base, String other, String dirSeparator, boolean caseSensitive) {
589 if (base.equals(other))
590 return "";
591
592 final String[] baseSegments = base.split(Pattern.quote(dirSeparator));
593 final String[] otherSegments = other.split(Pattern
594 .quote(dirSeparator));
595
596 int commonPrefix = 0;
597 while (commonPrefix < baseSegments.length
598 && commonPrefix < otherSegments.length) {
599 if (caseSensitive
600 && baseSegments[commonPrefix]
601 .equals(otherSegments[commonPrefix]))
602 commonPrefix++;
603 else if (!caseSensitive
604 && baseSegments[commonPrefix]
605 .equalsIgnoreCase(otherSegments[commonPrefix]))
606 commonPrefix++;
607 else
608 break;
609 }
610
611 final StringBuilder builder = new StringBuilder();
612 for (int i = commonPrefix; i < baseSegments.length; i++)
613 builder.append("..").append(dirSeparator);
614 for (int i = commonPrefix; i < otherSegments.length; i++) {
615 builder.append(otherSegments[i]);
616 if (i < otherSegments.length - 1)
617 builder.append(dirSeparator);
618 }
619 return builder.toString();
620 }
621
622
623
624
625
626
627
628
629
630 public static boolean isStaleFileHandle(IOException ioe) {
631 String msg = ioe.getMessage();
632 return msg != null
633 && msg.toLowerCase(Locale.ROOT)
634 .matches("stale .*file .*handle");
635 }
636
637
638
639
640
641
642
643
644
645
646
647 public static boolean isStaleFileHandleInCausalChain(Throwable throwable) {
648 while (throwable != null) {
649 if (throwable instanceof IOException
650 && isStaleFileHandle((IOException) throwable)) {
651 return true;
652 }
653 throwable = throwable.getCause();
654 }
655 return false;
656 }
657
658
659
660
661
662
663
664
665
666
667
668 @FunctionalInterface
669 public interface IOFunction<A, B> {
670
671
672
673
674
675
676
677
678
679
680 B apply(A t) throws Exception;
681 }
682
683 private static void backOff(long delay, IOException cause)
684 throws IOException {
685 try {
686 Thread.sleep(delay);
687 } catch (InterruptedException e) {
688 IOException interruption = new InterruptedIOException();
689 interruption.initCause(e);
690 interruption.addSuppressed(cause);
691 Thread.currentThread().interrupt();
692 throw interruption;
693 }
694 }
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713 public static <T> T readWithRetries(File file,
714 IOFunction<File, ? extends T> reader)
715 throws Exception {
716 int maxStaleRetries = 5;
717 int retries = 0;
718 long backoff = 50;
719 while (true) {
720 try {
721 try {
722 return reader.apply(file);
723 } catch (IOException e) {
724 if (FileUtils.isStaleFileHandleInCausalChain(e)
725 && retries < maxStaleRetries) {
726 if (LOG.isDebugEnabled()) {
727 LOG.debug(MessageFormat.format(
728 JGitText.get().packedRefsHandleIsStale,
729 Integer.valueOf(retries)), e);
730 }
731 retries++;
732 continue;
733 }
734 throw e;
735 }
736 } catch (FileNotFoundException noFile) {
737 if (!file.isFile()) {
738 return null;
739 }
740
741
742 if (backoff > 1000) {
743 throw noFile;
744 }
745 backOff(backoff, noFile);
746 backoff *= 2;
747 }
748 }
749 }
750
751
752
753
754
755 static boolean isSymlink(File file) {
756 return Files.isSymbolicLink(file.toPath());
757 }
758
759
760
761
762
763
764
765
766
767 @Deprecated
768 static long lastModified(File file) throws IOException {
769 return Files.getLastModifiedTime(toPath(file), LinkOption.NOFOLLOW_LINKS)
770 .toMillis();
771 }
772
773
774
775
776
777
778 static Instant lastModifiedInstant(Path path) {
779 try {
780 return Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS)
781 .toInstant();
782 } catch (NoSuchFileException e) {
783 LOG.debug(
784 "Cannot read lastModifiedInstant since path {} does not exist",
785 path);
786 return Instant.EPOCH;
787 } catch (IOException e) {
788 LOG.error(MessageFormat
789 .format(JGitText.get().readLastModifiedFailed, path), e);
790 return Instant.ofEpochMilli(path.toFile().lastModified());
791 }
792 }
793
794
795
796
797
798
799
800
801
802
803 static BasicFileAttributes fileAttributes(File file) throws IOException {
804 return Files.readAttributes(file.toPath(), BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
805 }
806
807
808
809
810
811
812
813
814 @Deprecated
815 static void setLastModified(File file, long time) throws IOException {
816 Files.setLastModifiedTime(toPath(file), FileTime.fromMillis(time));
817 }
818
819
820
821
822
823
824
825
826 static void setLastModified(Path path, Instant time)
827 throws IOException {
828 Files.setLastModifiedTime(path, FileTime.from(time));
829 }
830
831
832
833
834
835
836 static boolean exists(File file) {
837 return Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS);
838 }
839
840
841
842
843
844
845 static boolean isHidden(File file) throws IOException {
846 return Files.isHidden(toPath(file));
847 }
848
849
850
851
852
853
854
855
856
857
858
859 public static void setHidden(File file, boolean hidden) throws IOException {
860 Files.setAttribute(toPath(file), "dos:hidden", Boolean.valueOf(hidden),
861 LinkOption.NOFOLLOW_LINKS);
862 }
863
864
865
866
867
868
869
870
871
872
873 public static long getLength(File file) throws IOException {
874 Path nioPath = toPath(file);
875 if (Files.isSymbolicLink(nioPath))
876 return Files.readSymbolicLink(nioPath).toString()
877 .getBytes(UTF_8).length;
878 return Files.size(nioPath);
879 }
880
881
882
883
884
885
886 static boolean isDirectory(File file) {
887 return Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS);
888 }
889
890
891
892
893
894
895 static boolean isFile(File file) {
896 return Files.isRegularFile(file.toPath(), LinkOption.NOFOLLOW_LINKS);
897 }
898
899
900
901
902
903
904
905
906
907
908
909
910 public static boolean hasFiles(Path dir) throws IOException {
911 try (Stream<Path> stream = Files.list(dir)) {
912 return stream.findAny().isPresent();
913 }
914 }
915
916
917
918
919
920
921
922
923
924 public static boolean canExecute(File file) {
925 if (!isFile(file)) {
926 return false;
927 }
928 return Files.isExecutable(file.toPath());
929 }
930
931
932
933
934
935
936 static Attributes getFileAttributesBasic(FS fs, File file) {
937 try {
938 Path nioPath = toPath(file);
939 BasicFileAttributes readAttributes = nioPath
940 .getFileSystem()
941 .provider()
942 .getFileAttributeView(nioPath,
943 BasicFileAttributeView.class,
944 LinkOption.NOFOLLOW_LINKS).readAttributes();
945 Attributes attributes = new Attributes(fs, file,
946 true,
947 readAttributes.isDirectory(),
948 fs.supportsExecute() ? file.canExecute() : false,
949 readAttributes.isSymbolicLink(),
950 readAttributes.isRegularFile(),
951 readAttributes.creationTime().toMillis(),
952 readAttributes.lastModifiedTime().toInstant(),
953 readAttributes.isSymbolicLink() ? Constants
954 .encode(readSymLink(file)).length
955 : readAttributes.size());
956 return attributes;
957 } catch (IOException e) {
958 return new Attributes(file, fs);
959 }
960 }
961
962
963
964
965
966
967
968
969
970
971
972 public static Attributes getFileAttributesPosix(FS fs, File file) {
973 try {
974 Path nioPath = toPath(file);
975 PosixFileAttributes readAttributes = nioPath
976 .getFileSystem()
977 .provider()
978 .getFileAttributeView(nioPath,
979 PosixFileAttributeView.class,
980 LinkOption.NOFOLLOW_LINKS).readAttributes();
981 Attributes attributes = new Attributes(
982 fs,
983 file,
984 true,
985 readAttributes.isDirectory(),
986 readAttributes.permissions().contains(
987 PosixFilePermission.OWNER_EXECUTE),
988 readAttributes.isSymbolicLink(),
989 readAttributes.isRegularFile(),
990 readAttributes.creationTime().toMillis(),
991 readAttributes.lastModifiedTime().toInstant(),
992 readAttributes.size());
993 return attributes;
994 } catch (IOException e) {
995 return new Attributes(file, fs);
996 }
997 }
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008 public static File normalize(File file) {
1009 if (SystemReader.getInstance().isMacOS()) {
1010
1011
1012 String normalized = Normalizer.normalize(file.getPath(),
1013 Normalizer.Form.NFC);
1014 return new File(normalized);
1015 }
1016 return file;
1017 }
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027 public static String normalize(String name) {
1028 if (SystemReader.getInstance().isMacOS()) {
1029 if (name == null)
1030 return null;
1031 return Normalizer.normalize(name, Normalizer.Form.NFC);
1032 }
1033 return name;
1034 }
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049 public static File canonicalize(File file) {
1050 if (file == null) {
1051 return null;
1052 }
1053 try {
1054 return file.getCanonicalFile();
1055 } catch (IOException e) {
1056 return file;
1057 }
1058 }
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068 public static String pathToString(File file) {
1069 final String path = file.getPath();
1070 if (SystemReader.getInstance().isWindows()) {
1071 return path.replace('\\', '/');
1072 }
1073 return path;
1074 }
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084 public static void touch(Path f) throws IOException {
1085 try (FileChannel fc = FileChannel.open(f, StandardOpenOption.CREATE,
1086 StandardOpenOption.APPEND, StandardOpenOption.SYNC)) {
1087
1088 }
1089 Files.setLastModifiedTime(f, FileTime.from(Instant.now()));
1090 }
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107 public static long delay(long last, long min, long max) {
1108 long r = Math.max(0, last * 3 - min);
1109 if (r > 0) {
1110 int c = (int) Math.min(r + 1, Integer.MAX_VALUE);
1111 r = RNG.nextInt(c);
1112 }
1113 return Math.max(Math.min(min + r, max), min);
1114 }
1115 }