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 28KB

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