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.

Sync.java 14 kB

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