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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 org.eclipse.jgit.internal.JGitText;
  53. /**
  54. * File Utilities
  55. */
  56. public class FileUtils {
  57. /**
  58. * Option to delete given {@code File}
  59. */
  60. public static final int NONE = 0;
  61. /**
  62. * Option to recursively delete given {@code File}
  63. */
  64. public static final int RECURSIVE = 1;
  65. /**
  66. * Option to retry deletion if not successful
  67. */
  68. public static final int RETRY = 2;
  69. /**
  70. * Option to skip deletion if file doesn't exist
  71. */
  72. public static final int SKIP_MISSING = 4;
  73. /**
  74. * Option not to throw exceptions when a deletion finally doesn't succeed.
  75. * @since 2.0
  76. */
  77. public static final int IGNORE_ERRORS = 8;
  78. /**
  79. * Option to only delete empty directories. This option can be combined with
  80. * {@link #RECURSIVE}
  81. *
  82. * @since 3.0
  83. */
  84. public static final int EMPTY_DIRECTORIES_ONLY = 16;
  85. /**
  86. * Delete file or empty folder
  87. *
  88. * @param f
  89. * {@code File} to be deleted
  90. * @throws IOException
  91. * if deletion of {@code f} fails. This may occur if {@code f}
  92. * didn't exist when the method was called. This can therefore
  93. * cause IOExceptions during race conditions when multiple
  94. * concurrent threads all try to delete the same file.
  95. */
  96. public static void delete(final File f) throws IOException {
  97. delete(f, NONE);
  98. }
  99. /**
  100. * Delete file or folder
  101. *
  102. * @param f
  103. * {@code File} to be deleted
  104. * @param options
  105. * deletion options, {@code RECURSIVE} for recursive deletion of
  106. * a subtree, {@code RETRY} to retry when deletion failed.
  107. * Retrying may help if the underlying file system doesn't allow
  108. * deletion of files being read by another thread.
  109. * @throws IOException
  110. * if deletion of {@code f} fails. This may occur if {@code f}
  111. * didn't exist when the method was called. This can therefore
  112. * cause IOExceptions during race conditions when multiple
  113. * concurrent threads all try to delete the same file. This
  114. * exception is not thrown when IGNORE_ERRORS is set.
  115. */
  116. public static void delete(final File f, int options) throws IOException {
  117. FS fs = FS.DETECTED;
  118. if ((options & SKIP_MISSING) != 0 && !fs.exists(f))
  119. return;
  120. if ((options & RECURSIVE) != 0 && fs.isDirectory(f)) {
  121. final File[] items = f.listFiles();
  122. if (items != null) {
  123. List<File> files = new ArrayList<File>();
  124. List<File> dirs = new ArrayList<File>();
  125. for (File c : items)
  126. if (c.isFile())
  127. files.add(c);
  128. else
  129. dirs.add(c);
  130. // Try to delete files first, otherwise options
  131. // EMPTY_DIRECTORIES_ONLY|RECURSIVE will delete empty
  132. // directories before aborting, depending on order.
  133. for (File file : files)
  134. delete(file, options);
  135. for (File d : dirs)
  136. delete(d, options);
  137. }
  138. }
  139. boolean delete = false;
  140. if ((options & EMPTY_DIRECTORIES_ONLY) != 0) {
  141. if (f.isDirectory()) {
  142. delete = true;
  143. } else {
  144. if ((options & IGNORE_ERRORS) == 0)
  145. throw new IOException(MessageFormat.format(
  146. JGitText.get().deleteFileFailed,
  147. f.getAbsolutePath()));
  148. }
  149. } else {
  150. delete = true;
  151. }
  152. if (delete && !f.delete()) {
  153. if ((options & RETRY) != 0 && fs.exists(f)) {
  154. for (int i = 1; i < 10; i++) {
  155. try {
  156. Thread.sleep(100);
  157. } catch (InterruptedException e) {
  158. // ignore
  159. }
  160. if (f.delete())
  161. return;
  162. }
  163. }
  164. if ((options & IGNORE_ERRORS) == 0)
  165. throw new IOException(MessageFormat.format(
  166. JGitText.get().deleteFileFailed, f.getAbsolutePath()));
  167. }
  168. }
  169. /**
  170. * Rename a file or folder. If the rename fails and if we are running on a
  171. * filesystem where it makes sense to repeat a failing rename then repeat
  172. * the rename operation up to 9 times with 100ms sleep time between two
  173. * calls. Furthermore if the destination exists and is directory hierarchy
  174. * with only directories in it, the whole directory hierarchy will be
  175. * deleted. If the target represents a non-empty directory structure, empty
  176. * subdirectories within that structure may or may not be deleted even if
  177. * the method fails. Furthermore if the destination exists and is a file
  178. * then the file will be deleted and then the rename is retried.
  179. * <p>
  180. * This operation is <em>not</em> atomic.
  181. *
  182. * @see FS#retryFailedLockFileCommit()
  183. * @param src
  184. * the old {@code File}
  185. * @param dst
  186. * the new {@code File}
  187. * @throws IOException
  188. * if the rename has failed
  189. * @since 3.0
  190. */
  191. public static void rename(final File src, final File dst)
  192. throws IOException {
  193. int attempts = FS.DETECTED.retryFailedLockFileCommit() ? 10 : 1;
  194. while (--attempts >= 0) {
  195. if (src.renameTo(dst))
  196. return;
  197. try {
  198. if (!dst.delete())
  199. delete(dst, EMPTY_DIRECTORIES_ONLY | RECURSIVE);
  200. // On *nix there is no try, you do or do not
  201. if (src.renameTo(dst))
  202. return;
  203. } catch (IOException e) {
  204. // ignore and continue retry
  205. }
  206. try {
  207. Thread.sleep(100);
  208. } catch (InterruptedException e) {
  209. throw new IOException(MessageFormat.format(
  210. JGitText.get().renameFileFailed, src.getAbsolutePath(),
  211. dst.getAbsolutePath()));
  212. }
  213. }
  214. throw new IOException(MessageFormat.format(
  215. JGitText.get().renameFileFailed, src.getAbsolutePath(),
  216. dst.getAbsolutePath()));
  217. }
  218. /**
  219. * Creates the directory named by this abstract pathname.
  220. *
  221. * @param d
  222. * directory to be created
  223. * @throws IOException
  224. * if creation of {@code d} fails. This may occur if {@code d}
  225. * did exist when the method was called. This can therefore
  226. * cause IOExceptions during race conditions when multiple
  227. * concurrent threads all try to create the same directory.
  228. */
  229. public static void mkdir(final File d)
  230. throws IOException {
  231. mkdir(d, false);
  232. }
  233. /**
  234. * Creates the directory named by this abstract pathname.
  235. *
  236. * @param d
  237. * directory to be created
  238. * @param skipExisting
  239. * if {@code true} skip creation of the given directory if it
  240. * already exists in the file system
  241. * @throws IOException
  242. * if creation of {@code d} fails. This may occur if {@code d}
  243. * did exist when the method was called. This can therefore
  244. * cause IOExceptions during race conditions when multiple
  245. * concurrent threads all try to create the same directory.
  246. */
  247. public static void mkdir(final File d, boolean skipExisting)
  248. throws IOException {
  249. if (!d.mkdir()) {
  250. if (skipExisting && d.isDirectory())
  251. return;
  252. throw new IOException(MessageFormat.format(
  253. JGitText.get().mkDirFailed, d.getAbsolutePath()));
  254. }
  255. }
  256. /**
  257. * Creates the directory named by this abstract pathname, including any
  258. * necessary but nonexistent parent directories. Note that if this operation
  259. * fails it may have succeeded in creating some of the necessary parent
  260. * directories.
  261. *
  262. * @param d
  263. * directory to be created
  264. * @throws IOException
  265. * if creation of {@code d} fails. This may occur if {@code d}
  266. * did exist when the method was called. This can therefore
  267. * cause IOExceptions during race conditions when multiple
  268. * concurrent threads all try to create the same directory.
  269. */
  270. public static void mkdirs(final File d) throws IOException {
  271. mkdirs(d, false);
  272. }
  273. /**
  274. * Creates the directory named by this abstract pathname, including any
  275. * necessary but nonexistent parent directories. Note that if this operation
  276. * fails it may have succeeded in creating some of the necessary parent
  277. * directories.
  278. *
  279. * @param d
  280. * directory to be created
  281. * @param skipExisting
  282. * if {@code true} skip creation of the given directory if it
  283. * already exists in the file system
  284. * @throws IOException
  285. * if creation of {@code d} fails. This may occur if {@code d}
  286. * did exist when the method was called. This can therefore
  287. * cause IOExceptions during race conditions when multiple
  288. * concurrent threads all try to create the same directory.
  289. */
  290. public static void mkdirs(final File d, boolean skipExisting)
  291. throws IOException {
  292. if (!d.mkdirs()) {
  293. if (skipExisting && d.isDirectory())
  294. return;
  295. throw new IOException(MessageFormat.format(
  296. JGitText.get().mkDirsFailed, d.getAbsolutePath()));
  297. }
  298. }
  299. /**
  300. * Atomically creates a new, empty file named by this abstract pathname if
  301. * and only if a file with this name does not yet exist. The check for the
  302. * existence of the file and the creation of the file if it does not exist
  303. * are a single operation that is atomic with respect to all other
  304. * filesystem activities that might affect the file.
  305. * <p>
  306. * Note: this method should not be used for file-locking, as the resulting
  307. * protocol cannot be made to work reliably. The {@link FileLock} facility
  308. * should be used instead.
  309. *
  310. * @param f
  311. * the file to be created
  312. * @throws IOException
  313. * if the named file already exists or if an I/O error occurred
  314. */
  315. public static void createNewFile(File f) throws IOException {
  316. if (!f.createNewFile())
  317. throw new IOException(MessageFormat.format(
  318. JGitText.get().createNewFileFailed, f));
  319. }
  320. /**
  321. * Create a symbolic link
  322. *
  323. * @param path
  324. * @param target
  325. * @throws IOException
  326. * @since 3.0
  327. */
  328. public static void createSymLink(File path, String target)
  329. throws IOException {
  330. FS.DETECTED.createSymLink(path, target);
  331. }
  332. /**
  333. * @param path
  334. * @return the target of the symbolic link, or null if it is not a symbolic
  335. * link
  336. * @throws IOException
  337. * @since 3.0
  338. */
  339. public static String readSymLink(File path) throws IOException {
  340. return FS.DETECTED.readSymLink(path);
  341. }
  342. }