1. /*
  2. * Copyright 2000-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.taskdefs;
  18. import java.io.File;
  19. import java.util.Vector;
  20. import org.apache.tools.ant.BuildException;
  21. import org.apache.tools.ant.DirectoryScanner;
  22. import org.apache.tools.ant.Project;
  23. import org.apache.tools.ant.taskdefs.condition.Os;
  24. import org.apache.tools.ant.types.FileSet;
  25. import org.apache.tools.ant.types.PatternSet;
  26. import org.apache.tools.ant.types.selectors.AndSelector;
  27. import org.apache.tools.ant.types.selectors.ContainsRegexpSelector;
  28. import org.apache.tools.ant.types.selectors.ContainsSelector;
  29. import org.apache.tools.ant.types.selectors.DateSelector;
  30. import org.apache.tools.ant.types.selectors.DependSelector;
  31. import org.apache.tools.ant.types.selectors.DepthSelector;
  32. import org.apache.tools.ant.types.selectors.ExtendSelector;
  33. import org.apache.tools.ant.types.selectors.FilenameSelector;
  34. import org.apache.tools.ant.types.selectors.MajoritySelector;
  35. import org.apache.tools.ant.types.selectors.NoneSelector;
  36. import org.apache.tools.ant.types.selectors.NotSelector;
  37. import org.apache.tools.ant.types.selectors.OrSelector;
  38. import org.apache.tools.ant.types.selectors.PresentSelector;
  39. import org.apache.tools.ant.types.selectors.SelectSelector;
  40. import org.apache.tools.ant.types.selectors.SizeSelector;
  41. import org.apache.tools.ant.types.selectors.FileSelector;
  42. import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector;
  43. /**
  44. * Deletes a file or directory, or set of files defined by a fileset.
  45. * The original delete task would delete a file, or a set of files
  46. * using the include/exclude syntax. The deltree task would delete a
  47. * directory tree. This task combines the functionality of these two
  48. * originally distinct tasks.
  49. * <p>Currently Delete extends MatchingTask. This is intend <i>only</i>
  50. * to provide backwards compatibility for a release. The future position
  51. * is to use nested filesets exclusively.</p>
  52. *
  53. * @since Ant 1.2
  54. *
  55. * @ant.task category="filesystem"
  56. */
  57. public class Delete extends MatchingTask {
  58. private static final int DELETE_RETRY_SLEEP_MILLIS = 10;
  59. protected File file = null;
  60. protected File dir = null;
  61. protected Vector filesets = new Vector();
  62. protected boolean usedMatchingTask = false;
  63. // by default, remove matching empty dirs
  64. protected boolean includeEmpty = false;
  65. private int verbosity = Project.MSG_VERBOSE;
  66. private boolean quiet = false;
  67. private boolean failonerror = true;
  68. private boolean deleteOnExit = false;
  69. /**
  70. * Set the name of a single file to be removed.
  71. *
  72. * @param file the file to be deleted
  73. */
  74. public void setFile(File file) {
  75. this.file = file;
  76. }
  77. /**
  78. * Set the directory from which files are to be deleted
  79. *
  80. * @param dir the directory path.
  81. */
  82. public void setDir(File dir) {
  83. this.dir = dir;
  84. }
  85. /**
  86. * If true, list all names of deleted files.
  87. *
  88. * @param verbose "true" or "on"
  89. */
  90. public void setVerbose(boolean verbose) {
  91. if (verbose) {
  92. this.verbosity = Project.MSG_INFO;
  93. } else {
  94. this.verbosity = Project.MSG_VERBOSE;
  95. }
  96. }
  97. /**
  98. * If true and the file does not exist, do not display a diagnostic
  99. * message or modify the exit status to reflect an error.
  100. * This means that if a file or directory cannot be deleted,
  101. * then no error is reported. This setting emulates the
  102. * -f option to the Unix "rm" command.
  103. * Default is false meaning things are "noisy"
  104. * @param quiet "true" or "on"
  105. */
  106. public void setQuiet(boolean quiet) {
  107. this.quiet = quiet;
  108. if (quiet) {
  109. this.failonerror = false;
  110. }
  111. }
  112. /**
  113. * If false, note errors but continue.
  114. *
  115. * @param failonerror true or false
  116. */
  117. public void setFailOnError(boolean failonerror) {
  118. this.failonerror = failonerror;
  119. }
  120. /**
  121. * If true, on failure to delete, note the error and set
  122. * the deleteonexit flag, and continue
  123. *
  124. * @param deleteOnExit true or false
  125. */
  126. public void setDeleteOnExit(boolean deleteOnExit) {
  127. this.deleteOnExit = deleteOnExit;
  128. }
  129. /**
  130. * If true, delete empty directories.
  131. * @param includeEmpty if true delete empty directories (only
  132. * for filesets). Default is false.
  133. */
  134. public void setIncludeEmptyDirs(boolean includeEmpty) {
  135. this.includeEmpty = includeEmpty;
  136. }
  137. /**
  138. * Adds a set of files to be deleted.
  139. * @param set the set of files to be deleted
  140. */
  141. public void addFileset(FileSet set) {
  142. filesets.addElement(set);
  143. }
  144. /**
  145. * add a name entry on the include list
  146. * @return a NameEntry object to be configured
  147. */
  148. public PatternSet.NameEntry createInclude() {
  149. usedMatchingTask = true;
  150. return super.createInclude();
  151. }
  152. /**
  153. * add a name entry on the include files list
  154. * @return an NameEntry object to be configured
  155. */
  156. public PatternSet.NameEntry createIncludesFile() {
  157. usedMatchingTask = true;
  158. return super.createIncludesFile();
  159. }
  160. /**
  161. * add a name entry on the exclude list
  162. * @return an NameEntry object to be configured
  163. */
  164. public PatternSet.NameEntry createExclude() {
  165. usedMatchingTask = true;
  166. return super.createExclude();
  167. }
  168. /**
  169. * add a name entry on the include files list
  170. * @return an NameEntry object to be configured
  171. */
  172. public PatternSet.NameEntry createExcludesFile() {
  173. usedMatchingTask = true;
  174. return super.createExcludesFile();
  175. }
  176. /**
  177. * add a set of patterns
  178. * @return PatternSet object to be configured
  179. */
  180. public PatternSet createPatternSet() {
  181. usedMatchingTask = true;
  182. return super.createPatternSet();
  183. }
  184. /**
  185. * Sets the set of include patterns. Patterns may be separated by a comma
  186. * or a space.
  187. *
  188. * @param includes the string containing the include patterns
  189. */
  190. public void setIncludes(String includes) {
  191. usedMatchingTask = true;
  192. super.setIncludes(includes);
  193. }
  194. /**
  195. * Sets the set of exclude patterns. Patterns may be separated by a comma
  196. * or a space.
  197. *
  198. * @param excludes the string containing the exclude patterns
  199. */
  200. public void setExcludes(String excludes) {
  201. usedMatchingTask = true;
  202. super.setExcludes(excludes);
  203. }
  204. /**
  205. * Sets whether default exclusions should be used or not.
  206. *
  207. * @param useDefaultExcludes "true"|"on"|"yes" when default exclusions
  208. * should be used, "false"|"off"|"no" when they
  209. * shouldn't be used.
  210. */
  211. public void setDefaultexcludes(boolean useDefaultExcludes) {
  212. usedMatchingTask = true;
  213. super.setDefaultexcludes(useDefaultExcludes);
  214. }
  215. /**
  216. * Sets the name of the file containing the includes patterns.
  217. *
  218. * @param includesfile A string containing the filename to fetch
  219. * the include patterns from.
  220. */
  221. public void setIncludesfile(File includesfile) {
  222. usedMatchingTask = true;
  223. super.setIncludesfile(includesfile);
  224. }
  225. /**
  226. * Sets the name of the file containing the includes patterns.
  227. *
  228. * @param excludesfile A string containing the filename to fetch
  229. * the include patterns from.
  230. */
  231. public void setExcludesfile(File excludesfile) {
  232. usedMatchingTask = true;
  233. super.setExcludesfile(excludesfile);
  234. }
  235. /**
  236. * Sets case sensitivity of the file system
  237. *
  238. * @param isCaseSensitive "true"|"on"|"yes" if file system is case
  239. * sensitive, "false"|"off"|"no" when not.
  240. */
  241. public void setCaseSensitive(boolean isCaseSensitive) {
  242. usedMatchingTask = true;
  243. super.setCaseSensitive(isCaseSensitive);
  244. }
  245. /**
  246. * Sets whether or not symbolic links should be followed.
  247. *
  248. * @param followSymlinks whether or not symbolic links should be followed
  249. */
  250. public void setFollowSymlinks(boolean followSymlinks) {
  251. usedMatchingTask = true;
  252. super.setFollowSymlinks(followSymlinks);
  253. }
  254. /**
  255. * add a "Select" selector entry on the selector list
  256. * @param selector the selector to be added
  257. */
  258. public void addSelector(SelectSelector selector) {
  259. usedMatchingTask = true;
  260. super.addSelector(selector);
  261. }
  262. /**
  263. * add an "And" selector entry on the selector list
  264. * @param selector the selector to be added
  265. */
  266. public void addAnd(AndSelector selector) {
  267. usedMatchingTask = true;
  268. super.addAnd(selector);
  269. }
  270. /**
  271. * add an "Or" selector entry on the selector list
  272. * @param selector the selector to be added
  273. */
  274. public void addOr(OrSelector selector) {
  275. usedMatchingTask = true;
  276. super.addOr(selector);
  277. }
  278. /**
  279. * add a "Not" selector entry on the selector list
  280. * @param selector the selector to be added
  281. */
  282. public void addNot(NotSelector selector) {
  283. usedMatchingTask = true;
  284. super.addNot(selector);
  285. }
  286. /**
  287. * add a "None" selector entry on the selector list
  288. * @param selector the selector to be added
  289. */
  290. public void addNone(NoneSelector selector) {
  291. usedMatchingTask = true;
  292. super.addNone(selector);
  293. }
  294. /**
  295. * add a majority selector entry on the selector list
  296. * @param selector the selector to be added
  297. */
  298. public void addMajority(MajoritySelector selector) {
  299. usedMatchingTask = true;
  300. super.addMajority(selector);
  301. }
  302. /**
  303. * add a selector date entry on the selector list
  304. * @param selector the selector to be added
  305. */
  306. public void addDate(DateSelector selector) {
  307. usedMatchingTask = true;
  308. super.addDate(selector);
  309. }
  310. /**
  311. * add a selector size entry on the selector list
  312. * @param selector the selector to be added
  313. */
  314. public void addSize(SizeSelector selector) {
  315. usedMatchingTask = true;
  316. super.addSize(selector);
  317. }
  318. /**
  319. * add a selector filename entry on the selector list
  320. * @param selector the selector to be added
  321. */
  322. public void addFilename(FilenameSelector selector) {
  323. usedMatchingTask = true;
  324. super.addFilename(selector);
  325. }
  326. /**
  327. * add an extended selector entry on the selector list
  328. * @param selector the selector to be added
  329. */
  330. public void addCustom(ExtendSelector selector) {
  331. usedMatchingTask = true;
  332. super.addCustom(selector);
  333. }
  334. /**
  335. * add a contains selector entry on the selector list
  336. * @param selector the selector to be added
  337. */
  338. public void addContains(ContainsSelector selector) {
  339. usedMatchingTask = true;
  340. super.addContains(selector);
  341. }
  342. /**
  343. * add a present selector entry on the selector list
  344. * @param selector the selector to be added
  345. */
  346. public void addPresent(PresentSelector selector) {
  347. usedMatchingTask = true;
  348. super.addPresent(selector);
  349. }
  350. /**
  351. * add a depth selector entry on the selector list
  352. * @param selector the selector to be added
  353. */
  354. public void addDepth(DepthSelector selector) {
  355. usedMatchingTask = true;
  356. super.addDepth(selector);
  357. }
  358. /**
  359. * add a depends selector entry on the selector list
  360. * @param selector the selector to be added
  361. */
  362. public void addDepend(DependSelector selector) {
  363. usedMatchingTask = true;
  364. super.addDepend(selector);
  365. }
  366. /**
  367. * add a regular expression selector entry on the selector list
  368. * @param selector the selector to be added
  369. */
  370. public void addContainsRegexp(ContainsRegexpSelector selector) {
  371. usedMatchingTask = true;
  372. super.addContainsRegexp(selector);
  373. }
  374. /**
  375. * add the modified selector
  376. * @param selector the selector to add
  377. * @since ant 1.6
  378. */
  379. public void addModified(ModifiedSelector selector) {
  380. usedMatchingTask = true;
  381. super.addModified(selector);
  382. }
  383. /**
  384. * add an arbitrary selector
  385. * @param selector the selector to be added
  386. * @since Ant 1.6
  387. */
  388. public void add(FileSelector selector) {
  389. usedMatchingTask = true;
  390. super.add(selector);
  391. }
  392. /**
  393. * Delete the file(s).
  394. * @exception BuildException if an error occurs
  395. */
  396. public void execute() throws BuildException {
  397. if (usedMatchingTask) {
  398. log("DEPRECATED - Use of the implicit FileSet is deprecated. "
  399. + "Use a nested fileset element instead.");
  400. }
  401. if (file == null && dir == null && filesets.size() == 0) {
  402. throw new BuildException("At least one of the file or dir "
  403. + "attributes, or a fileset element, "
  404. + "must be set.");
  405. }
  406. if (quiet && failonerror) {
  407. throw new BuildException("quiet and failonerror cannot both be "
  408. + "set to true", getLocation());
  409. }
  410. // delete the single file
  411. if (file != null) {
  412. if (file.exists()) {
  413. if (file.isDirectory()) {
  414. log("Directory " + file.getAbsolutePath()
  415. + " cannot be removed using the file attribute. "
  416. + "Use dir instead.");
  417. } else {
  418. log("Deleting: " + file.getAbsolutePath());
  419. if (!delete(file)) {
  420. String message = "Unable to delete file "
  421. + file.getAbsolutePath();
  422. if (failonerror) {
  423. throw new BuildException(message);
  424. } else {
  425. log(message, quiet ? Project.MSG_VERBOSE
  426. : Project.MSG_WARN);
  427. }
  428. }
  429. }
  430. } else {
  431. log("Could not find file " + file.getAbsolutePath()
  432. + " to delete.",
  433. Project.MSG_VERBOSE);
  434. }
  435. }
  436. // delete the directory
  437. if (dir != null && dir.exists() && dir.isDirectory()
  438. && !usedMatchingTask) {
  439. /*
  440. If verbosity is MSG_VERBOSE, that mean we are doing
  441. regular logging (backwards as that sounds). In that
  442. case, we want to print one message about deleting the
  443. top of the directory tree. Otherwise, the removeDir
  444. method will handle messages for _all_ directories.
  445. */
  446. if (verbosity == Project.MSG_VERBOSE) {
  447. log("Deleting directory " + dir.getAbsolutePath());
  448. }
  449. removeDir(dir);
  450. }
  451. // delete the files in the filesets
  452. for (int i = 0; i < filesets.size(); i++) {
  453. FileSet fs = (FileSet) filesets.elementAt(i);
  454. try {
  455. DirectoryScanner ds = fs.getDirectoryScanner(getProject());
  456. String[] files = ds.getIncludedFiles();
  457. String[] dirs = ds.getIncludedDirectories();
  458. removeFiles(fs.getDir(getProject()), files, dirs);
  459. } catch (BuildException be) {
  460. // directory doesn't exist or is not readable
  461. if (failonerror) {
  462. throw be;
  463. } else {
  464. log(be.getMessage(),
  465. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  466. }
  467. }
  468. }
  469. // delete the files from the default fileset
  470. if (usedMatchingTask && dir != null) {
  471. try {
  472. DirectoryScanner ds = super.getDirectoryScanner(dir);
  473. String[] files = ds.getIncludedFiles();
  474. String[] dirs = ds.getIncludedDirectories();
  475. removeFiles(dir, files, dirs);
  476. } catch (BuildException be) {
  477. // directory doesn't exist or is not readable
  478. if (failonerror) {
  479. throw be;
  480. } else {
  481. log(be.getMessage(),
  482. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  483. }
  484. }
  485. }
  486. }
  487. //************************************************************************
  488. // protected and private methods
  489. //************************************************************************
  490. /**
  491. * Accommodate Windows bug encountered in both Sun and IBM JDKs.
  492. * Others possible. If the delete does not work, call System.gc(),
  493. * wait a little and try again.
  494. */
  495. private boolean delete(File f) {
  496. if (!f.delete()) {
  497. if (Os.isFamily("windows")) {
  498. System.gc();
  499. }
  500. try {
  501. Thread.sleep(DELETE_RETRY_SLEEP_MILLIS);
  502. } catch (InterruptedException ex) {
  503. // Ignore Exception
  504. }
  505. if (!f.delete()) {
  506. if (deleteOnExit) {
  507. int level = quiet ? Project.MSG_VERBOSE : Project.MSG_INFO;
  508. log("Failed to delete " + f + ", calling deleteOnExit."
  509. + " This attempts to delete the file when the ant jvm"
  510. + " has exited and might not succeed."
  511. , level);
  512. f.deleteOnExit();
  513. return true;
  514. }
  515. return false;
  516. }
  517. }
  518. return true;
  519. }
  520. /**
  521. * Delete a directory
  522. *
  523. * @param d the directory to delete
  524. */
  525. protected void removeDir(File d) {
  526. String[] list = d.list();
  527. if (list == null) {
  528. list = new String[0];
  529. }
  530. for (int i = 0; i < list.length; i++) {
  531. String s = list[i];
  532. File f = new File(d, s);
  533. if (f.isDirectory()) {
  534. removeDir(f);
  535. } else {
  536. log("Deleting " + f.getAbsolutePath(), verbosity);
  537. if (!delete(f)) {
  538. String message = "Unable to delete file "
  539. + f.getAbsolutePath();
  540. if (failonerror) {
  541. throw new BuildException(message);
  542. } else {
  543. log(message,
  544. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  545. }
  546. }
  547. }
  548. }
  549. log("Deleting directory " + d.getAbsolutePath(), verbosity);
  550. if (!delete(d)) {
  551. String message = "Unable to delete directory "
  552. + dir.getAbsolutePath();
  553. if (failonerror) {
  554. throw new BuildException(message);
  555. } else {
  556. log(message,
  557. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  558. }
  559. }
  560. }
  561. /**
  562. * remove an array of files in a directory, and a list of subdirectories
  563. * which will only be deleted if 'includeEmpty' is true
  564. * @param d directory to work from
  565. * @param files array of files to delete; can be of zero length
  566. * @param dirs array of directories to delete; can of zero length
  567. */
  568. protected void removeFiles(File d, String[] files, String[] dirs) {
  569. if (files.length > 0) {
  570. log("Deleting " + files.length + " files from "
  571. + d.getAbsolutePath());
  572. for (int j = 0; j < files.length; j++) {
  573. File f = new File(d, files[j]);
  574. log("Deleting " + f.getAbsolutePath(), verbosity);
  575. if (!delete(f)) {
  576. String message = "Unable to delete file "
  577. + f.getAbsolutePath();
  578. if (failonerror) {
  579. throw new BuildException(message);
  580. } else {
  581. log(message,
  582. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  583. }
  584. }
  585. }
  586. }
  587. if (dirs.length > 0 && includeEmpty) {
  588. int dirCount = 0;
  589. for (int j = dirs.length - 1; j >= 0; j--) {
  590. File dir = new File(d, dirs[j]);
  591. String[] dirFiles = dir.list();
  592. if (dirFiles == null || dirFiles.length == 0) {
  593. log("Deleting " + dir.getAbsolutePath(), verbosity);
  594. if (!delete(dir)) {
  595. String message = "Unable to delete directory "
  596. + dir.getAbsolutePath();
  597. if (failonerror) {
  598. throw new BuildException(message);
  599. } else {
  600. log(message,
  601. quiet ? Project.MSG_VERBOSE : Project.MSG_WARN);
  602. }
  603. } else {
  604. dirCount++;
  605. }
  606. }
  607. }
  608. if (dirCount > 0) {
  609. log("Deleted " + dirCount + " director"
  610. + (dirCount == 1 ? "y" : "ies")
  611. + " from " + d.getAbsolutePath());
  612. }
  613. }
  614. }
  615. }