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