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

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