//----------------------------------------------------------------------- // // Copyright (c) Outercurve Foundation. All rights reserved. // //----------------------------------------------------------------------- namespace DotNetOpenAuth.BuildTasks { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; /// /// Purges directory trees of all directories and files that are not on a whitelist. /// /// /// This task performs a function similar to robocopy's /MIR switch, except that /// this task does not require that an entire directory tree be used as the source /// in order to purge old files from the destination. /// public class Purge : Task { /// /// Initializes a new instance of the class. /// public Purge() { this.PurgeEmptyDirectories = true; } /// /// Gets or sets the root directories to purge. /// /// The directories. [Required] public string[] Directories { get; set; } /// /// Gets or sets the files that should be NOT be purged. /// [Required] public ITaskItem[] IntendedFiles { get; set; } /// /// Gets or sets a value indicating whether empty directories will be deleted. /// /// /// The default value is true. /// public bool PurgeEmptyDirectories { get; set; } /// /// Executes this instance. /// public override bool Execute() { HashSet intendedFiles = new HashSet(this.IntendedFiles.Select(file => file.GetMetadata("FullPath")), StringComparer.OrdinalIgnoreCase); foreach (string directory in this.Directories.Select(dir => NormalizePath(dir)).Where(dir => Directory.Exists(dir))) { foreach (string existingFile in Directory.GetFiles(directory, "*", SearchOption.AllDirectories)) { if (!intendedFiles.Contains(existingFile)) { this.Log.LogWarning("Purging file \"{0}\".", existingFile); File.Delete(existingFile); } } if (this.PurgeEmptyDirectories) { foreach (string subdirectory in Directory.GetDirectories(directory, "*", SearchOption.AllDirectories)) { // We have to check for the existance of the directory because it MAY be // a descendent of a directory we already deleted in this loop. if (Directory.Exists(subdirectory)) { if (Directory.GetDirectories(subdirectory).Length == 0 && Directory.GetFiles(subdirectory).Length == 0) { this.Log.LogWarning("Purging empty directory \"{0}\".", subdirectory); Directory.Delete(subdirectory); } } } } } return !this.Log.HasLoggedErrors; } private static string NormalizePath(string path) { return Path.GetFullPath(Regex.Replace(path, @"\\+", @"\")); } } }