You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Delete.java 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2000 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowlegement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowlegement may appear in the software itself,
  24. * if and wherever such third-party acknowlegements normally appear.
  25. *
  26. * 4. The names "The Jakarta Project", "Ant", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Group.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.tools.ant.taskdefs;
  55. import org.apache.tools.ant.Project;
  56. import org.apache.tools.ant.BuildException;
  57. import org.apache.tools.ant.DirectoryScanner;
  58. import org.apache.tools.ant.types.FileSet;
  59. import org.apache.tools.ant.types.PatternSet;
  60. import java.io.File;
  61. import java.util.Vector;
  62. /**
  63. * Deletes a file or directory, or set of files defined by a fileset.
  64. * The original delete task would delete a file, or a set of files
  65. * using the include/exclude syntax. The deltree task would delete a
  66. * directory tree. This task combines the functionality of these two
  67. * originally distinct tasks.
  68. * <p>Currently Delete extends MatchingTask. This is intend <i>only</i>
  69. * to provide backwards compatibility for a release. The future position
  70. * is to use nested filesets exclusively.</p>
  71. *
  72. * @author Stefano Mazzocchi <a href="mailto:stefano@apache.org">stefano@apache.org</a>
  73. * @author Tom Dimock <a href="mailto:tad1@cornell.edu">tad1@cornell.edu</a>
  74. * @author Glenn McAllister <a href="mailto:glennm@ca.ibm.com">glennm@ca.ibm.com</a>
  75. * @author Jon S. Stevens <a href="mailto:jon@latchkey.com">jon@latchkey.com</a>
  76. */
  77. public class Delete extends MatchingTask {
  78. protected File file = null;
  79. protected File dir = null;
  80. protected Vector filesets = new Vector();
  81. protected boolean usedMatchingTask = false;
  82. protected boolean includeEmpty = false; // by default, remove matching empty dirs
  83. private int verbosity = Project.MSG_VERBOSE;
  84. private boolean quiet = false;
  85. private boolean failonerror = true;
  86. /**
  87. * Set the name of a single file to be removed.
  88. *
  89. * @param file the file to be deleted
  90. */
  91. public void setFile(File file) {
  92. this.file = file;
  93. }
  94. /**
  95. * Set the directory from which files are to be deleted
  96. *
  97. * @param dir the directory path.
  98. */
  99. public void setDir(File dir) {
  100. this.dir = dir;
  101. }
  102. /**
  103. * Used to force listing of all names of deleted files.
  104. *
  105. * @param verbose "true" or "on"
  106. */
  107. public void setVerbose(boolean verbose) {
  108. if (verbose) {
  109. this.verbosity = Project.MSG_INFO;
  110. } else {
  111. this.verbosity = Project.MSG_VERBOSE;
  112. }
  113. }
  114. /**
  115. * If the file does not exist, do not display a diagnostic
  116. * message or modify the exit status to reflect an error.
  117. * This means that if a file or directory cannot be deleted,
  118. * then no error is reported. This setting emulates the
  119. * -f option to the Unix &quot;rm&quot; command.
  120. * Default is false meaning things are &quot;noisy&quot;
  121. * @param quiet "true" or "on"
  122. */
  123. public void setQuiet(boolean quiet) {
  124. this.quiet = quiet;
  125. if (quiet) {
  126. this.failonerror = false;
  127. }
  128. }
  129. /**
  130. * this flag means 'note errors to the output, but keep going'
  131. * @param failonerror true or false
  132. */
  133. public void setFailOnError(boolean failonerror) {
  134. this.failonerror=failonerror;
  135. }
  136. /**
  137. * Used to delete empty directories.
  138. */
  139. public void setIncludeEmptyDirs(boolean includeEmpty) {
  140. this.includeEmpty = includeEmpty;
  141. }
  142. /**
  143. * Adds a set of files (nested fileset attribute).
  144. */
  145. public void addFileset(FileSet set) {
  146. filesets.addElement(set);
  147. }
  148. /**
  149. * add a name entry on the include list
  150. */
  151. public PatternSet.NameEntry createInclude() {
  152. usedMatchingTask = true;
  153. return super.createInclude();
  154. }
  155. /**
  156. * add a name entry on the exclude list
  157. */
  158. public PatternSet.NameEntry createExclude() {
  159. usedMatchingTask = true;
  160. return super.createExclude();
  161. }
  162. /**
  163. * add a set of patterns
  164. */
  165. public PatternSet createPatternSet() {
  166. usedMatchingTask = true;
  167. return super.createPatternSet();
  168. }
  169. /**
  170. * Sets the set of include patterns. Patterns may be separated by a comma
  171. * or a space.
  172. *
  173. * @param includes the string containing the include patterns
  174. */
  175. public void setIncludes(String includes) {
  176. usedMatchingTask = true;
  177. super.setIncludes(includes);
  178. }
  179. /**
  180. * Sets the set of exclude patterns. Patterns may be separated by a comma
  181. * or a space.
  182. *
  183. * @param excludes the string containing the exclude patterns
  184. */
  185. public void setExcludes(String excludes) {
  186. usedMatchingTask = true;
  187. super.setExcludes(excludes);
  188. }
  189. /**
  190. * Sets whether default exclusions should be used or not.
  191. *
  192. * @param useDefaultExcludes "true"|"on"|"yes" when default exclusions
  193. * should be used, "false"|"off"|"no" when they
  194. * shouldn't be used.
  195. */
  196. public void setDefaultexcludes(boolean useDefaultExcludes) {
  197. usedMatchingTask = true;
  198. super.setDefaultexcludes(useDefaultExcludes);
  199. }
  200. /**
  201. * Sets the name of the file containing the includes patterns.
  202. *
  203. * @param includesfile A string containing the filename to fetch
  204. * the include patterns from.
  205. */
  206. public void setIncludesfile(File includesfile) {
  207. usedMatchingTask = true;
  208. super.setIncludesfile(includesfile);
  209. }
  210. /**
  211. * Sets the name of the file containing the includes patterns.
  212. *
  213. * @param excludesfile A string containing the filename to fetch
  214. * the include patterns from.
  215. */
  216. public void setExcludesfile(File excludesfile) {
  217. usedMatchingTask = true;
  218. super.setExcludesfile(excludesfile);
  219. }
  220. /**
  221. * Delete the file(s).
  222. */
  223. public void execute() throws BuildException {
  224. if (usedMatchingTask) {
  225. log("DEPRECATED - Use of the implicit FileSet is deprecated. Use a nested fileset element instead.");
  226. }
  227. if (file == null && dir == null && filesets.size() == 0) {
  228. throw new BuildException("At least one of the file or dir attributes, or a fileset element, must be set.");
  229. }
  230. if (quiet && failonerror) {
  231. throw new BuildException("quiet and failonerror cannot both be set to true",
  232. location);
  233. }
  234. // delete the single file
  235. if (file != null) {
  236. if (file.exists()) {
  237. if (file.isDirectory()) {
  238. log("Directory " + file.getAbsolutePath() + " cannot be removed using the file attribute. Use dir instead.");
  239. } else {
  240. log("Deleting: " + file.getAbsolutePath());
  241. if (!file.delete()) {
  242. String message="Unable to delete file " + file.getAbsolutePath();
  243. if(failonerror)
  244. throw new BuildException(message);
  245. else
  246. log(message,
  247. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  248. }
  249. }
  250. } else {
  251. log("Could not find file " + file.getAbsolutePath() + " to delete.",
  252. Project.MSG_VERBOSE);
  253. }
  254. }
  255. // delete the directory
  256. if (dir != null && dir.exists() && dir.isDirectory() && !usedMatchingTask) {
  257. /*
  258. If verbosity is MSG_VERBOSE, that mean we are doing regular logging
  259. (backwards as that sounds). In that case, we want to print one
  260. message about deleting the top of the directory tree. Otherwise,
  261. the removeDir method will handle messages for _all_ directories.
  262. */
  263. if (verbosity == Project.MSG_VERBOSE) {
  264. log("Deleting directory " + dir.getAbsolutePath());
  265. }
  266. removeDir(dir);
  267. }
  268. // delete the files in the filesets
  269. for (int i=0; i<filesets.size(); i++) {
  270. FileSet fs = (FileSet) filesets.elementAt(i);
  271. try {
  272. DirectoryScanner ds = fs.getDirectoryScanner(project);
  273. String[] files = ds.getIncludedFiles();
  274. String[] dirs = ds.getIncludedDirectories();
  275. removeFiles(fs.getDir(project), files, dirs);
  276. } catch (BuildException be) {
  277. // directory doesn't exist or is not readable
  278. if (failonerror) {
  279. throw be;
  280. } else {
  281. log(be.getMessage(),
  282. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  283. }
  284. }
  285. }
  286. // delete the files from the default fileset
  287. if (usedMatchingTask && dir != null) {
  288. try {
  289. DirectoryScanner ds = super.getDirectoryScanner(dir);
  290. String[] files = ds.getIncludedFiles();
  291. String[] dirs = ds.getIncludedDirectories();
  292. removeFiles(dir, files, dirs);
  293. } catch (BuildException be) {
  294. // directory doesn't exist or is not readable
  295. if (failonerror) {
  296. throw be;
  297. } else {
  298. log(be.getMessage(),
  299. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  300. }
  301. }
  302. }
  303. }
  304. //************************************************************************
  305. // protected and private methods
  306. //************************************************************************
  307. protected void removeDir(File d) {
  308. String[] list = d.list();
  309. if (list == null) list = new String[0];
  310. for (int i = 0; i < list.length; i++) {
  311. String s = list[i];
  312. File f = new File(d, s);
  313. if (f.isDirectory()) {
  314. removeDir(f);
  315. } else {
  316. log("Deleting " + f.getAbsolutePath(), verbosity);
  317. if (!f.delete()) {
  318. String message="Unable to delete file " + f.getAbsolutePath();
  319. if(failonerror)
  320. throw new BuildException(message);
  321. else
  322. log(message,
  323. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  324. }
  325. }
  326. }
  327. log("Deleting directory " + d.getAbsolutePath(), verbosity);
  328. if (!d.delete()) {
  329. String message="Unable to delete directory " + dir.getAbsolutePath();
  330. if(failonerror)
  331. throw new BuildException(message);
  332. else
  333. log(message,
  334. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  335. }
  336. }
  337. /**
  338. * remove an array of files in a directory, and a list of subdirectories
  339. * which will only be deleted if 'includeEmpty' is true
  340. * @param d directory to work from
  341. * @param files array of files to delete; can be of zero length
  342. * @param dirs array of directories to delete; can of zero length
  343. */
  344. protected void removeFiles(File d, String[] files, String[] dirs) {
  345. if (files.length > 0) {
  346. log("Deleting " + files.length + " files from " + d.getAbsolutePath());
  347. for (int j=0; j<files.length; j++) {
  348. File f = new File(d, files[j]);
  349. log("Deleting " + f.getAbsolutePath(), verbosity);
  350. if (!f.delete()) {
  351. String message="Unable to delete file " + f.getAbsolutePath();
  352. if(failonerror)
  353. throw new BuildException(message);
  354. else
  355. log(message,
  356. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  357. }
  358. }
  359. }
  360. if (dirs.length > 0 && includeEmpty) {
  361. int dirCount = 0;
  362. for (int j=dirs.length-1; j>=0; j--) {
  363. File dir = new File(d, dirs[j]);
  364. String[] dirFiles = dir.list();
  365. if (dirFiles == null || dirFiles.length == 0) {
  366. log("Deleting " + dir.getAbsolutePath(), verbosity);
  367. if (!dir.delete()) {
  368. String message="Unable to delete directory "
  369. + dir.getAbsolutePath();
  370. if(failonerror)
  371. throw new BuildException(message);
  372. else
  373. log(message,
  374. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  375. } else {
  376. dirCount++;
  377. }
  378. }
  379. }
  380. if (dirCount > 0) {
  381. log("Deleted " + dirCount + " director" +
  382. (dirCount==1 ? "y" : "ies") +
  383. " from " + d.getAbsolutePath());
  384. }
  385. }
  386. }
  387. }