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

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