Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rebased: Added support for basic glob patterns in "inputFile" #317

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/WebCompiler/Compile/SassCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ public CompilerResult Compile(Config config)
OriginalContent = content,
};

if (config.GlobalMatch && string.IsNullOrWhiteSpace(content) || Path.GetFileName(config.InputFile).StartsWith("_"))
return result;

try
{
RunCompilerProcess(config, info);
Expand Down
49 changes: 48 additions & 1 deletion src/WebCompiler/Config/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using WebCompiler.Helpers;

namespace WebCompiler
{
Expand Down Expand Up @@ -56,6 +57,8 @@ public class Config

internal string Output { get; set; }

internal bool GlobalMatch { get; set; }

/// <summary>
/// Converts the relative input file to an absolute file path.
/// </summary>
Expand Down Expand Up @@ -188,5 +191,49 @@ private static bool DictionaryEqual<TKey, TValue>(
}
return true;
}

internal Config Match(string folder, string sourceFile)
{
if (sourceFile == null)
return null;

string inputFile = Path.Combine(folder, this.InputFile);

if (!GlobHelper.IsGlobPattern(this.InputFile))
return sourceFile.Equals(inputFile.Replace('/', '\\'), System.StringComparison.OrdinalIgnoreCase)
? this : null;

if (GlobHelper.Glob(sourceFile, inputFile))
return MakeMatchedConfig(sourceFile);

return null;
}

Config MakeMatchedConfig(string sourceFile)
{
string compileExtension = CompileHelper.GetCompiledExtension(sourceFile);
return new Config()
{
InputFile = sourceFile,
OutputFile = Path.ChangeExtension(sourceFile, compileExtension),
FileName = this.FileName,
IncludeInProject = this.IncludeInProject,
Minify = this.Minify,
Options = this.Options,
Output = this.Output,
SourceMap = this.SourceMap
};
}

internal IEnumerable<Config> Match(string folder)
{
return Directory.EnumerateFiles(folder, this.InputFile, SearchOption.AllDirectories)
.Select(s =>
{
Config config = MakeMatchedConfig(s);
config.GlobalMatch = true;
return config;
});
}
}
}
}
36 changes: 24 additions & 12 deletions src/WebCompiler/Config/ConfigFileProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.IO;
using System.Linq;
using System.Text;
using WebCompiler.Helpers;

namespace WebCompiler
{
Expand All @@ -21,7 +22,7 @@ public class ConfigFileProcessor
/// <param name="configs">Optional configuration items in the config file</param>
/// <param name="force">Forces compilation of all config items.</param>
/// <returns>A list of compiler results.</returns>
public IEnumerable<CompilerResult> Process(string configFile, IEnumerable<Config> configs = null, bool force = false)
public IEnumerable<CompilerResult> Process(string configFile, Config[] configs = null, bool force = false)
{
if (_processing.Contains(configFile))
return Enumerable.Empty<CompilerResult>();
Expand All @@ -32,18 +33,30 @@ public IEnumerable<CompilerResult> Process(string configFile, IEnumerable<Config
try
{
FileInfo info = new FileInfo(configFile);
string directory = info.Directory.FullName;
configs = configs ?? ConfigHandler.GetConfigs(configFile);

if (configs.Any())
OnConfigProcessed(configs.First(), 0, configs.Count());
if (configs.Length > 0)
OnConfigProcessed(configs.First(), 0, configs.Length);

int i = 0;
foreach (Config config in configs)
{
++i;

if (force || config.CompilationRequired())
{
var result = ProcessConfig(info.Directory.FullName, config);
list.Add(result);
OnConfigProcessed(config, list.Count, configs.Count());
if (GlobHelper.IsGlobPattern(config.InputFile))
{
foreach (Config matchedConfig in config.Match(directory))
list.Add(ProcessConfig(directory, matchedConfig));
}
else
{
list.Add(ProcessConfig(directory, config));
}

OnConfigProcessed(config, i, configs.Length);
}
}
}
Expand Down Expand Up @@ -112,12 +125,11 @@ private IEnumerable<CompilerResult> SourceFileChanged(string configFile,
// Compile if the file if it's referenced directly in compilerconfig.json
foreach (Config config in configs)
{
string input = Path.Combine(folder, config.InputFile.Replace("/", "\\"));

if (input.Equals(sourceFile, StringComparison.OrdinalIgnoreCase))
Config matchingConfig = config.Match(folder, sourceFile);
if (matchingConfig != null)
{
list.Add(ProcessConfig(folder, config));
compiledFiles.Add(input.ToLowerInvariant());
list.Add(ProcessConfig(folder, matchingConfig));
compiledFiles.Add(matchingConfig.InputFile.ToLowerInvariant());
}
}

Expand Down Expand Up @@ -191,7 +203,7 @@ private CompilerResult ProcessConfig(string baseFolder, Config config)

var result = compiler.Compile(config);

if (result.Errors.Any(e => !e.IsWarning))
if (result.Errors.Any(e => !e.IsWarning) || string.IsNullOrWhiteSpace(result.CompiledContent))
return result;

if (Path.GetExtension(config.OutputFile).Equals(".css", StringComparison.OrdinalIgnoreCase) && AdjustRelativePaths(config))
Expand Down
7 changes: 3 additions & 4 deletions src/WebCompiler/Config/ConfigHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,15 @@ public void CreateDefaultsFile(string fileName)
/// </summary>
/// <param name="fileName">A relative or absolute file path to the configuration file.</param>
/// <returns>A list of Config objects.</returns>
public static IEnumerable<Config> GetConfigs(string fileName)
public static Config[] GetConfigs(string fileName)
{
FileInfo file = new FileInfo(fileName);

if (!file.Exists)
return Enumerable.Empty<Config>();
return new Config[0];

string content = File.ReadAllText(fileName);
var configs = JsonConvert.DeserializeObject<IEnumerable<Config>>(content);
string folder = Path.GetDirectoryName(file.FullName);
Config[] configs = JsonConvert.DeserializeObject<Config[]>(content);

foreach (Config config in configs)
{
Expand Down
39 changes: 39 additions & 0 deletions src/WebCompiler/Helpers/CompileHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebCompiler.Helpers
{
public static class CompileHelper
{
/// <summary>
///
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string GetCompiledExtension(string filename)
{
string extension = Path.GetExtension(filename).ToLowerInvariant();
switch (extension)
{
case ".coffee":
case ".iced":
case ".litcoffee":
case ".jsx":
case ".es6":
case ".hbs":
case ".handlebars":
return ".js";

case ".js":
return ".es5.js";

default:
return ".css";
}
}
}
}
43 changes: 43 additions & 0 deletions src/WebCompiler/Helpers/GlobHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace WebCompiler.Helpers
{
/// <summary>
/// Utils for glob matching
/// </summary>
public static class GlobHelper
{
/// <summary>
/// Returns true if the input text contains a basic glob character: *?
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool IsGlobPattern(string text)
{
return text != null && text.LastIndexOfAny(new char[] { '*', '?' }) >= 0;
}

/// <summary>
/// String matching including basic glob patterns: *?
/// </summary>
/// <param name="text">string to be matched</param>
/// <param name="pattern">pattern to match against</param>
/// <returns></returns>
public static bool Glob(this string text, string pattern)
{
StringBuilder sb = new StringBuilder(pattern, pattern.Length + 10);
sb.Replace('*', (char)1).Replace('?', (char)2).Replace('/', '\\');

pattern = Regex.Escape(sb.ToString());

sb.Clear().Append('^').Append(pattern).Replace("\u0001", ".*").Replace("\u0002", ".").Append('$');

return Regex.IsMatch(text, sb.ToString(), RegexOptions.IgnoreCase);
}
}
}
6 changes: 3 additions & 3 deletions src/WebCompiler/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ private static void EventHookups(ConfigFileProcessor processor, string configPat
FileMinifier.AfterWritingGzipFile += (s, e) => { Console.WriteLine($" \x1B[32mGZipped"); };
}

private static IEnumerable<Config> GetConfigs(string configPath, string file)
private static Config[] GetConfigs(string configPath, string file)
{
var configs = ConfigHandler.GetConfigs(configPath);

Expand All @@ -60,9 +60,9 @@ private static IEnumerable<Config> GetConfigs(string configPath, string file)
if (file != null)
{
if (file.StartsWith("*"))
configs = configs.Where(c => Path.GetExtension(c.InputFile).Equals(file.Substring(1), StringComparison.OrdinalIgnoreCase));
configs = configs.Where(c => Path.GetExtension(c.InputFile).Equals(file.Substring(1), StringComparison.OrdinalIgnoreCase)).ToArray();
else
configs = configs.Where(c => c.InputFile.Equals(file, StringComparison.OrdinalIgnoreCase));
configs = configs.Where(c => c.InputFile.Equals(file, StringComparison.OrdinalIgnoreCase)).ToArray();
}

return configs;
Expand Down
4 changes: 1 addition & 3 deletions src/WebCompilerTest/Config/ConfigHandlerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,9 @@ public void AddConfig()
[TestMethod, TestCategory("Config")]
public void NonExistingConfigFileShouldReturnEmptyList()
{
var expectedResult = Enumerable.Empty<WebCompiler.Config>();

var result = ConfigHandler.GetConfigs("../NonExistingFile.config");

Assert.AreEqual(expectedResult, result);
Assert.AreEqual(0, result.Length);
}
}
}
1 change: 1 addition & 0 deletions src/WebCompilerTest/Minify/artifacts/css/minify.less
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
body {
background: black
}
6 changes: 6 additions & 0 deletions src/WebCompilerVsix/Adornments/AdornmentProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using WebCompiler.Helpers;

namespace WebCompilerVsix
{
Expand Down Expand Up @@ -101,6 +102,11 @@ private void CreateAdornments(ITextDocument document, IWpfTextView textView)

foreach (Config config in configs)
{
if (GlobHelper.IsGlobPattern(config.InputFile))
{
continue;
}

if (config.GetAbsoluteOutputFile().FullName.Equals(normalizedFilePath, StringComparison.OrdinalIgnoreCase))
{
GeneratedAdornment generated = new GeneratedAdornment(textView, _isVisible, _initOpacity);
Expand Down
12 changes: 2 additions & 10 deletions src/WebCompilerVsix/Commands/CreateConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using WebCompiler;
using WebCompiler.Helpers;

namespace WebCompilerVsix
{
Expand Down Expand Up @@ -163,16 +164,7 @@ private static Config CreateConfigFile(string inputfile, string outputFile)

private static string GetOutputFileName(string inputFile)
{
string extension = Path.GetExtension(inputFile).ToLowerInvariant();
string ext = ".css";

if (extension == ".coffee" || extension == ".iced" || extension == ".litcoffee" || extension == ".jsx" || extension == ".es6" || extension == ".hbs" || extension == ".handlebars")
ext = ".js";

if (extension == ".js")
ext = ".es5.js";

return Path.ChangeExtension(inputFile, ext);
return Path.ChangeExtension(inputFile, CompileHelper.GetCompiledExtension(inputFile));
}
}
}
2 changes: 1 addition & 1 deletion src/WebCompilerVsix/CompilerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ private static void ConfigProcessed(object sender, ConfigProcessedEventArgs e)
_dte.StatusBar.Progress(true, "Compiling...", e.AmountProcessed, e.Total);
}

public static void Process(string configFile, IEnumerable<Config> configs = null, bool force = false)
public static void Process(string configFile, Config[] configs = null, bool force = false)
{
ThreadPool.QueueUserWorkItem((o) =>
{
Expand Down