1. /*
  2. * Copyright 2003-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. /*
  18. * This code is based on code Copyright (c) 2002, Landmark Graphics
  19. * Corp that has been kindly donated to the Apache Software
  20. * Foundation.
  21. */
  22. package org.apache.tools.ant.taskdefs;
  23. import java.io.File;
  24. import java.util.Hashtable;
  25. import org.apache.tools.ant.BuildException;
  26. import org.apache.tools.ant.Project;
  27. import org.apache.tools.ant.Task;
  28. import org.apache.tools.ant.types.FileSet;
  29. import org.apache.tools.ant.util.FileNameMapper;
  30. import org.apache.tools.ant.util.IdentityMapper;
  31. /**
  32. * Synchronize a local target directory from the files defined
  33. * in one or more filesets.
  34. *
  35. * <p>Uses a <copy> task internally, but forbidding the use of
  36. * mappers and filter chains. Files of the destination directory not
  37. * present in any of the source fileset are removed.</p>
  38. *
  39. * @version $Revision: 1.7.2.5 $
  40. * @since Ant 1.6
  41. *
  42. * revised by <a href="mailto:daniel.armbrust@mayo.edu">Dan Armbrust</a>
  43. * to remove orphaned directories.
  44. *
  45. * @ant.task category="filesystem"
  46. */
  47. public class Sync extends Task {
  48. // Same as regular <copy> task... see at end-of-file!
  49. private MyCopy _copy;
  50. // Override Task#init
  51. public void init()
  52. throws BuildException {
  53. // Instantiate it
  54. _copy = new MyCopy();
  55. configureTask(_copy);
  56. // Default config of <mycopy> for our purposes.
  57. _copy.setFiltering(false);
  58. _copy.setIncludeEmptyDirs(false);
  59. _copy.setPreserveLastModified(true);
  60. }
  61. private void configureTask(Task helper) {
  62. helper.setProject(getProject());
  63. helper.setTaskName(getTaskName());
  64. helper.setOwningTarget(getOwningTarget());
  65. helper.init();
  66. }
  67. // Override Task#execute
  68. public void execute()
  69. throws BuildException {
  70. // The destination of the files to copy
  71. File toDir = _copy.getToDir();
  72. // The complete list of files to copy
  73. Hashtable allFiles = _copy._dest2src;
  74. // If the destination directory didn't already exist,
  75. // or was empty, then no previous file removal is necessary!
  76. boolean noRemovalNecessary = !toDir.exists() || toDir.list().length < 1;
  77. // Copy all the necessary out-of-date files
  78. log("PASS#1: Copying files to " + toDir, Project.MSG_DEBUG);
  79. _copy.execute();
  80. // Do we need to perform further processing?
  81. if (noRemovalNecessary) {
  82. log("NO removing necessary in " + toDir, Project.MSG_DEBUG);
  83. return; // nope ;-)
  84. }
  85. // Get rid of all files not listed in the source filesets.
  86. log("PASS#2: Removing orphan files from " + toDir, Project.MSG_DEBUG);
  87. int[] removedFileCount = removeOrphanFiles(allFiles, toDir);
  88. logRemovedCount(removedFileCount[0], "dangling director", "y", "ies");
  89. logRemovedCount(removedFileCount[1], "dangling file", "", "s");
  90. // Get rid of empty directories on the destination side
  91. if (!_copy.getIncludeEmptyDirs()) {
  92. log("PASS#3: Removing empty directories from " + toDir,
  93. Project.MSG_DEBUG);
  94. int removedDirCount = removeEmptyDirectories(toDir, false);
  95. logRemovedCount(removedDirCount, "empty director", "y", "ies");
  96. }
  97. }
  98. private void logRemovedCount(int count, String prefix,
  99. String singularSuffix, String pluralSuffix) {
  100. File toDir = _copy.getToDir();
  101. String what = (prefix == null) ? "" : prefix;
  102. what += (count < 2) ? singularSuffix : pluralSuffix;
  103. if (count > 0) {
  104. log("Removed " + count + " " + what + " from " + toDir,
  105. Project.MSG_INFO);
  106. } else {
  107. log("NO " + what + " to remove from " + toDir,
  108. Project.MSG_VERBOSE);
  109. }
  110. }
  111. /**
  112. * Removes all files and folders not found as keys of a table
  113. * (used as a set!).
  114. *
  115. * <p>If the provided file is a directory, it is recursively
  116. * scanned for orphaned files which will be removed as well.</p>
  117. *
  118. * <p>If the directory is an orphan, it will also be removed.</p>
  119. *
  120. * @param nonOrphans the table of all non-orphan <code>File</code>s.
  121. * @param file the initial file or directory to scan or test.
  122. * @return the number of orphaned files and directories actually removed.
  123. * Position 0 of the array is the number of orphaned directories.
  124. * Position 1 of the array is the number or orphaned files.
  125. * Position 2 is meaningless.
  126. */
  127. private int[] removeOrphanFiles(Hashtable nonOrphans, File file) {
  128. int[] removedCount = new int[] {0, 0, 0};
  129. if (file.isDirectory()) {
  130. File[] children = file.listFiles();
  131. for (int i = 0; i < children.length; ++i) {
  132. int[] temp = removeOrphanFiles(nonOrphans, children[i]);
  133. removedCount[0] += temp[0];
  134. removedCount[1] += temp[1];
  135. removedCount[2] += temp[2];
  136. }
  137. if (nonOrphans.get(file) == null && removedCount[2] == 0) {
  138. log("Removing orphan directory: " + file, Project.MSG_DEBUG);
  139. file.delete();
  140. ++removedCount[0];
  141. } else {
  142. /*
  143. Contrary to what is said above, position 2 is not
  144. meaningless inside the recursion.
  145. Position 2 is used to carry information back up the
  146. recursion about whether or not a directory contains
  147. a directory or file at any depth that is not an
  148. orphan
  149. This has to be done, because if you have the
  150. following directory structure: c:\src\a\file and
  151. your mapper src files were constructed like so:
  152. <include name="**\a\**\*"/>
  153. The folder 'a' will not be in the hashtable of
  154. nonorphans. So, before deleting it as an orphan, we
  155. have to know whether or not any of its children at
  156. any level are orphans.
  157. If no, then this folder is also an orphan, and may
  158. be deleted. I do this by changing position 2 to a
  159. '1'.
  160. */
  161. removedCount[2] = 1;
  162. }
  163. } else {
  164. if (nonOrphans.get(file) == null) {
  165. log("Removing orphan file: " + file, Project.MSG_DEBUG);
  166. file.delete();
  167. ++removedCount[1];
  168. } else {
  169. removedCount[2] = 1;
  170. }
  171. }
  172. return removedCount;
  173. }
  174. /**
  175. * Removes all empty directories from a directory.
  176. *
  177. * <p><em>Note that a directory that contains only empty
  178. * directories, directly or not, will be removed!</em></p>
  179. *
  180. * <p>Recurses depth-first to find the leaf directories
  181. * which are empty and removes them, then unwinds the
  182. * recursion stack, removing directories which have
  183. * become empty themselves, etc...</p>
  184. *
  185. * @param dir the root directory to scan for empty directories.
  186. * @param removeIfEmpty whether to remove the root directory
  187. * itself if it becomes empty.
  188. * @return the number of empty directories actually removed.
  189. */
  190. private int removeEmptyDirectories(File dir, boolean removeIfEmpty) {
  191. int removedCount = 0;
  192. if (dir.isDirectory()) {
  193. File[] children = dir.listFiles();
  194. for (int i = 0; i < children.length; ++i) {
  195. File file = children[i];
  196. // Test here again to avoid method call for non-directories!
  197. if (file.isDirectory()) {
  198. removedCount += removeEmptyDirectories(file, true);
  199. }
  200. }
  201. if (children.length > 0) {
  202. // This directory may have become empty...
  203. // We need to re-query its children list!
  204. children = dir.listFiles();
  205. }
  206. if (children.length < 1 && removeIfEmpty) {
  207. log("Removing empty directory: " + dir, Project.MSG_DEBUG);
  208. dir.delete();
  209. ++removedCount;
  210. }
  211. }
  212. return removedCount;
  213. }
  214. //
  215. // Various copy attributes/subelements of <copy> passed thru to <mycopy>
  216. //
  217. /**
  218. * Sets the destination directory.
  219. */
  220. public void setTodir(File destDir) {
  221. _copy.setTodir(destDir);
  222. }
  223. /**
  224. * Used to force listing of all names of copied files.
  225. */
  226. public void setVerbose(boolean verbose) {
  227. _copy.setVerbose(verbose);
  228. }
  229. /**
  230. * Overwrite any existing destination file(s).
  231. */
  232. public void setOverwrite(boolean overwrite) {
  233. _copy.setOverwrite(overwrite);
  234. }
  235. /**
  236. * Used to copy empty directories.
  237. */
  238. public void setIncludeEmptyDirs(boolean includeEmpty) {
  239. _copy.setIncludeEmptyDirs(includeEmpty);
  240. }
  241. /**
  242. * If false, note errors to the output but keep going.
  243. * @param failonerror true or false
  244. */
  245. public void setFailOnError(boolean failonerror) {
  246. _copy.setFailOnError(failonerror);
  247. }
  248. /**
  249. * Adds a set of files to copy.
  250. */
  251. public void addFileset(FileSet set) {
  252. _copy.addFileset(set);
  253. }
  254. /**
  255. * The number of milliseconds leeway to give before deciding a
  256. * target is out of date.
  257. *
  258. * <p>Default is 0 milliseconds, or 2 seconds on DOS systems.</p>
  259. *
  260. * @since Ant 1.6.2
  261. */
  262. public void setGranularity(long granularity) {
  263. _copy.setGranularity(granularity);
  264. }
  265. /**
  266. * Subclass Copy in order to access it's file/dir maps.
  267. */
  268. public static class MyCopy extends Copy {
  269. // List of files that must be copied, irrelevant from the
  270. // fact that they are newer or not than the destination.
  271. private Hashtable _dest2src = new Hashtable();
  272. public MyCopy() {
  273. }
  274. protected void buildMap(File fromDir, File toDir, String[] names,
  275. FileNameMapper mapper, Hashtable map) {
  276. assertTrue("No mapper", mapper instanceof IdentityMapper);
  277. super.buildMap(fromDir, toDir, names, mapper, map);
  278. for (int i = 0; i < names.length; ++i) {
  279. String name = names[i];
  280. File dest = new File(toDir, name);
  281. // No need to instantiate the src file, as we use the
  282. // table as a set (to remain Java 1.1 compatible!!!).
  283. //File src = new File(fromDir, name);
  284. //_dest2src.put(dest, src);
  285. _dest2src.put(dest, fromDir);
  286. }
  287. }
  288. public File getToDir() {
  289. return destDir;
  290. }
  291. public boolean getIncludeEmptyDirs() {
  292. return includeEmpty;
  293. }
  294. }
  295. /**
  296. * Pseudo-assert method.
  297. */
  298. private static void assertTrue(String message, boolean condition) {
  299. if (!condition) {
  300. throw new BuildException("Assertion Error: " + message);
  301. }
  302. }
  303. }