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 java.io.File;
49 import java.io.IOException;
50 import java.nio.channels.FileLock;
51 import java.nio.file.AtomicMoveNotSupportedException;
52 import java.nio.file.CopyOption;
53 import java.nio.file.Files;
54 import java.nio.file.LinkOption;
55 import java.nio.file.Path;
56 import java.nio.file.StandardCopyOption;
57 import java.nio.file.attribute.BasicFileAttributeView;
58 import java.nio.file.attribute.BasicFileAttributes;
59 import java.nio.file.attribute.FileTime;
60 import java.nio.file.attribute.PosixFileAttributeView;
61 import java.nio.file.attribute.PosixFileAttributes;
62 import java.nio.file.attribute.PosixFilePermission;
63 import java.text.MessageFormat;
64 import java.text.Normalizer;
65 import java.text.Normalizer.Form;
66 import java.util.ArrayList;
67 import java.util.List;
68 import java.util.Locale;
69 import java.util.regex.Pattern;
70
71 import org.eclipse.jgit.internal.JGitText;
72 import org.eclipse.jgit.lib.Constants;
73 import org.eclipse.jgit.util.FS.Attributes;
74
75
76
77
78 public class FileUtils {
79
80
81
82
83 public static final int NONE = 0;
84
85
86
87
88 public static final int RECURSIVE = 1;
89
90
91
92
93 public static final int RETRY = 2;
94
95
96
97
98 public static final int SKIP_MISSING = 4;
99
100
101
102
103
104 public static final int IGNORE_ERRORS = 8;
105
106
107
108
109
110
111
112 public static final int EMPTY_DIRECTORIES_ONLY = 16;
113
114
115
116
117
118
119
120
121
122
123
124
125 public static void delete(final File f) throws IOException {
126 delete(f, NONE);
127 }
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146 public static void delete(final File f, int options) throws IOException {
147 FS fs = FS.DETECTED;
148 if ((options & SKIP_MISSING) != 0 && !fs.exists(f))
149 return;
150
151 if ((options & RECURSIVE) != 0 && fs.isDirectory(f)) {
152 final File[] items = f.listFiles();
153 if (items != null) {
154 List<File> files = new ArrayList<>();
155 List<File> dirs = new ArrayList<>();
156 for (File c : items)
157 if (c.isFile())
158 files.add(c);
159 else
160 dirs.add(c);
161
162
163
164 for (File file : files)
165 delete(file, options);
166 for (File d : dirs)
167 delete(d, options);
168 }
169 }
170
171 boolean delete = false;
172 if ((options & EMPTY_DIRECTORIES_ONLY) != 0) {
173 if (f.isDirectory()) {
174 delete = true;
175 } else {
176 if ((options & IGNORE_ERRORS) == 0)
177 throw new IOException(MessageFormat.format(
178 JGitText.get().deleteFileFailed,
179 f.getAbsolutePath()));
180 }
181 } else {
182 delete = true;
183 }
184
185 if (delete && !f.delete()) {
186 if ((options & RETRY) != 0 && fs.exists(f)) {
187 for (int i = 1; i < 10; i++) {
188 try {
189 Thread.sleep(100);
190 } catch (InterruptedException e) {
191
192 }
193 if (f.delete())
194 return;
195 }
196 }
197 if ((options & IGNORE_ERRORS) == 0)
198 throw new IOException(MessageFormat.format(
199 JGitText.get().deleteFileFailed, f.getAbsolutePath()));
200 }
201 }
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225 public static void rename(final File src, final File dst)
226 throws IOException {
227 rename(src, dst, StandardCopyOption.REPLACE_EXISTING);
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
254
255
256 public static void rename(final File src, final File dst,
257 CopyOption... options)
258 throws AtomicMoveNotSupportedException, IOException {
259 int attempts = FS.DETECTED.retryFailedLockFileCommit() ? 10 : 1;
260 while (--attempts >= 0) {
261 try {
262 Files.move(src.toPath(), dst.toPath(), options);
263 return;
264 } catch (AtomicMoveNotSupportedException e) {
265 throw e;
266 } catch (IOException e) {
267 try {
268 if (!dst.delete()) {
269 delete(dst, EMPTY_DIRECTORIES_ONLY | RECURSIVE);
270 }
271
272 Files.move(src.toPath(), dst.toPath(), options);
273 return;
274 } catch (IOException e2) {
275
276 }
277 }
278 try {
279 Thread.sleep(100);
280 } catch (InterruptedException e) {
281 throw new IOException(
282 MessageFormat.format(JGitText.get().renameFileFailed,
283 src.getAbsolutePath(), dst.getAbsolutePath()));
284 }
285 }
286 throw new IOException(
287 MessageFormat.format(JGitText.get().renameFileFailed,
288 src.getAbsolutePath(), dst.getAbsolutePath()));
289 }
290
291
292
293
294
295
296
297
298
299
300
301
302 public static void mkdir(final File d)
303 throws IOException {
304 mkdir(d, false);
305 }
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321 public static void mkdir(final File d, boolean skipExisting)
322 throws IOException {
323 if (!d.mkdir()) {
324 if (skipExisting && d.isDirectory())
325 return;
326 throw new IOException(MessageFormat.format(
327 JGitText.get().mkDirFailed, d.getAbsolutePath()));
328 }
329 }
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345 public static void mkdirs(final File d) throws IOException {
346 mkdirs(d, false);
347 }
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366 public static void mkdirs(final File d, boolean skipExisting)
367 throws IOException {
368 if (!d.mkdirs()) {
369 if (skipExisting && d.isDirectory())
370 return;
371 throw new IOException(MessageFormat.format(
372 JGitText.get().mkDirsFailed, d.getAbsolutePath()));
373 }
374 }
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392 public static void createNewFile(File f) throws IOException {
393 if (!f.createNewFile())
394 throw new IOException(MessageFormat.format(
395 JGitText.get().createNewFileFailed, f));
396 }
397
398
399
400
401
402
403
404
405
406
407
408
409 public static Path createSymLink(File path, String target)
410 throws IOException {
411 Path nioPath = path.toPath();
412 if (Files.exists(nioPath, LinkOption.NOFOLLOW_LINKS)) {
413 BasicFileAttributes attrs = Files.readAttributes(nioPath,
414 BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
415 if (attrs.isRegularFile() || attrs.isSymbolicLink()) {
416 delete(path);
417 } else {
418 delete(path, EMPTY_DIRECTORIES_ONLY | RECURSIVE);
419 }
420 }
421 if (SystemReader.getInstance().isWindows()) {
422 target = target.replace('/', '\\');
423 }
424 Path nioTarget = new File(target).toPath();
425 return Files.createSymbolicLink(nioPath, nioTarget);
426 }
427
428
429
430
431
432
433
434 public static String readSymLink(File path) throws IOException {
435 Path nioPath = path.toPath();
436 Path target = Files.readSymbolicLink(nioPath);
437 String targetString = target.toString();
438 if (SystemReader.getInstance().isWindows()) {
439 targetString = targetString.replace('\\', '/');
440 } else if (SystemReader.getInstance().isMacOS()) {
441 targetString = Normalizer.normalize(targetString, Form.NFC);
442 }
443 return targetString;
444 }
445
446
447
448
449
450
451
452
453
454
455
456
457 public static File createTempDir(String prefix, String suffix, File dir)
458 throws IOException {
459 final int RETRIES = 1;
460 for (int i = 0; i < RETRIES; i++) {
461 File tmp = File.createTempFile(prefix, suffix, dir);
462 if (!tmp.delete())
463 continue;
464 if (!tmp.mkdir())
465 continue;
466 return tmp;
467 }
468 throw new IOException(JGitText.get().cannotCreateTempDir);
469 }
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492 @Deprecated
493 public static String relativize(String base, String other) {
494 return relativizeNativePath(base, other);
495 }
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510 public static String relativizeNativePath(String base, String other) {
511 return FS.DETECTED.relativize(base, other);
512 }
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527 public static String relativizeGitPath(String base, String other) {
528 return relativizePath(base, other, "/", false);
529 }
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564 public static String relativizePath(String base, String other, String dirSeparator, boolean caseSensitive) {
565 if (base.equals(other))
566 return "";
567
568 final String[] baseSegments = base.split(Pattern.quote(dirSeparator));
569 final String[] otherSegments = other.split(Pattern
570 .quote(dirSeparator));
571
572 int commonPrefix = 0;
573 while (commonPrefix < baseSegments.length
574 && commonPrefix < otherSegments.length) {
575 if (caseSensitive
576 && baseSegments[commonPrefix]
577 .equals(otherSegments[commonPrefix]))
578 commonPrefix++;
579 else if (!caseSensitive
580 && baseSegments[commonPrefix]
581 .equalsIgnoreCase(otherSegments[commonPrefix]))
582 commonPrefix++;
583 else
584 break;
585 }
586
587 final StringBuilder builder = new StringBuilder();
588 for (int i = commonPrefix; i < baseSegments.length; i++)
589 builder.append("..").append(dirSeparator);
590 for (int i = commonPrefix; i < otherSegments.length; i++) {
591 builder.append(otherSegments[i]);
592 if (i < otherSegments.length - 1)
593 builder.append(dirSeparator);
594 }
595 return builder.toString();
596 }
597
598
599
600
601
602
603
604
605 public static boolean isStaleFileHandle(IOException ioe) {
606 String msg = ioe.getMessage();
607 return msg != null
608 && msg.toLowerCase(Locale.ROOT)
609 .matches("stale .*file .*handle");
610 }
611
612
613
614
615
616
617
618
619
620
621 public static boolean isStaleFileHandleInCausalChain(Throwable throwable) {
622 while (throwable != null) {
623 if (throwable instanceof IOException
624 && isStaleFileHandle((IOException) throwable)) {
625 return true;
626 }
627 throwable = throwable.getCause();
628 }
629 return false;
630 }
631
632
633
634
635
636 static boolean isSymlink(File file) {
637 return Files.isSymbolicLink(file.toPath());
638 }
639
640
641
642
643
644
645
646 static long lastModified(File file) throws IOException {
647 return Files.getLastModifiedTime(file.toPath(), LinkOption.NOFOLLOW_LINKS)
648 .toMillis();
649 }
650
651
652
653
654
655
656 static void setLastModified(File file, long time) throws IOException {
657 Files.setLastModifiedTime(file.toPath(), FileTime.fromMillis(time));
658 }
659
660
661
662
663
664
665 static boolean exists(File file) {
666 return Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS);
667 }
668
669
670
671
672
673
674 static boolean isHidden(File file) throws IOException {
675 return Files.isHidden(file.toPath());
676 }
677
678
679
680
681
682
683
684 public static void setHidden(File file, boolean hidden) throws IOException {
685 Files.setAttribute(file.toPath(), "dos:hidden", Boolean.valueOf(hidden),
686 LinkOption.NOFOLLOW_LINKS);
687 }
688
689
690
691
692
693
694
695 public static long getLength(File file) throws IOException {
696 Path nioPath = file.toPath();
697 if (Files.isSymbolicLink(nioPath))
698 return Files.readSymbolicLink(nioPath).toString()
699 .getBytes(Constants.CHARSET).length;
700 return Files.size(nioPath);
701 }
702
703
704
705
706
707
708 static boolean isDirectory(File file) {
709 return Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS);
710 }
711
712
713
714
715
716
717 static boolean isFile(File file) {
718 return Files.isRegularFile(file.toPath(), LinkOption.NOFOLLOW_LINKS);
719 }
720
721
722
723
724
725
726 public static boolean canExecute(File file) {
727 if (!isFile(file)) {
728 return false;
729 }
730 return Files.isExecutable(file.toPath());
731 }
732
733
734
735
736
737
738 static Attributes getFileAttributesBasic(FS fs, File file) {
739 try {
740 Path nioPath = file.toPath();
741 BasicFileAttributes readAttributes = nioPath
742 .getFileSystem()
743 .provider()
744 .getFileAttributeView(nioPath,
745 BasicFileAttributeView.class,
746 LinkOption.NOFOLLOW_LINKS).readAttributes();
747 Attributes attributes = new Attributes(fs, file,
748 true,
749 readAttributes.isDirectory(),
750 fs.supportsExecute() ? file.canExecute() : false,
751 readAttributes.isSymbolicLink(),
752 readAttributes.isRegularFile(),
753 readAttributes.creationTime().toMillis(),
754 readAttributes.lastModifiedTime().toMillis(),
755 readAttributes.isSymbolicLink() ? Constants
756 .encode(readSymLink(file)).length
757 : readAttributes.size());
758 return attributes;
759 } catch (IOException e) {
760 return new Attributes(file, fs);
761 }
762 }
763
764
765
766
767
768
769
770 public static Attributes getFileAttributesPosix(FS fs, File file) {
771 try {
772 Path nioPath = file.toPath();
773 PosixFileAttributes readAttributes = nioPath
774 .getFileSystem()
775 .provider()
776 .getFileAttributeView(nioPath,
777 PosixFileAttributeView.class,
778 LinkOption.NOFOLLOW_LINKS).readAttributes();
779 Attributes attributes = new Attributes(
780 fs,
781 file,
782 true,
783 readAttributes.isDirectory(),
784 readAttributes.permissions().contains(
785 PosixFilePermission.OWNER_EXECUTE),
786 readAttributes.isSymbolicLink(),
787 readAttributes.isRegularFile(),
788 readAttributes.creationTime().toMillis(),
789 readAttributes.lastModifiedTime().toMillis(),
790 readAttributes.size());
791 return attributes;
792 } catch (IOException e) {
793 return new Attributes(file, fs);
794 }
795 }
796
797
798
799
800
801
802 public static File normalize(File file) {
803 if (SystemReader.getInstance().isMacOS()) {
804
805
806 String normalized = Normalizer.normalize(file.getPath(),
807 Normalizer.Form.NFC);
808 return new File(normalized);
809 }
810 return file;
811 }
812
813
814
815
816
817
818 public static String normalize(String name) {
819 if (SystemReader.getInstance().isMacOS()) {
820 if (name == null)
821 return null;
822 return Normalizer.normalize(name, Normalizer.Form.NFC);
823 }
824 return name;
825 }
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840 public static File canonicalize(File file) {
841 if (file == null) {
842 return null;
843 }
844 try {
845 return file.getCanonicalFile();
846 } catch (IOException e) {
847 return file;
848 }
849 }
850
851 }