Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Created January 9, 2012 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kamranayub/1583784 to your computer and use it in GitHub Desktop.
Save kamranayub/1583784 to your computer and use it in GitHub Desktop.
Cassette ExcludeDirectorySearch
/// <summary>
/// An exclude directory search for Cassette. Provide the patterns you want to search for
/// and this will exclude *.min/*-vsdoc files as well as the directories you specify.
/// </summary>
public class ExcludeDirectorySearch : FileSearch
{
/// <summary>
/// Excludes specified directories in search (also .min and -vsdoc files)
/// </summary>
/// <param name="pattern">File search pattern (wildcards, e.g. *.css;*.less)</param>
/// <param name="directoriesToExclude">A string array of folder names to exclude. Will match anywhere in full file path.</param>
public ExcludeDirectorySearch(string pattern, string[] directoriesToExclude)
{
SearchOption = SearchOption.AllDirectories;
Pattern = pattern;
ExcludeDirectories = directoriesToExclude;
}
private string[] ExcludeDirectories
{
set
{
// Join with rx | (or)
var directories = String.Join("|", value);
// Extensions "*.js;*.coffee" => "js", "coffee"
// Assumes you're using wildcard... but whatever.
var extensions = String.Join("|", Pattern.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries).
Select(s => s.Substring(2)).ToArray());
var excludeRegex =
new Regex(String.Format(@"(
{0} # Directory exclusions
)[\\/]|([\.-](
vsdoc | # Vsdoc files
min # Minified files
)\.({1})$)", directories, extensions), RegexOptions.IgnorePatternWhitespace);
// Set exclusions
Exclude = excludeRegex;
}
}
}
@kamranayub
Copy link
Author

This is very limited in scope; it'll break if directories have special Regex characters and it's probably not efficient (especially if the search is called more than once). TODO is to refactor into a real IFileSearch implementation that intelligently excludes directories and file suffixes.

@voithos
Copy link

voithos commented Sep 12, 2012

I needed precisely this kind of IFileSearch implementation, so I basically wrote an augmented variant of the standard FileSearch, including directory exclusion, without having to rely on a single Regex. It isn't very elegant currently (as it duplicates most of the code from FileSearch), but it seems to work decently. If there's a good way to isolate it out and get some code reuse, I'd be glad to hear about it.

@damonbauer
Copy link

Thanks for this. In order to get it to work, I had to add using System.IO; in order to get SearchOption = SearchOption.AllDirectories; to work properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment