public async Task<CompileResult> CompileFile(FileInfo file, CompilerConfiguration compilerConfig)
{
if (file == null) { throw new ArgumentNullException("file"); }
if (compilerConfig == null) { throw new ArgumentNullException("compilerConfig"); }
var compiler = compilerConfig.GetCompiler(file.Name);
if (compiler == null)
{
throw new InvalidOperationException("Compiler could not be found for '" + file.Extension + "' type file");
}
ICompiler minCompiler = null;
string minFileName = null;
if (_minimise)
{
minFileName = Path.GetFileNameWithoutExtension(file.Name) + _compileExtension + ".min";
minCompiler = compilerConfig.GetCompiler(minFileName);
if (minCompiler == null)
{
throw new InvalidOperationException("Minimising compiler could not be found for '" + _compileExtension + "' type file");
}
}
// First step is grab the file contents, then continue
// Do the initial compile
var fileData = file.Exists ? AttemptRead(file.FullName) : string.Empty;
var output = string.Empty;
var deps = new List<string>();
bool hasErrored = false;
if (!string.IsNullOrEmpty(fileData))
{
var stopwatch = new Stopwatch();
stopwatch.Start();
try
{
var compileResult = await compiler.Compile(fileData, file).ConfigureAwait(false);
output = compileResult.Output;
deps = compileResult.AdditionalDependencies ?? deps;
}
catch (Exception e)
{
output = "An error occurred during initial compilation: \r\n" + e.GetBaseException().Message;
hasErrored = true;
compilerConfig.HasException(e);
}
stopwatch.Stop();
compilerConfig.HasMeasurement(new CompileMeasurement
{
Compiler = compiler.GetType().Name,
File = file.FullName,
CompileTimeMilliseconds = stopwatch.ElapsedMilliseconds
});
}
// Do the minimisation if it has been selected
if (!hasErrored && _minimise && !string.IsNullOrEmpty(output))
{
var stopwatch = new Stopwatch();
stopwatch.Start();
try
{
var minResult = await minCompiler.Compile(output, null).ConfigureAwait(false);
output = minResult.Output;
if (minResult.AdditionalDependencies != null && minResult.AdditionalDependencies.Any())
{
foreach(var dep in minResult.AdditionalDependencies)
{
if (!deps.Contains(dep))
{
deps.Add(dep);
}
}
}
}
catch (Exception e)
{
output = "An error occurred during minification: \r\n" + e.GetBaseException().Message;
compilerConfig.HasException(e);
}
stopwatch.Stop();
compilerConfig.HasMeasurement(new CompileMeasurement
{
Compiler = minCompiler.GetType().Name,
File = minFileName,
CompileTimeMilliseconds = stopwatch.ElapsedMilliseconds
});
}
return new CompileResult
{
Output = output,
AdditionalDependencies = deps
};
}