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

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