1 /*
2 * Copyright (C) 2010, Google Inc.
3 * Copyright (C) 2010, Matthias Sohn <matthias.sohn@sap.com>
4 * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com>
5 * and other copyright owners as documented in the project's IP log.
6 *
7 * This program and the accompanying materials are made available
8 * under the terms of the Eclipse Distribution License v1.0 which
9 * accompanies this distribution, is reproduced below, and is
10 * available at http://www.eclipse.org/org/documents/edl-v10.php
11 *
12 * All rights reserved.
13 *
14 * Redistribution and use in source and binary forms, with or
15 * without modification, are permitted provided that the following
16 * conditions are met:
17 *
18 * - Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 *
21 * - Redistributions in binary form must reproduce the above
22 * copyright notice, this list of conditions and the following
23 * disclaimer in the documentation and/or other materials provided
24 * with the distribution.
25 *
26 * - Neither the name of the Eclipse Foundation, Inc. nor the
27 * names of its contributors may be used to endorse or promote
28 * products derived from this software without specific prior
29 * written permission.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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.regex.Pattern;
69
70 import org.eclipse.jgit.internal.JGitText;
71 import org.eclipse.jgit.lib.Constants;
72 import org.eclipse.jgit.util.FS.Attributes;
73
74 /**
75 * File Utilities
76 */
77 public class FileUtils {
78
79 /**
80 * Option to delete given {@code File}
81 */
82 public static final int NONE = 0;
83
84 /**
85 * Option to recursively delete given {@code File}
86 */
87 public static final int RECURSIVE = 1;
88
89 /**
90 * Option to retry deletion if not successful
91 */
92 public static final int RETRY = 2;
93
94 /**
95 * Option to skip deletion if file doesn't exist
96 */
97 public static final int SKIP_MISSING = 4;
98
99 /**
100 * Option not to throw exceptions when a deletion finally doesn't succeed.
101 * @since 2.0
102 */
103 public static final int IGNORE_ERRORS = 8;
104
105 /**
106 * Option to only delete empty directories. This option can be combined with
107 * {@link #RECURSIVE}
108 *
109 * @since 3.0
110 */
111 public static final int EMPTY_DIRECTORIES_ONLY = 16;
112
113 /**
114 * Delete file or empty folder
115 *
116 * @param f
117 * {@code File} to be deleted
118 * @throws IOException
119 * if deletion of {@code f} fails. This may occur if {@code f}
120 * didn't exist when the method was called. This can therefore
121 * cause IOExceptions during race conditions when multiple
122 * concurrent threads all try to delete the same file.
123 */
124 public static void delete(final File f) throws IOException {
125 delete(f, NONE);
126 }
127
128 /**
129 * Delete file or folder
130 *
131 * @param f
132 * {@code File} to be deleted
133 * @param options
134 * deletion options, {@code RECURSIVE} for recursive deletion of
135 * a subtree, {@code RETRY} to retry when deletion failed.
136 * Retrying may help if the underlying file system doesn't allow
137 * deletion of files being read by another thread.
138 * @throws IOException
139 * if deletion of {@code f} fails. This may occur if {@code f}
140 * didn't exist when the method was called. This can therefore
141 * cause IOExceptions during race conditions when multiple
142 * concurrent threads all try to delete the same file. This
143 * exception is not thrown when IGNORE_ERRORS is set.
144 */
145 public static void delete(final File f, int options) throws IOException {
146 FS fs = FS.DETECTED;
147 if ((options & SKIP_MISSING) != 0 && !fs.exists(f))
148 return;
149
150 if ((options & RECURSIVE) != 0 && fs.isDirectory(f)) {
151 final File[] items = f.listFiles();
152 if (items != null) {
153 List<File> files = new ArrayList<File>();
154 List<File> dirs = new ArrayList<File>();
155 for (File c : items)
156 if (c.isFile())
157 files.add(c);
158 else
159 dirs.add(c);
160 // Try to delete files first, otherwise options
161 // EMPTY_DIRECTORIES_ONLY|RECURSIVE will delete empty
162 // directories before aborting, depending on order.
163 for (File file : files)
164 delete(file, options);
165 for (File d : dirs)
166 delete(d, options);
167 }
168 }
169
170 boolean delete = false;
171 if ((options & EMPTY_DIRECTORIES_ONLY) != 0) {
172 if (f.isDirectory()) {
173 delete = true;
174 } else {
175 if ((options & IGNORE_ERRORS) == 0)
176 throw new IOException(MessageFormat.format(
177 JGitText.get().deleteFileFailed,
178 f.getAbsolutePath()));
179 }
180 } else {
181 delete = true;
182 }
183
184 if (delete && !f.delete()) {
185 if ((options & RETRY) != 0 && fs.exists(f)) {
186 for (int i = 1; i < 10; i++) {
187 try {
188 Thread.sleep(100);
189 } catch (InterruptedException e) {
190 // ignore
191 }
192 if (f.delete())
193 return;
194 }
195 }
196 if ((options & IGNORE_ERRORS) == 0)
197 throw new IOException(MessageFormat.format(
198 JGitText.get().deleteFileFailed, f.getAbsolutePath()));
199 }
200 }
201
202 /**
203 * Rename a file or folder. If the rename fails and if we are running on a
204 * filesystem where it makes sense to repeat a failing rename then repeat
205 * the rename operation up to 9 times with 100ms sleep time between two
206 * calls. Furthermore if the destination exists and is directory hierarchy
207 * with only directories in it, the whole directory hierarchy will be
208 * deleted. If the target represents a non-empty directory structure, empty
209 * subdirectories within that structure may or may not be deleted even if
210 * the method fails. Furthermore if the destination exists and is a file
211 * then the file will be deleted and then the rename is retried.
212 * <p>
213 * This operation is <em>not</em> atomic.
214 *
215 * @see FS#retryFailedLockFileCommit()
216 * @param src
217 * the old {@code File}
218 * @param dst
219 * the new {@code File}
220 * @throws IOException
221 * if the rename has failed
222 * @since 3.0
223 */
224 public static void rename(final File src, final File dst)
225 throws IOException {
226 rename(src, dst, StandardCopyOption.REPLACE_EXISTING);
227 }
228
229 /**
230 * Rename a file or folder using the passed {@link CopyOption}s. If the
231 * rename fails and if we are running on a filesystem where it makes sense
232 * to repeat a failing rename then repeat the rename operation up to 9 times
233 * with 100ms sleep time between two calls. Furthermore if the destination
234 * exists and is a directory hierarchy with only directories in it, the
235 * whole directory hierarchy will be deleted. If the target represents a
236 * non-empty directory structure, empty subdirectories within that structure
237 * may or may not be deleted even if the method fails. Furthermore if the
238 * destination exists and is a file then the file will be replaced if
239 * {@link StandardCopyOption#REPLACE_EXISTING} has been set. If
240 * {@link StandardCopyOption#ATOMIC_MOVE} has been set the rename will be
241 * done atomically or fail with an {@link AtomicMoveNotSupportedException}
242 *
243 * @param src
244 * the old file
245 * @param dst
246 * the new file
247 * @param options
248 * options to pass to
249 * {@link Files#move(java.nio.file.Path, java.nio.file.Path, CopyOption...)}
250 * @throws AtomicMoveNotSupportedException
251 * if file cannot be moved as an atomic file system operation
252 * @throws IOException
253 * @since 4.1
254 */
255 public static void rename(final File src, final File dst,
256 CopyOption... options)
257 throws AtomicMoveNotSupportedException, IOException {
258 int attempts = FS.DETECTED.retryFailedLockFileCommit() ? 10 : 1;
259 while (--attempts >= 0) {
260 try {
261 Files.move(src.toPath(), dst.toPath(), options);
262 return;
263 } catch (AtomicMoveNotSupportedException e) {
264 throw e;
265 } catch (IOException e) {
266 try {
267 if (!dst.delete()) {
268 delete(dst, EMPTY_DIRECTORIES_ONLY | RECURSIVE);
269 }
270 // On *nix there is no try, you do or do not
271 Files.move(src.toPath(), dst.toPath(), options);
272 return;
273 } catch (IOException e2) {
274 // ignore and continue retry
275 }
276 }
277 try {
278 Thread.sleep(100);
279 } catch (InterruptedException e) {
280 throw new IOException(
281 MessageFormat.format(JGitText.get().renameFileFailed,
282 src.getAbsolutePath(), dst.getAbsolutePath()));
283 }
284 }
285 throw new IOException(
286 MessageFormat.format(JGitText.get().renameFileFailed,
287 src.getAbsolutePath(), dst.getAbsolutePath()));
288 }
289
290 /**
291 * Creates the directory named by this abstract pathname.
292 *
293 * @param d
294 * directory to be created
295 * @throws IOException
296 * if creation of {@code d} fails. This may occur if {@code d}
297 * did exist when the method was called. This can therefore
298 * cause IOExceptions during race conditions when multiple
299 * concurrent threads all try to create the same directory.
300 */
301 public static void mkdir(final File d)
302 throws IOException {
303 mkdir(d, false);
304 }
305
306 /**
307 * Creates the directory named by this abstract pathname.
308 *
309 * @param d
310 * directory to be created
311 * @param skipExisting
312 * if {@code true} skip creation of the given directory if it
313 * already exists in the file system
314 * @throws IOException
315 * if creation of {@code d} fails. This may occur if {@code d}
316 * did exist when the method was called. This can therefore
317 * cause IOExceptions during race conditions when multiple
318 * concurrent threads all try to create the same directory.
319 */
320 public static void mkdir(final File d, boolean skipExisting)
321 throws IOException {
322 if (!d.mkdir()) {
323 if (skipExisting && d.isDirectory())
324 return;
325 throw new IOException(MessageFormat.format(
326 JGitText.get().mkDirFailed, d.getAbsolutePath()));
327 }
328 }
329
330 /**
331 * Creates the directory named by this abstract pathname, including any
332 * necessary but nonexistent parent directories. Note that if this operation
333 * fails it may have succeeded in creating some of the necessary parent
334 * directories.
335 *
336 * @param d
337 * directory to be created
338 * @throws IOException
339 * if creation of {@code d} fails. This may occur if {@code d}
340 * did exist when the method was called. This can therefore
341 * cause IOExceptions during race conditions when multiple
342 * concurrent threads all try to create the same directory.
343 */
344 public static void mkdirs(final File d) throws IOException {
345 mkdirs(d, false);
346 }
347
348 /**
349 * Creates the directory named by this abstract pathname, including any
350 * necessary but nonexistent parent directories. Note that if this operation
351 * fails it may have succeeded in creating some of the necessary parent
352 * directories.
353 *
354 * @param d
355 * directory to be created
356 * @param skipExisting
357 * if {@code true} skip creation of the given directory if it
358 * already exists in the file system
359 * @throws IOException
360 * if creation of {@code d} fails. This may occur if {@code d}
361 * did exist when the method was called. This can therefore
362 * cause IOExceptions during race conditions when multiple
363 * concurrent threads all try to create the same directory.
364 */
365 public static void mkdirs(final File d, boolean skipExisting)
366 throws IOException {
367 if (!d.mkdirs()) {
368 if (skipExisting && d.isDirectory())
369 return;
370 throw new IOException(MessageFormat.format(
371 JGitText.get().mkDirsFailed, d.getAbsolutePath()));
372 }
373 }
374
375 /**
376 * Atomically creates a new, empty file named by this abstract pathname if
377 * and only if a file with this name does not yet exist. The check for the
378 * existence of the file and the creation of the file if it does not exist
379 * are a single operation that is atomic with respect to all other
380 * filesystem activities that might affect the file.
381 * <p>
382 * Note: this method should not be used for file-locking, as the resulting
383 * protocol cannot be made to work reliably. The {@link FileLock} facility
384 * should be used instead.
385 *
386 * @param f
387 * the file to be created
388 * @throws IOException
389 * if the named file already exists or if an I/O error occurred
390 */
391 public static void createNewFile(File f) throws IOException {
392 if (!f.createNewFile())
393 throw new IOException(MessageFormat.format(
394 JGitText.get().createNewFileFailed, f));
395 }
396
397 /**
398 * Create a symbolic link
399 *
400 * @param path
401 * the path of the symbolic link to create
402 * @param target
403 * the target of the symbolic link
404 * @return the path to the symbolic link
405 * @throws IOException
406 * @since 4.2
407 */
408 public static Path createSymLink(File path, String target)
409 throws IOException {
410 Path nioPath = path.toPath();
411 if (Files.exists(nioPath, LinkOption.NOFOLLOW_LINKS)) {
412 BasicFileAttributes attrs = Files.readAttributes(nioPath,
413 BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
414 if (attrs.isRegularFile() || attrs.isSymbolicLink()) {
415 delete(path);
416 } else {
417 delete(path, EMPTY_DIRECTORIES_ONLY | RECURSIVE);
418 }
419 }
420 if (SystemReader.getInstance().isWindows()) {
421 target = target.replace('/', '\\');
422 }
423 Path nioTarget = new File(target).toPath();
424 return Files.createSymbolicLink(nioPath, nioTarget);
425 }
426
427 /**
428 * @param path
429 * @return target path of the symlink, or null if it is not a symbolic link
430 * @throws IOException
431 * @since 3.0
432 */
433 public static String readSymLink(File path) throws IOException {
434 Path nioPath = path.toPath();
435 Path target = Files.readSymbolicLink(nioPath);
436 String targetString = target.toString();
437 if (SystemReader.getInstance().isWindows()) {
438 targetString = targetString.replace('\\', '/');
439 } else if (SystemReader.getInstance().isMacOS()) {
440 targetString = Normalizer.normalize(targetString, Form.NFC);
441 }
442 return targetString;
443 }
444
445 /**
446 * Create a temporary directory.
447 *
448 * @param prefix
449 * @param suffix
450 * @param dir
451 * The parent dir, can be null to use system default temp dir.
452 * @return the temp dir created.
453 * @throws IOException
454 * @since 3.4
455 */
456 public static File createTempDir(String prefix, String suffix, File dir)
457 throws IOException {
458 final int RETRIES = 1; // When something bad happens, retry once.
459 for (int i = 0; i < RETRIES; i++) {
460 File tmp = File.createTempFile(prefix, suffix, dir);
461 if (!tmp.delete())
462 continue;
463 if (!tmp.mkdir())
464 continue;
465 return tmp;
466 }
467 throw new IOException(JGitText.get().cannotCreateTempDir);
468 }
469
470 /**
471 * This will try and make a given path relative to another.
472 * <p>
473 * For example, if this is called with the two following paths :
474 *
475 * <pre>
476 * <code>base = "c:\\Users\\jdoe\\eclipse\\git\\project"</code>
477 * <code>other = "c:\\Users\\jdoe\\eclipse\\git\\another_project\\pom.xml"</code>
478 * </pre>
479 *
480 * This will return "..\\another_project\\pom.xml".
481 * </p>
482 * <p>
483 * This method uses {@link File#separator} to split the paths into segments.
484 * </p>
485 * <p>
486 * <b>Note</b> that this will return the empty String if <code>base</code>
487 * and <code>other</code> are equal.
488 * </p>
489 *
490 * @param base
491 * The path against which <code>other</code> should be
492 * relativized. This will be assumed to denote the path to a
493 * folder and not a file.
494 * @param other
495 * The path that will be made relative to <code>base</code>.
496 * @return A relative path that, when resolved against <code>base</code>,
497 * will yield the original <code>other</code>.
498 * @since 3.7
499 */
500 public static String relativize(String base, String other) {
501 if (base.equals(other))
502 return ""; //$NON-NLS-1$
503
504 final boolean ignoreCase = !FS.DETECTED.isCaseSensitive();
505 final String[] baseSegments = base.split(Pattern.quote(File.separator));
506 final String[] otherSegments = other.split(Pattern
507 .quote(File.separator));
508
509 int commonPrefix = 0;
510 while (commonPrefix < baseSegments.length
511 && commonPrefix < otherSegments.length) {
512 if (ignoreCase
513 && baseSegments[commonPrefix]
514 .equalsIgnoreCase(otherSegments[commonPrefix]))
515 commonPrefix++;
516 else if (!ignoreCase
517 && baseSegments[commonPrefix]
518 .equals(otherSegments[commonPrefix]))
519 commonPrefix++;
520 else
521 break;
522 }
523
524 final StringBuilder builder = new StringBuilder();
525 for (int i = commonPrefix; i < baseSegments.length; i++)
526 builder.append("..").append(File.separator); //$NON-NLS-1$
527 for (int i = commonPrefix; i < otherSegments.length; i++) {
528 builder.append(otherSegments[i]);
529 if (i < otherSegments.length - 1)
530 builder.append(File.separator);
531 }
532 return builder.toString();
533 }
534
535 /**
536 * Determine if an IOException is a Stale NFS File Handle
537 *
538 * @param ioe
539 * @return a boolean true if the IOException is a Stale NFS FIle Handle
540 * @since 4.1
541 */
542 public static boolean isStaleFileHandle(IOException ioe) {
543 String msg = ioe.getMessage();
544 return msg != null
545 && msg.toLowerCase().matches("stale .*file .*handle"); //$NON-NLS-1$
546 }
547
548 /**
549 * @param file
550 * @return {@code true} if the passed file is a symbolic link
551 */
552 static boolean isSymlink(File file) {
553 return Files.isSymbolicLink(file.toPath());
554 }
555
556 /**
557 * @param file
558 * @return lastModified attribute for given file, not following symbolic
559 * links
560 * @throws IOException
561 */
562 static long lastModified(File file) throws IOException {
563 return Files.getLastModifiedTime(file.toPath(), LinkOption.NOFOLLOW_LINKS)
564 .toMillis();
565 }
566
567 /**
568 * @param file
569 * @param time
570 * @throws IOException
571 */
572 static void setLastModified(File file, long time) throws IOException {
573 Files.setLastModifiedTime(file.toPath(), FileTime.fromMillis(time));
574 }
575
576 /**
577 * @param file
578 * @return {@code true} if the given file exists, not following symbolic
579 * links
580 */
581 static boolean exists(File file) {
582 return Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS);
583 }
584
585 /**
586 * @param file
587 * @return {@code true} if the given file is hidden
588 * @throws IOException
589 */
590 static boolean isHidden(File file) throws IOException {
591 return Files.isHidden(file.toPath());
592 }
593
594 /**
595 * @param file
596 * @param hidden
597 * @throws IOException
598 * @since 4.1
599 */
600 public static void setHidden(File file, boolean hidden) throws IOException {
601 Files.setAttribute(file.toPath(), "dos:hidden", Boolean.valueOf(hidden), //$NON-NLS-1$
602 LinkOption.NOFOLLOW_LINKS);
603 }
604
605 /**
606 * @param file
607 * @return length of the given file
608 * @throws IOException
609 * @since 4.1
610 */
611 public static long getLength(File file) throws IOException {
612 Path nioPath = file.toPath();
613 if (Files.isSymbolicLink(nioPath))
614 return Files.readSymbolicLink(nioPath).toString()
615 .getBytes(Constants.CHARSET).length;
616 return Files.size(nioPath);
617 }
618
619 /**
620 * @param file
621 * @return {@code true} if the given file is a directory, not following
622 * symbolic links
623 */
624 static boolean isDirectory(File file) {
625 return Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS);
626 }
627
628 /**
629 * @param file
630 * @return {@code true} if the given file is a file, not following symbolic
631 * links
632 */
633 static boolean isFile(File file) {
634 return Files.isRegularFile(file.toPath(), LinkOption.NOFOLLOW_LINKS);
635 }
636
637 /**
638 * @param file
639 * @return {@code true} if the given file can be executed
640 * @since 4.1
641 */
642 public static boolean canExecute(File file) {
643 if (!isFile(file)) {
644 return false;
645 }
646 return Files.isExecutable(file.toPath());
647 }
648
649 /**
650 * @param fs
651 * @param file
652 * @return non null attributes object
653 */
654 static Attributes getFileAttributesBasic(FS fs, File file) {
655 try {
656 Path nioPath = file.toPath();
657 BasicFileAttributes readAttributes = nioPath
658 .getFileSystem()
659 .provider()
660 .getFileAttributeView(nioPath,
661 BasicFileAttributeView.class,
662 LinkOption.NOFOLLOW_LINKS).readAttributes();
663 Attributes attributes = new Attributes(fs, file,
664 true,
665 readAttributes.isDirectory(),
666 fs.supportsExecute() ? file.canExecute() : false,
667 readAttributes.isSymbolicLink(),
668 readAttributes.isRegularFile(), //
669 readAttributes.creationTime().toMillis(), //
670 readAttributes.lastModifiedTime().toMillis(),
671 readAttributes.isSymbolicLink() ? Constants
672 .encode(readSymLink(file)).length
673 : readAttributes.size());
674 return attributes;
675 } catch (IOException e) {
676 return new Attributes(file, fs);
677 }
678 }
679
680 /**
681 * @param fs
682 * @param file
683 * @return file system attributes for the given file
684 * @since 4.1
685 */
686 public static Attributes getFileAttributesPosix(FS fs, File file) {
687 try {
688 Path nioPath = file.toPath();
689 PosixFileAttributes readAttributes = nioPath
690 .getFileSystem()
691 .provider()
692 .getFileAttributeView(nioPath,
693 PosixFileAttributeView.class,
694 LinkOption.NOFOLLOW_LINKS).readAttributes();
695 Attributes attributes = new Attributes(
696 fs,
697 file,
698 true, //
699 readAttributes.isDirectory(), //
700 readAttributes.permissions().contains(
701 PosixFilePermission.OWNER_EXECUTE),
702 readAttributes.isSymbolicLink(),
703 readAttributes.isRegularFile(), //
704 readAttributes.creationTime().toMillis(), //
705 readAttributes.lastModifiedTime().toMillis(),
706 readAttributes.size());
707 return attributes;
708 } catch (IOException e) {
709 return new Attributes(file, fs);
710 }
711 }
712
713 /**
714 * @param file
715 * @return on Mac: NFC normalized {@link File}, otherwise the passed file
716 * @since 4.1
717 */
718 public static File normalize(File file) {
719 if (SystemReader.getInstance().isMacOS()) {
720 // TODO: Would it be faster to check with isNormalized first
721 // assuming normalized paths are much more common
722 String normalized = Normalizer.normalize(file.getPath(),
723 Normalizer.Form.NFC);
724 return new File(normalized);
725 }
726 return file;
727 }
728
729 /**
730 * @param name
731 * @return on Mac: NFC normalized form of given name
732 * @since 4.1
733 */
734 public static String normalize(String name) {
735 if (SystemReader.getInstance().isMacOS()) {
736 if (name == null)
737 return null;
738 return Normalizer.normalize(name, Normalizer.Form.NFC);
739 }
740 return name;
741 }
742
743 /**
744 * Best-effort variation of {@link File#getCanonicalFile()} returning the
745 * input file if the file cannot be canonicalized instead of throwing
746 * {@link IOException}.
747 *
748 * @param file
749 * to be canonicalized; may be {@code null}
750 * @return canonicalized file, or the unchanged input file if
751 * canonicalization failed or if {@code file == null}
752 * @throws SecurityException
753 * if {@link File#getCanonicalFile()} throws one
754 * @since 4.2
755 */
756 public static File canonicalize(File file) {
757 if (file == null) {
758 return null;
759 }
760 try {
761 return file.getCanonicalFile();
762 } catch (IOException e) {
763 return file;
764 }
765 }
766
767 }