Tuesday, November 9, 2010

Quick custom build task

We needed something to delete all but the last 3 *.zip files for a particular app  in a directory during a build. This was particularly simple because of 1 assumption the files would properly sort by filename alone. This is often not the case when Dates or times are involved unless you are using fixed width, padded, or formatted date/time strings.


using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
 
namespace BMsBuildTasks
{
  public class RollingVersionCleaner:Task
  {
    [Required]
    public string Path { getset; }
    [Required]
    public string AppName { getset; }
    [Output]
    public ITaskItem[ ] Deleted { getset; }
    public override bool Execute( )
    {
      if (System.IO.Directory.Exists(Path)==false)
      {
        Log.LogError("Directory does not exist:"+Path);
        return false;
      }
      var files = System.IO.Directory.GetFiles(Path, AppName+"*.zip");
 
      var q= from f in files
             let fileName=System.IO.Path.GetFileName(f)
             orderby fileName descending
             where fileName.Contains(".")
             select f;
      if (q.Any( )==false)
      {
        Log.LogMessage("No files found "+System.IO.Path.Combine(Path, AppName));
        return true;
      }
      var toDelete=q.Skip(3);
      if (toDelete.Any( )==false)
      {
        Log.LogMessage("No files to delete "+System.IO.Path.Combine(Path, AppName));
        return true;
      }
 
      var deleted = new List<string>( );
      foreach (var item in toDelete)
      {
        System.IO.File.Delete(item);
        deleted.Add(item);
      }
      Deleted=deleted.Select(x => new TaskItem(x)).ToArray( );
      Log.LogMessage("Deleted "+deleted.Count+" file(s)");
      return true;
    }
  }
}

No comments:

Post a Comment