You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileUtils.java 24KB

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