View Javadoc
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 	 * @param target
402 	 * @throws IOException
403 	 * @since 3.0
404 	 */
405 	public static void createSymLink(File path, String target)
406 			throws IOException {
407 		Path nioPath = path.toPath();
408 		if (Files.exists(nioPath, LinkOption.NOFOLLOW_LINKS)) {
409 			Files.delete(nioPath);
410 		}
411 		if (SystemReader.getInstance().isWindows()) {
412 			target = target.replace('/', '\\');
413 		}
414 		Path nioTarget = new File(target).toPath();
415 		Files.createSymbolicLink(nioPath, nioTarget);
416 	}
417 
418 	/**
419 	 * @param path
420 	 * @return target path of the symlink, or null if it is not a symbolic link
421 	 * @throws IOException
422 	 * @since 3.0
423 	 */
424 	public static String readSymLink(File path) throws IOException {
425 		Path nioPath = path.toPath();
426 		Path target = Files.readSymbolicLink(nioPath);
427 		String targetString = target.toString();
428 		if (SystemReader.getInstance().isWindows()) {
429 			targetString = targetString.replace('\\', '/');
430 		} else if (SystemReader.getInstance().isMacOS()) {
431 			targetString = Normalizer.normalize(targetString, Form.NFC);
432 		}
433 		return targetString;
434 	}
435 
436 	/**
437 	 * Create a temporary directory.
438 	 *
439 	 * @param prefix
440 	 * @param suffix
441 	 * @param dir
442 	 *            The parent dir, can be null to use system default temp dir.
443 	 * @return the temp dir created.
444 	 * @throws IOException
445 	 * @since 3.4
446 	 */
447 	public static File createTempDir(String prefix, String suffix, File dir)
448 			throws IOException {
449 		final int RETRIES = 1; // When something bad happens, retry once.
450 		for (int i = 0; i < RETRIES; i++) {
451 			File tmp = File.createTempFile(prefix, suffix, dir);
452 			if (!tmp.delete())
453 				continue;
454 			if (!tmp.mkdir())
455 				continue;
456 			return tmp;
457 		}
458 		throw new IOException(JGitText.get().cannotCreateTempDir);
459 	}
460 
461 	/**
462 	 * This will try and make a given path relative to another.
463 	 * <p>
464 	 * For example, if this is called with the two following paths :
465 	 *
466 	 * <pre>
467 	 * <code>base = "c:\\Users\\jdoe\\eclipse\\git\\project"</code>
468 	 * <code>other = "c:\\Users\\jdoe\\eclipse\\git\\another_project\\pom.xml"</code>
469 	 * </pre>
470 	 *
471 	 * This will return "..\\another_project\\pom.xml".
472 	 * </p>
473 	 * <p>
474 	 * This method uses {@link File#separator} to split the paths into segments.
475 	 * </p>
476 	 * <p>
477 	 * <b>Note</b> that this will return the empty String if <code>base</code>
478 	 * and <code>other</code> are equal.
479 	 * </p>
480 	 *
481 	 * @param base
482 	 *            The path against which <code>other</code> should be
483 	 *            relativized. This will be assumed to denote the path to a
484 	 *            folder and not a file.
485 	 * @param other
486 	 *            The path that will be made relative to <code>base</code>.
487 	 * @return A relative path that, when resolved against <code>base</code>,
488 	 *         will yield the original <code>other</code>.
489 	 * @since 3.7
490 	 */
491 	public static String relativize(String base, String other) {
492 		if (base.equals(other))
493 			return ""; //$NON-NLS-1$
494 
495 		final boolean ignoreCase = !FS.DETECTED.isCaseSensitive();
496 		final String[] baseSegments = base.split(Pattern.quote(File.separator));
497 		final String[] otherSegments = other.split(Pattern
498 				.quote(File.separator));
499 
500 		int commonPrefix = 0;
501 		while (commonPrefix < baseSegments.length
502 				&& commonPrefix < otherSegments.length) {
503 			if (ignoreCase
504 					&& baseSegments[commonPrefix]
505 							.equalsIgnoreCase(otherSegments[commonPrefix]))
506 				commonPrefix++;
507 			else if (!ignoreCase
508 					&& baseSegments[commonPrefix]
509 							.equals(otherSegments[commonPrefix]))
510 				commonPrefix++;
511 			else
512 				break;
513 		}
514 
515 		final StringBuilder builder = new StringBuilder();
516 		for (int i = commonPrefix; i < baseSegments.length; i++)
517 			builder.append("..").append(File.separator); //$NON-NLS-1$
518 		for (int i = commonPrefix; i < otherSegments.length; i++) {
519 			builder.append(otherSegments[i]);
520 			if (i < otherSegments.length - 1)
521 				builder.append(File.separator);
522 		}
523 		return builder.toString();
524 	}
525 
526 	/**
527 	 * Determine if an IOException is a Stale NFS File Handle
528 	 *
529 	 * @param ioe
530 	 * @return a boolean true if the IOException is a Stale NFS FIle Handle
531 	 * @since 4.1
532 	 */
533 	public static boolean isStaleFileHandle(IOException ioe) {
534 		String msg = ioe.getMessage();
535 		return msg != null
536 				&& msg.toLowerCase().matches("stale .*file .*handle"); //$NON-NLS-1$
537 	}
538 
539 	/**
540 	 * @param file
541 	 * @return {@code true} if the passed file is a symbolic link
542 	 */
543 	static boolean isSymlink(File file) {
544 		return Files.isSymbolicLink(file.toPath());
545 	}
546 
547 	/**
548 	 * @param file
549 	 * @return lastModified attribute for given file, not following symbolic
550 	 *         links
551 	 * @throws IOException
552 	 */
553 	static long lastModified(File file) throws IOException {
554 		return Files.getLastModifiedTime(file.toPath(), LinkOption.NOFOLLOW_LINKS)
555 				.toMillis();
556 	}
557 
558 	/**
559 	 * @param file
560 	 * @param time
561 	 * @throws IOException
562 	 */
563 	static void setLastModified(File file, long time) throws IOException {
564 		Files.setLastModifiedTime(file.toPath(), FileTime.fromMillis(time));
565 	}
566 
567 	/**
568 	 * @param file
569 	 * @return {@code true} if the given file exists, not following symbolic
570 	 *         links
571 	 */
572 	static boolean exists(File file) {
573 		return Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS);
574 	}
575 
576 	/**
577 	 * @param file
578 	 * @return {@code true} if the given file is hidden
579 	 * @throws IOException
580 	 */
581 	static boolean isHidden(File file) throws IOException {
582 		return Files.isHidden(file.toPath());
583 	}
584 
585 	/**
586 	 * @param file
587 	 * @param hidden
588 	 * @throws IOException
589 	 * @since 4.1
590 	 */
591 	public static void setHidden(File file, boolean hidden) throws IOException {
592 		Files.setAttribute(file.toPath(), "dos:hidden", Boolean.valueOf(hidden), //$NON-NLS-1$
593 				LinkOption.NOFOLLOW_LINKS);
594 	}
595 
596 	/**
597 	 * @param file
598 	 * @return length of the given file
599 	 * @throws IOException
600 	 * @since 4.1
601 	 */
602 	public static long getLength(File file) throws IOException {
603 		Path nioPath = file.toPath();
604 		if (Files.isSymbolicLink(nioPath))
605 			return Files.readSymbolicLink(nioPath).toString()
606 					.getBytes(Constants.CHARSET).length;
607 		return Files.size(nioPath);
608 	}
609 
610 	/**
611 	 * @param file
612 	 * @return {@code true} if the given file is a directory, not following
613 	 *         symbolic links
614 	 */
615 	static boolean isDirectory(File file) {
616 		return Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS);
617 	}
618 
619 	/**
620 	 * @param file
621 	 * @return {@code true} if the given file is a file, not following symbolic
622 	 *         links
623 	 */
624 	static boolean isFile(File file) {
625 		return Files.isRegularFile(file.toPath(), LinkOption.NOFOLLOW_LINKS);
626 	}
627 
628 	/**
629 	 * @param file
630 	 * @return {@code true} if the given file can be executed
631 	 * @since 4.1
632 	 */
633 	public static boolean canExecute(File file) {
634 		if (!isFile(file)) {
635 			return false;
636 		}
637 		return Files.isExecutable(file.toPath());
638 	}
639 
640 	/**
641 	 * @param fs
642 	 * @param file
643 	 * @return non null attributes object
644 	 */
645 	static Attributes getFileAttributesBasic(FS fs, File file) {
646 		try {
647 			Path nioPath = file.toPath();
648 			BasicFileAttributes readAttributes = nioPath
649 					.getFileSystem()
650 					.provider()
651 					.getFileAttributeView(nioPath,
652 							BasicFileAttributeView.class,
653 							LinkOption.NOFOLLOW_LINKS).readAttributes();
654 			Attributes attributes = new Attributes(fs, file,
655 					true,
656 					readAttributes.isDirectory(),
657 					fs.supportsExecute() ? file.canExecute() : false,
658 					readAttributes.isSymbolicLink(),
659 					readAttributes.isRegularFile(), //
660 					readAttributes.creationTime().toMillis(), //
661 					readAttributes.lastModifiedTime().toMillis(),
662 					readAttributes.isSymbolicLink() ? Constants
663 							.encode(readSymLink(file)).length
664 							: readAttributes.size());
665 			return attributes;
666 		} catch (IOException e) {
667 			return new Attributes(file, fs);
668 		}
669 	}
670 
671 	/**
672 	 * @param fs
673 	 * @param file
674 	 * @return file system attributes for the given file
675 	 * @since 4.1
676 	 */
677 	public static Attributes getFileAttributesPosix(FS fs, File file) {
678 		try {
679 			Path nioPath = file.toPath();
680 			PosixFileAttributes readAttributes = nioPath
681 					.getFileSystem()
682 					.provider()
683 					.getFileAttributeView(nioPath,
684 							PosixFileAttributeView.class,
685 							LinkOption.NOFOLLOW_LINKS).readAttributes();
686 			Attributes attributes = new Attributes(
687 					fs,
688 					file,
689 					true, //
690 					readAttributes.isDirectory(), //
691 					readAttributes.permissions().contains(
692 							PosixFilePermission.OWNER_EXECUTE),
693 					readAttributes.isSymbolicLink(),
694 					readAttributes.isRegularFile(), //
695 					readAttributes.creationTime().toMillis(), //
696 					readAttributes.lastModifiedTime().toMillis(),
697 					readAttributes.size());
698 			return attributes;
699 		} catch (IOException e) {
700 			return new Attributes(file, fs);
701 		}
702 	}
703 
704 	/**
705 	 * @param file
706 	 * @return on Mac: NFC normalized {@link File}, otherwise the passed file
707 	 * @since 4.1
708 	 */
709 	public static File normalize(File file) {
710 		if (SystemReader.getInstance().isMacOS()) {
711 			// TODO: Would it be faster to check with isNormalized first
712 			// assuming normalized paths are much more common
713 			String normalized = Normalizer.normalize(file.getPath(),
714 					Normalizer.Form.NFC);
715 			return new File(normalized);
716 		}
717 		return file;
718 	}
719 
720 	/**
721 	 * @param name
722 	 * @return on Mac: NFC normalized form of given name
723 	 * @since 4.1
724 	 */
725 	public static String normalize(String name) {
726 		if (SystemReader.getInstance().isMacOS()) {
727 			if (name == null)
728 				return null;
729 			return Normalizer.normalize(name, Normalizer.Form.NFC);
730 		}
731 		return name;
732 	}
733 }