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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /*
  2. * Copyright (C) 2010, Google Inc.
  3. * Copyright (C) 2010, Matthias Sohn <matthias.sohn@sap.com>
  4. * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.util;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.nio.channels.FileLock;
  49. import java.text.MessageFormat;
  50. import java.util.ArrayList;
  51. import java.util.List;
  52. import java.util.regex.Pattern;
  53. import org.eclipse.jgit.internal.JGitText;
  54. /**
  55. * File Utilities
  56. */
  57. public class FileUtils {
  58. /**
  59. * Option to delete given {@code File}
  60. */
  61. public static final int NONE = 0;
  62. /**
  63. * Option to recursively delete given {@code File}
  64. */
  65. public static final int RECURSIVE = 1;
  66. /**
  67. * Option to retry deletion if not successful
  68. */
  69. public static final int RETRY = 2;
  70. /**
  71. * Option to skip deletion if file doesn't exist
  72. */
  73. public static final int SKIP_MISSING = 4;
  74. /**
  75. * Option not to throw exceptions when a deletion finally doesn't succeed.
  76. * @since 2.0
  77. */
  78. public static final int IGNORE_ERRORS = 8;
  79. /**
  80. * Option to only delete empty directories. This option can be combined with
  81. * {@link #RECURSIVE}
  82. *
  83. * @since 3.0
  84. */
  85. public static final int EMPTY_DIRECTORIES_ONLY = 16;
  86. /**
  87. * Delete file or empty folder
  88. *
  89. * @param f
  90. * {@code File} to be deleted
  91. * @throws IOException
  92. * if deletion of {@code f} fails. This may occur if {@code f}
  93. * didn't exist when the method was called. This can therefore
  94. * cause IOExceptions during race conditions when multiple
  95. * concurrent threads all try to delete the same file.
  96. */
  97. public static void delete(final File f) throws IOException {
  98. delete(f, NONE);
  99. }
  100. /**
  101. * Delete file or folder
  102. *
  103. * @param f
  104. * {@code File} to be deleted
  105. * @param options
  106. * deletion options, {@code RECURSIVE} for recursive deletion of
  107. * a subtree, {@code RETRY} to retry when deletion failed.
  108. * Retrying may help if the underlying file system doesn't allow
  109. * deletion of files being read by another thread.
  110. * @throws IOException
  111. * if deletion of {@code f} fails. This may occur if {@code f}
  112. * didn't exist when the method was called. This can therefore
  113. * cause IOExceptions during race conditions when multiple
  114. * concurrent threads all try to delete the same file. This
  115. * exception is not thrown when IGNORE_ERRORS is set.
  116. */
  117. public static void delete(final File f, int options) throws IOException {
  118. FS fs = FS.DETECTED;
  119. if ((options & SKIP_MISSING) != 0 && !fs.exists(f))
  120. return;
  121. if ((options & RECURSIVE) != 0 && fs.isDirectory(f)) {
  122. final File[] items = f.listFiles();
  123. if (items != null) {
  124. List<File> files = new ArrayList<File>();
  125. List<File> dirs = new ArrayList<File>();
  126. for (File c : items)
  127. if (c.isFile())
  128. files.add(c);
  129. else
  130. dirs.add(c);
  131. // Try to delete files first, otherwise options
  132. // EMPTY_DIRECTORIES_ONLY|RECURSIVE will delete empty
  133. // directories before aborting, depending on order.
  134. for (File file : files)
  135. delete(file, options);
  136. for (File d : dirs)
  137. delete(d, options);
  138. }
  139. }
  140. boolean delete = false;
  141. if ((options & EMPTY_DIRECTORIES_ONLY) != 0) {
  142. if (f.isDirectory()) {
  143. delete = true;
  144. } else {
  145. if ((options & IGNORE_ERRORS) == 0)
  146. throw new IOException(MessageFormat.format(
  147. JGitText.get().deleteFileFailed,
  148. f.getAbsolutePath()));
  149. }
  150. } else {
  151. delete = true;
  152. }
  153. if (delete && !f.delete()) {
  154. if ((options & RETRY) != 0 && fs.exists(f)) {
  155. for (int i = 1; i < 10; i++) {
  156. try {
  157. Thread.sleep(100);
  158. } catch (InterruptedException e) {
  159. // ignore
  160. }
  161. if (f.delete())
  162. return;
  163. }
  164. }
  165. if ((options & IGNORE_ERRORS) == 0)
  166. throw new IOException(MessageFormat.format(
  167. JGitText.get().deleteFileFailed, f.getAbsolutePath()));
  168. }
  169. }
  170. /**
  171. * Rename a file or folder. If the rename fails and if we are running on a
  172. * filesystem where it makes sense to repeat a failing rename then repeat
  173. * the rename operation up to 9 times with 100ms sleep time between two
  174. * calls. Furthermore if the destination exists and is directory hierarchy
  175. * with only directories in it, the whole directory hierarchy will be
  176. * deleted. If the target represents a non-empty directory structure, empty
  177. * subdirectories within that structure may or may not be deleted even if
  178. * the method fails. Furthermore if the destination exists and is a file
  179. * then the file will be deleted and then the rename is retried.
  180. * <p>
  181. * This operation is <em>not</em> atomic.
  182. *
  183. * @see FS#retryFailedLockFileCommit()
  184. * @param src
  185. * the old {@code File}
  186. * @param dst
  187. * the new {@code File}
  188. * @throws IOException
  189. * if the rename has failed
  190. * @since 3.0
  191. */
  192. public static void rename(final File src, final File dst)
  193. throws IOException {
  194. int attempts = FS.DETECTED.retryFailedLockFileCommit() ? 10 : 1;
  195. while (--attempts >= 0) {
  196. if (src.renameTo(dst))
  197. return;
  198. try {
  199. if (!dst.delete())
  200. delete(dst, EMPTY_DIRECTORIES_ONLY | RECURSIVE);
  201. // On *nix there is no try, you do or do not
  202. if (src.renameTo(dst))
  203. return;
  204. } catch (IOException e) {
  205. // ignore and continue retry
  206. }
  207. try {
  208. Thread.sleep(100);
  209. } catch (InterruptedException e) {
  210. throw new IOException(MessageFormat.format(
  211. JGitText.get().renameFileFailed, src.getAbsolutePath(),
  212. dst.getAbsolutePath()));
  213. }
  214. }
  215. throw new IOException(MessageFormat.format(
  216. JGitText.get().renameFileFailed, src.getAbsolutePath(),
  217. dst.getAbsolutePath()));
  218. }
  219. /**
  220. * Creates the directory named by this abstract pathname.
  221. *
  222. * @param d
  223. * directory to be created
  224. * @throws IOException
  225. * if creation of {@code d} fails. This may occur if {@code d}
  226. * did exist when the method was called. This can therefore
  227. * cause IOExceptions during race conditions when multiple
  228. * concurrent threads all try to create the same directory.
  229. */
  230. public static void mkdir(final File d)
  231. throws IOException {
  232. mkdir(d, false);
  233. }
  234. /**
  235. * Creates the directory named by this abstract pathname.
  236. *
  237. * @param d
  238. * directory to be created
  239. * @param skipExisting
  240. * if {@code true} skip creation of the given directory if it
  241. * already exists in the file system
  242. * @throws IOException
  243. * if creation of {@code d} fails. This may occur if {@code d}
  244. * did exist when the method was called. This can therefore
  245. * cause IOExceptions during race conditions when multiple
  246. * concurrent threads all try to create the same directory.
  247. */
  248. public static void mkdir(final File d, boolean skipExisting)
  249. throws IOException {
  250. if (!d.mkdir()) {
  251. if (skipExisting && d.isDirectory())
  252. return;
  253. throw new IOException(MessageFormat.format(
  254. JGitText.get().mkDirFailed, d.getAbsolutePath()));
  255. }
  256. }
  257. /**
  258. * Creates the directory named by this abstract pathname, including any
  259. * necessary but nonexistent parent directories. Note that if this operation
  260. * fails it may have succeeded in creating some of the necessary parent
  261. * directories.
  262. *
  263. * @param d
  264. * directory to be created
  265. * @throws IOException
  266. * if creation of {@code d} fails. This may occur if {@code d}
  267. * did exist when the method was called. This can therefore
  268. * cause IOExceptions during race conditions when multiple
  269. * concurrent threads all try to create the same directory.
  270. */
  271. public static void mkdirs(final File d) throws IOException {
  272. mkdirs(d, false);
  273. }
  274. /**
  275. * Creates the directory named by this abstract pathname, including any
  276. * necessary but nonexistent parent directories. Note that if this operation
  277. * fails it may have succeeded in creating some of the necessary parent
  278. * directories.
  279. *
  280. * @param d
  281. * directory to be created
  282. * @param skipExisting
  283. * if {@code true} skip creation of the given directory if it
  284. * already exists in the file system
  285. * @throws IOException
  286. * if creation of {@code d} fails. This may occur if {@code d}
  287. * did exist when the method was called. This can therefore
  288. * cause IOExceptions during race conditions when multiple
  289. * concurrent threads all try to create the same directory.
  290. */
  291. public static void mkdirs(final File d, boolean skipExisting)
  292. throws IOException {
  293. if (!d.mkdirs()) {
  294. if (skipExisting && d.isDirectory())
  295. return;
  296. throw new IOException(MessageFormat.format(
  297. JGitText.get().mkDirsFailed, d.getAbsolutePath()));
  298. }
  299. }
  300. /**
  301. * Atomically creates a new, empty file named by this abstract pathname if
  302. * and only if a file with this name does not yet exist. The check for the
  303. * existence of the file and the creation of the file if it does not exist
  304. * are a single operation that is atomic with respect to all other
  305. * filesystem activities that might affect the file.
  306. * <p>
  307. * Note: this method should not be used for file-locking, as the resulting
  308. * protocol cannot be made to work reliably. The {@link FileLock} facility
  309. * should be used instead.
  310. *
  311. * @param f
  312. * the file to be created
  313. * @throws IOException
  314. * if the named file already exists or if an I/O error occurred
  315. */
  316. public static void createNewFile(File f) throws IOException {
  317. if (!f.createNewFile())
  318. throw new IOException(MessageFormat.format(
  319. JGitText.get().createNewFileFailed, f));
  320. }
  321. /**
  322. * Create a symbolic link
  323. *
  324. * @param path
  325. * @param target
  326. * @throws IOException
  327. * @since 3.0
  328. */
  329. public static void createSymLink(File path, String target)
  330. throws IOException {
  331. FS.DETECTED.createSymLink(path, target);
  332. }
  333. /**
  334. * @param path
  335. * @return the target of the symbolic link, or null if it is not a symbolic
  336. * link
  337. * @throws IOException
  338. * @since 3.0
  339. */
  340. public static String readSymLink(File path) throws IOException {
  341. return FS.DETECTED.readSymLink(path);
  342. }
  343. /**
  344. * Create a temporary directory.
  345. *
  346. * @param prefix
  347. * @param suffix
  348. * @param dir
  349. * The parent dir, can be null to use system default temp dir.
  350. * @return the temp dir created.
  351. * @throws IOException
  352. * @since 3.4
  353. */
  354. public static File createTempDir(String prefix, String suffix, File dir)
  355. throws IOException {
  356. final int RETRIES = 1; // When something bad happens, retry once.
  357. for (int i = 0; i < RETRIES; i++) {
  358. File tmp = File.createTempFile(prefix, suffix, dir);
  359. if (!tmp.delete())
  360. continue;
  361. if (!tmp.mkdir())
  362. continue;
  363. return tmp;
  364. }
  365. throw new IOException(JGitText.get().cannotCreateTempDir);
  366. }
  367. /**
  368. * This will try and make a given path relative to another.
  369. * <p>
  370. * For example, if this is called with the two following paths :
  371. *
  372. * <pre>
  373. * <code>base = "c:\\Users\\jdoe\\eclipse\\git\\project"</code>
  374. * <code>other = "c:\\Users\\jdoe\\eclipse\\git\\another_project\\pom.xml"</code>
  375. * </pre>
  376. *
  377. * This will return "..\\another_project\\pom.xml".
  378. * </p>
  379. * <p>
  380. * This method uses {@link File#separator} to split the paths into segments.
  381. * </p>
  382. * <p>
  383. * <b>Note</b> that this will return the empty String if <code>base</code>
  384. * and <code>other</code> are equal.
  385. * </p>
  386. *
  387. * @param base
  388. * The path against which <code>other</code> should be
  389. * relativized. This will be assumed to denote the path to a
  390. * folder and not a file.
  391. * @param other
  392. * The path that will be made relative to <code>base</code>.
  393. * @return A relative path that, when resolved against <code>base</code>,
  394. * will yield the original <code>other</code>.
  395. * @since 3.7
  396. */
  397. public static String relativize(String base, String other) {
  398. if (base.equals(other))
  399. return ""; //$NON-NLS-1$
  400. final boolean ignoreCase = !FS.DETECTED.isCaseSensitive();
  401. final String[] baseSegments = base.split(Pattern.quote(File.separator));
  402. final String[] otherSegments = other.split(Pattern
  403. .quote(File.separator));
  404. int commonPrefix = 0;
  405. while (commonPrefix < baseSegments.length
  406. && commonPrefix < otherSegments.length) {
  407. if (ignoreCase
  408. && baseSegments[commonPrefix]
  409. .equalsIgnoreCase(otherSegments[commonPrefix]))
  410. commonPrefix++;
  411. else if (!ignoreCase
  412. && baseSegments[commonPrefix]
  413. .equals(otherSegments[commonPrefix]))
  414. commonPrefix++;
  415. else
  416. break;
  417. }
  418. final StringBuilder builder = new StringBuilder();
  419. for (int i = commonPrefix; i < baseSegments.length; i++)
  420. builder.append("..").append(File.separator); //$NON-NLS-1$
  421. for (int i = commonPrefix; i < otherSegments.length; i++) {
  422. builder.append(otherSegments[i]);
  423. if (i < otherSegments.length - 1)
  424. builder.append(File.separator);
  425. }
  426. return builder.toString();
  427. }
  428. }