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.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 * File Utilities
77 */
78 public class FileUtils {
79
80 /**
81 * Option to delete given {@code File}
82 */
83 public static final int NONE = 0;
84
85 /**
86 * Option to recursively delete given {@code File}
87 */
88 public static final int RECURSIVE = 1;
89
90 /**
91 * Option to retry deletion if not successful
92 */
93 public static final int RETRY = 2;
94
95 /**
96 * Option to skip deletion if file doesn't exist
97 */
98 public static final int SKIP_MISSING = 4;
99
100 /**
101 * Option not to throw exceptions when a deletion finally doesn't succeed.
102 * @since 2.0
103 */
104 public static final int IGNORE_ERRORS = 8;
105
106 /**
107 * Option to only delete empty directories. This option can be combined with
108 * {@link #RECURSIVE}
109 *
110 * @since 3.0
111 */
112 public static final int EMPTY_DIRECTORIES_ONLY = 16;
113
114 /**
115 * Delete file or empty folder
116 *
117 * @param f
118 * {@code File} to be deleted
119 * @throws IOException
120 * if deletion of {@code f} fails. This may occur if {@code f}
121 * didn't exist when the method was called. This can therefore
122 * cause IOExceptions during race conditions when multiple
123 * concurrent threads all try to delete the same file.
124 */
125 public static void delete(final File f) throws IOException {
126 delete(f, NONE);
127 }
128
129 /**
130 * Delete file or folder
131 *
132 * @param f
133 * {@code File} to be deleted
134 * @param options
135 * deletion options, {@code RECURSIVE} for recursive deletion of
136 * a subtree, {@code RETRY} to retry when deletion failed.
137 * Retrying may help if the underlying file system doesn't allow
138 * deletion of files being read by another thread.
139 * @throws IOException
140 * if deletion of {@code f} fails. This may occur if {@code f}
141 * didn't exist when the method was called. This can therefore
142 * cause IOExceptions during race conditions when multiple
143 * concurrent threads all try to delete the same file. This
144 * exception is not thrown when IGNORE_ERRORS is set.
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 // Try to delete files first, otherwise options
162 // EMPTY_DIRECTORIES_ONLY|RECURSIVE will delete empty
163 // directories before aborting, depending on order.
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 // ignore
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 * Rename a file or folder. If the rename fails and if we are running on a
205 * filesystem where it makes sense to repeat a failing rename then repeat
206 * the rename operation up to 9 times with 100ms sleep time between two
207 * calls. Furthermore if the destination exists and is directory hierarchy
208 * with only directories in it, the whole directory hierarchy will be
209 * deleted. If the target represents a non-empty directory structure, empty
210 * subdirectories within that structure may or may not be deleted even if
211 * the method fails. Furthermore if the destination exists and is a file
212 * then the file will be deleted and then the rename is retried.
213 * <p>
214 * This operation is <em>not</em> atomic.
215 *
216 * @see FS#retryFailedLockFileCommit()
217 * @param src
218 * the old {@code File}
219 * @param dst
220 * the new {@code File}
221 * @throws IOException
222 * if the rename has failed
223 * @since 3.0
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 * Rename a file or folder using the passed {@link CopyOption}s. If the
232 * rename fails and if we are running on a filesystem where it makes sense
233 * to repeat a failing rename then repeat the rename operation up to 9 times
234 * with 100ms sleep time between two calls. Furthermore if the destination
235 * exists and is a directory hierarchy with only directories in it, the
236 * whole directory hierarchy will be deleted. If the target represents a
237 * non-empty directory structure, empty subdirectories within that structure
238 * may or may not be deleted even if the method fails. Furthermore if the
239 * destination exists and is a file then the file will be replaced if
240 * {@link StandardCopyOption#REPLACE_EXISTING} has been set. If
241 * {@link StandardCopyOption#ATOMIC_MOVE} has been set the rename will be
242 * done atomically or fail with an {@link AtomicMoveNotSupportedException}
243 *
244 * @param src
245 * the old file
246 * @param dst
247 * the new file
248 * @param options
249 * options to pass to
250 * {@link Files#move(java.nio.file.Path, java.nio.file.Path, CopyOption...)}
251 * @throws AtomicMoveNotSupportedException
252 * if file cannot be moved as an atomic file system operation
253 * @throws IOException
254 * @since 4.1
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 // On *nix there is no try, you do or do not
272 Files.move(src.toPath(), dst.toPath(), options);
273 return;
274 } catch (IOException e2) {
275 // ignore and continue retry
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 * Creates the directory named by this abstract pathname.
293 *
294 * @param d
295 * directory to be created
296 * @throws IOException
297 * if creation of {@code d} fails. This may occur if {@code d}
298 * did exist when the method was called. This can therefore
299 * cause IOExceptions during race conditions when multiple
300 * concurrent threads all try to create the same directory.
301 */
302 public static void mkdir(final File d)
303 throws IOException {
304 mkdir(d, false);
305 }
306
307 /**
308 * Creates the directory named by this abstract pathname.
309 *
310 * @param d
311 * directory to be created
312 * @param skipExisting
313 * if {@code true} skip creation of the given directory if it
314 * already exists in the file system
315 * @throws IOException
316 * if creation of {@code d} fails. This may occur if {@code d}
317 * did exist when the method was called. This can therefore
318 * cause IOExceptions during race conditions when multiple
319 * concurrent threads all try to create the same directory.
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 * Creates the directory named by this abstract pathname, including any
333 * necessary but nonexistent parent directories. Note that if this operation
334 * fails it may have succeeded in creating some of the necessary parent
335 * directories.
336 *
337 * @param d
338 * directory to be created
339 * @throws IOException
340 * if creation of {@code d} fails. This may occur if {@code d}
341 * did exist when the method was called. This can therefore
342 * cause IOExceptions during race conditions when multiple
343 * concurrent threads all try to create the same directory.
344 */
345 public static void mkdirs(final File d) throws IOException {
346 mkdirs(d, false);
347 }
348
349 /**
350 * Creates the directory named by this abstract pathname, including any
351 * necessary but nonexistent parent directories. Note that if this operation
352 * fails it may have succeeded in creating some of the necessary parent
353 * directories.
354 *
355 * @param d
356 * directory to be created
357 * @param skipExisting
358 * if {@code true} skip creation of the given directory if it
359 * already exists in the file system
360 * @throws IOException
361 * if creation of {@code d} fails. This may occur if {@code d}
362 * did exist when the method was called. This can therefore
363 * cause IOExceptions during race conditions when multiple
364 * concurrent threads all try to create the same directory.
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 * Atomically creates a new, empty file named by this abstract pathname if
378 * and only if a file with this name does not yet exist. The check for the
379 * existence of the file and the creation of the file if it does not exist
380 * are a single operation that is atomic with respect to all other
381 * filesystem activities that might affect the file.
382 * <p>
383 * Note: this method should not be used for file-locking, as the resulting
384 * protocol cannot be made to work reliably. The {@link FileLock} facility
385 * should be used instead.
386 *
387 * @param f
388 * the file to be created
389 * @throws IOException
390 * if the named file already exists or if an I/O error occurred
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 * Create a symbolic link
400 *
401 * @param path
402 * the path of the symbolic link to create
403 * @param target
404 * the target of the symbolic link
405 * @return the path to the symbolic link
406 * @throws IOException
407 * @since 4.2
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 * @param path
430 * @return target path of the symlink, or null if it is not a symbolic link
431 * @throws IOException
432 * @since 3.0
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 * Create a temporary directory.
448 *
449 * @param prefix
450 * @param suffix
451 * @param dir
452 * The parent dir, can be null to use system default temp dir.
453 * @return the temp dir created.
454 * @throws IOException
455 * @since 3.4
456 */
457 public static File createTempDir(String prefix, String suffix, File dir)
458 throws IOException {
459 final int RETRIES = 1; // When something bad happens, retry once.
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 * @deprecated Use the more-clearly-named
474 * {@link FileUtils#relativizeNativePath(String, String)}
475 * instead, or directly call
476 * {@link FileUtils#relativizePath(String, String, String, boolean)}
477 *
478 * Expresses <code>other</code> as a relative file path from
479 * <code>base</code>. File-separator and case sensitivity are
480 * based on the current file system.
481 *
482 * See also
483 * {@link FileUtils#relativizePath(String, String, String, boolean)}.
484 *
485 * @param base
486 * Base path
487 * @param other
488 * Destination path
489 * @return Relative path from <code>base</code> to <code>other</code>
490 * @since 3.7
491 */
492 @Deprecated
493 public static String relativize(String base, String other) {
494 return relativizeNativePath(base, other);
495 }
496
497 /**
498 * Expresses <code>other</code> as a relative file path from <code>base</code>.
499 * File-separator and case sensitivity are based on the current file system.
500 *
501 * See also {@link FileUtils#relativizePath(String, String, String, boolean)}.
502 *
503 * @param base
504 * Base path
505 * @param other
506 * Destination path
507 * @return Relative path from <code>base</code> to <code>other</code>
508 * @since 4.8
509 */
510 public static String relativizeNativePath(String base, String other) {
511 return FS.DETECTED.relativize(base, other);
512 }
513
514 /**
515 * Expresses <code>other</code> as a relative file path from <code>base</code>.
516 * File-separator and case sensitivity are based on Git's internal representation of files (which matches Unix).
517 *
518 * See also {@link FileUtils#relativizePath(String, String, String, boolean)}.
519 *
520 * @param base
521 * Base path
522 * @param other
523 * Destination path
524 * @return Relative path from <code>base</code> to <code>other</code>
525 * @since 4.8
526 */
527 public static String relativizeGitPath(String base, String other) {
528 return relativizePath(base, other, "/", false); //$NON-NLS-1$
529 }
530
531
532 /**
533 * Expresses <code>other</code> as a relative file path from <code>base</code>
534 * <p>
535 * For example, if called with the two following paths :
536 *
537 * <pre>
538 * <code>base = "c:\\Users\\jdoe\\eclipse\\git\\project"</code>
539 * <code>other = "c:\\Users\\jdoe\\eclipse\\git\\another_project\\pom.xml"</code>
540 * </pre>
541 *
542 * This will return "..\\another_project\\pom.xml".
543 * </p>
544 *
545 * <p>
546 * <b>Note</b> that this will return the empty String if <code>base</code>
547 * and <code>other</code> are equal.
548 * </p>
549 *
550 * @param base
551 * The path against which <code>other</code> should be
552 * relativized. This will be assumed to denote the path to a
553 * folder and not a file.
554 * @param other
555 * The path that will be made relative to <code>base</code>.
556 * @param dirSeparator
557 * A string that separates components of the path. In practice, this is "/" or "\\".
558 * @param caseSensitive
559 * Whether to consider differently-cased directory names as distinct
560 * @return A relative path that, when resolved against <code>base</code>,
561 * will yield the original <code>other</code>.
562 * @since 4.8
563 */
564 public static String relativizePath(String base, String other, String dirSeparator, boolean caseSensitive) {
565 if (base.equals(other))
566 return ""; //$NON-NLS-1$
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); //$NON-NLS-1$
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 * Determine if an IOException is a Stale NFS File Handle
600 *
601 * @param ioe
602 * @return a boolean true if the IOException is a Stale NFS FIle Handle
603 * @since 4.1
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"); //$NON-NLS-1$
610 }
611
612 /**
613 * Determine if a throwable or a cause in its causal chain is a Stale NFS
614 * File Handle
615 *
616 * @param throwable
617 * @return a boolean true if the throwable or a cause in its causal chain is
618 * a Stale NFS File Handle
619 * @since 4.7
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 * @param file
634 * @return {@code true} if the passed file is a symbolic link
635 */
636 static boolean isSymlink(File file) {
637 return Files.isSymbolicLink(file.toPath());
638 }
639
640 /**
641 * @param file
642 * @return lastModified attribute for given file, not following symbolic
643 * links
644 * @throws IOException
645 */
646 static long lastModified(File file) throws IOException {
647 return Files.getLastModifiedTime(file.toPath(), LinkOption.NOFOLLOW_LINKS)
648 .toMillis();
649 }
650
651 /**
652 * @param file
653 * @param time
654 * @throws IOException
655 */
656 static void setLastModified(File file, long time) throws IOException {
657 Files.setLastModifiedTime(file.toPath(), FileTime.fromMillis(time));
658 }
659
660 /**
661 * @param file
662 * @return {@code true} if the given file exists, not following symbolic
663 * links
664 */
665 static boolean exists(File file) {
666 return Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS);
667 }
668
669 /**
670 * @param file
671 * @return {@code true} if the given file is hidden
672 * @throws IOException
673 */
674 static boolean isHidden(File file) throws IOException {
675 return Files.isHidden(file.toPath());
676 }
677
678 /**
679 * @param file
680 * @param hidden
681 * @throws IOException
682 * @since 4.1
683 */
684 public static void setHidden(File file, boolean hidden) throws IOException {
685 Files.setAttribute(file.toPath(), "dos:hidden", Boolean.valueOf(hidden), //$NON-NLS-1$
686 LinkOption.NOFOLLOW_LINKS);
687 }
688
689 /**
690 * @param file
691 * @return length of the given file
692 * @throws IOException
693 * @since 4.1
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 * @param file
705 * @return {@code true} if the given file is a directory, not following
706 * symbolic links
707 */
708 static boolean isDirectory(File file) {
709 return Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS);
710 }
711
712 /**
713 * @param file
714 * @return {@code true} if the given file is a file, not following symbolic
715 * links
716 */
717 static boolean isFile(File file) {
718 return Files.isRegularFile(file.toPath(), LinkOption.NOFOLLOW_LINKS);
719 }
720
721 /**
722 * @param file
723 * @return {@code true} if the given file can be executed
724 * @since 4.1
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 * @param fs
735 * @param file
736 * @return non null attributes object
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 * @param fs
766 * @param file
767 * @return file system attributes for the given file
768 * @since 4.1
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 * @param file
799 * @return on Mac: NFC normalized {@link File}, otherwise the passed file
800 * @since 4.1
801 */
802 public static File normalize(File file) {
803 if (SystemReader.getInstance().isMacOS()) {
804 // TODO: Would it be faster to check with isNormalized first
805 // assuming normalized paths are much more common
806 String normalized = Normalizer.normalize(file.getPath(),
807 Normalizer.Form.NFC);
808 return new File(normalized);
809 }
810 return file;
811 }
812
813 /**
814 * @param name
815 * @return on Mac: NFC normalized form of given name
816 * @since 4.1
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 * Best-effort variation of {@link File#getCanonicalFile()} returning the
829 * input file if the file cannot be canonicalized instead of throwing
830 * {@link IOException}.
831 *
832 * @param file
833 * to be canonicalized; may be {@code null}
834 * @return canonicalized file, or the unchanged input file if
835 * canonicalization failed or if {@code file == null}
836 * @throws SecurityException
837 * if {@link File#getCanonicalFile()} throws one
838 * @since 4.2
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 }