/* * Copyright 2003-2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * This code is based on code Copyright (c) 2002, Landmark Graphics * Corp that has been kindly donated to the Apache Software * Foundation. */ package org.apache.tools.ant.taskdefs; import java.io.File; import java.util.HashSet; import java.util.Set; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.AbstractFileSet; import org.apache.tools.ant.types.FileSet; /** * Synchronize a local target directory from the files defined * in one or more filesets. * *
Uses a <copy> task internally, but forbidding the use of * mappers and filter chains. Files of the destination directory not * present in any of the source fileset are removed.
* * @version $Revision$ * @since Ant 1.6 * * revised by Dan Armbrust * to remove orphaned directories. * * @ant.task category="filesystem" */ public class Sync extends Task { // Same as regularIf the provided file is a directory, it is recursively * scanned for orphaned files which will be removed as well.
* *If the directory is an orphan, it will also be removed.
* * @param nonOrphans the table of all non-orphanFiles.
* @param file the initial file or directory to scan or test.
* @return the number of orphaned files and directories actually removed.
* Position 0 of the array is the number of orphaned directories.
* Position 1 of the array is the number or orphaned files.
*/
private int[] removeOrphanFiles(Set nonOrphans, File toDir) {
int[] removedCount = new int[] {0, 0};
String[] excls =
(String[]) nonOrphans.toArray(new String[nonOrphans.size() + 1]);
// want to keep toDir itself
excls[nonOrphans.size()] = "";
DirectoryScanner ds = null;
if (syncTarget != null) {
syncTarget.setTargetDir(toDir);
ds = syncTarget.getDirectoryScanner(getProject());
} else {
ds = new DirectoryScanner();
ds.setBasedir(toDir);
}
ds.addExcludes(excls);
ds.scan();
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++) {
File f = new File(toDir, files[i]);
log("Removing orphan file: " + f, Project.MSG_DEBUG);
f.delete();
++removedCount[1];
}
String[] dirs = ds.getIncludedDirectories();
// ds returns the directories as it has visited them.
// iterating through the array backwards means we are deleting
// leaves before their parent nodes - thus making sure (well,
// more likely) that the directories are empty when we try to
// delete them.
for (int i = dirs.length - 1; i >= 0; --i) {
File f = new File(toDir, dirs[i]);
log("Removing orphan directory: " + f, Project.MSG_DEBUG);
f.delete();
++removedCount[0];
}
return removedCount;
}
/**
* Removes all empty directories from a directory.
*
* Note that a directory that contains only empty * directories, directly or not, will be removed!
* *Recurses depth-first to find the leaf directories * which are empty and removes them, then unwinds the * recursion stack, removing directories which have * become empty themselves, etc...
* * @param dir the root directory to scan for empty directories. * @param removeIfEmpty whether to remove the root directory * itself if it becomes empty. * @return the number of empty directories actually removed. */ private int removeEmptyDirectories(File dir, boolean removeIfEmpty) { int removedCount = 0; if (dir.isDirectory()) { File[] children = dir.listFiles(); for (int i = 0; i < children.length; ++i) { File file = children[i]; // Test here again to avoid method call for non-directories! if (file.isDirectory()) { removedCount += removeEmptyDirectories(file, true); } } if (children.length > 0) { // This directory may have become empty... // We need to re-query its children list! children = dir.listFiles(); } if (children.length < 1 && removeIfEmpty) { log("Removing empty directory: " + dir, Project.MSG_DEBUG); dir.delete(); ++removedCount; } } return removedCount; } // // Various copy attributes/subelements ofDefault is 0 milliseconds, or 2 seconds on DOS systems.
* @param granularity along value
* @since Ant 1.6.2
*/
public void setGranularity(long granularity) {
myCopy.setGranularity(granularity);
}
/**
* A container for patterns and selectors that can be used to
* specify files that should be kept in the target even if they
* are not present in any source directory.
*
* You must not invoke this method more than once.
* * @since Ant 1.7 */ public void addDeleteFromTarget(SyncTarget s) { if (syncTarget != null) { throw new BuildException("you must not specify multiple " + "deletefromtaget elements."); } syncTarget = s; } /** * Subclass Copy in order to access it's file/dir maps. */ public static class MyCopy extends Copy { // List of files that must be copied, irrelevant from the // fact that they are newer or not than the destination. private Set nonOrphans = new HashSet(); /** Constructor for MyCopy. */ public MyCopy() { } /** * @see Copy#scan(File, File, String[], String[]) */ protected void scan(File fromDir, File toDir, String[] files, String[] dirs) { assertTrue("No mapper", mapperElement == null); super.scan(fromDir, toDir, files, dirs); for (int i = 0; i < files.length; ++i) { nonOrphans.add(files[i]); } for (int i = 0; i < dirs.length; ++i) { nonOrphans.add(dirs[i]); } } /** * Get the destination directory. * @return the destination directory */ public File getToDir() { return destDir; } /** * Get the includeEmptyDirs attribute. * @return true if emptyDirs are to be included */ public boolean getIncludeEmptyDirs() { return includeEmpty; } } /** * Inner class used to hold exclude patterns and selectors to save * stuff that happens to live in the target directory but should * not get removed. * * @since Ant 1.7 */ public static class SyncTarget extends AbstractFileSet { public SyncTarget() { super(); setDefaultexcludes(false); } public void setDir(File dir) throws BuildException { throw new BuildException("synctarget doesn't support the dir " + "attribute"); } private void setTargetDir(File dir) throws BuildException { super.setDir(dir); } } /** * Pseudo-assert method. */ private static void assertTrue(String message, boolean condition) { if (!condition) { throw new BuildException("Assertion Error: " + message); } } }